├── cmake ├── cable │ ├── .gitignore │ ├── toolchains │ │ ├── default.cmake │ │ ├── cxx14.cmake │ │ ├── cxx17.cmake │ │ ├── cxx11.cmake │ │ ├── cxx14-pic.cmake │ │ ├── cxx17-pic.cmake │ │ ├── cxx11-pic.cmake │ │ ├── cxx14-32bit.cmake │ │ ├── cxx17-32bit.cmake │ │ ├── cxx11-32bit.cmake │ │ ├── cxx11-c99.cmake │ │ ├── cxx11-fpic.cmake │ │ ├── mips64.cmake │ │ └── powerpc64.cmake │ ├── buildinfo │ │ ├── buildinfo.sh.in │ │ ├── buildinfo.ps1.in │ │ ├── buildinfo.json.in │ │ ├── version.h.in │ │ ├── buildinfo.h.in │ │ ├── buildinfo.c.in │ │ ├── gitinfo.cmake │ │ └── buildinfo.cmake │ ├── defaults │ │ ├── HunterCacheServers-passwords.cmake │ │ └── HunterCacheServers.cmake │ ├── CableToolchains.cmake │ ├── CablePackage.cmake │ ├── CableBuildType.cmake │ ├── cable.cmake │ ├── bootstrap.cmake │ ├── README.md │ └── CableBuildInfo.cmake ├── toolbox_limit.patch ├── libmd4c_no_md2html.patch ├── FindBip3x.cmake ├── FindScrypt.cmake ├── FindSnappy.cmake ├── FindLevelDB.cmake ├── FindToolbox.cmake ├── FindEthash.cmake ├── FindSecp256k1.cmake ├── FindBoostCertify.cmake ├── arm-apple-darwin21.cmake ├── x86_64-apple-darwin20.cmake ├── x86_64-w64-mingw32.cmake ├── ProjectMPIR.cmake ├── ProjectScrypt.cmake ├── ProjectCryptoPP.cmake ├── ProjectBoostCertify.cmake ├── ProjectEthash.cmake ├── ProjectSecp256k1.cmake ├── ProjectToolbox.cmake ├── ProjectLibFF.cmake ├── secp256k1 │ └── CMakeLists.txt ├── ProjectLevelDB.cmake ├── ProjectBip3x.cmake ├── ProjectLibmd4c.cmake ├── ProjectSnappy.cmake ├── certifyPatch.patch ├── FindCryptoPP.cmake ├── bip3x_strings_fix.patch ├── WindowsLibraries.cmake └── web3cpp_install.patch ├── include └── web3cpp │ ├── version.h.in │ ├── devcrypto │ ├── Exceptions.h │ ├── AES.h │ ├── Hash.h │ ├── Blake2.h │ └── CryptoPP.h │ ├── devcore │ ├── TrieHash.h │ ├── Address.h │ ├── FileSystem.h │ ├── Base64.h │ ├── StateCacheDB.h │ ├── Assertions.h │ ├── Exceptions.h │ ├── SHA3.h │ ├── TrieCommon.h │ └── Guards.h │ ├── Net.h │ ├── ledger │ ├── comms.h │ └── ledger.h │ ├── Bip39.h │ ├── Cipher.h │ ├── Web3.h │ ├── ethcore │ ├── ABI.h │ └── Exceptions.h │ ├── Provider.h │ ├── Error.h │ ├── DB.h │ └── Account.h ├── .gitignore ├── src ├── devcore │ ├── Guards.cpp │ ├── Address.cpp │ ├── SHA3.cpp │ ├── FixedHash.cpp │ ├── FileSystem.cpp │ ├── CommonData.cpp │ ├── TrieCommon.cpp │ ├── TrieHash.cpp │ ├── StateCacheDB.cpp │ └── Common.cpp ├── Web3.cpp ├── Bip39.cpp ├── devcrypto │ └── AES.cpp ├── Account.cpp ├── Provider.cpp ├── Error.cpp └── DB.cpp ├── tests ├── net.cpp ├── utils.cpp ├── cipher.cpp ├── SolidityTest.json ├── provider.cpp └── ArrayTest.json └── README.md /cmake/cable/.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | -------------------------------------------------------------------------------- /include/web3cpp/version.h.in: -------------------------------------------------------------------------------- 1 | #define PROJECT_VERSION "@PROJECT_VERSION@" 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | .directory 3 | *.kate-swp 4 | .vscode/*.* 5 | include/web3cpp/version.h 6 | docs/ 7 | deps/ -------------------------------------------------------------------------------- /cmake/cable/toolchains/default.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | -------------------------------------------------------------------------------- /cmake/cable/buildinfo/buildinfo.sh.in: -------------------------------------------------------------------------------- 1 | PROJECT_NAME='@PROJECT_NAME@' 2 | PROJECT_VERSION='@PROJECT_VERSION@' 3 | PROJECT_VERSION_IS_PRERELEASE='@PROJECT_VERSION_IS_PRERELEASE@' 4 | SYSTEM_NAME='@SYSTEM_NAME@' 5 | SYSTEM_PROCESSOR='@SYSTEM_PROCESSOR@' 6 | -------------------------------------------------------------------------------- /cmake/toolbox_limit.patch: -------------------------------------------------------------------------------- 1 | --- a/src/data/bytes_data.cpp 2 | +++ b/src/data/bytes_data.cpp 3 | @@ -14,6 +14,7 @@ 4 | #include 5 | #include 6 | #include 7 | +#include 8 | 9 | using namespace toolbox::data; 10 | 11 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/cxx14.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2019 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | set(CMAKE_CXX_STANDARD 14) 6 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 7 | set(CMAKE_CXX_EXTENSIONS OFF) 8 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/cxx17.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2019 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | set(CMAKE_CXX_STANDARD 17) 6 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 7 | set(CMAKE_CXX_EXTENSIONS OFF) 8 | -------------------------------------------------------------------------------- /cmake/cable/buildinfo/buildinfo.ps1.in: -------------------------------------------------------------------------------- 1 | $env:project_name="@PROJECT_NAME@" 2 | $env:project_version="@PROJECT_VERSION@" 3 | $env:project_version_is_prerelease="@PROJECT_VERSION_IS_PRERELEASE@" 4 | $env:system_name='@SYSTEM_NAME@' 5 | $env:system_processor='@SYSTEM_PROCESSOR@' 6 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/cxx11.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | 5 | set(CMAKE_CXX_STANDARD 11) 6 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 7 | set(CMAKE_CXX_EXTENSIONS OFF) 8 | -------------------------------------------------------------------------------- /src/devcore/Guards.cpp: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #include 6 | using namespace dev; 7 | 8 | namespace dev 9 | { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /cmake/libmd4c_no_md2html.patch: -------------------------------------------------------------------------------- 1 | diff --git a/CMakeLists.txt b/CMakeLists.txt 2 | index cab797e..1f81c38 100644 3 | --- a/CMakeLists.txt 4 | +++ b/CMakeLists.txt 5 | @@ -56,4 +56,4 @@ endif() 6 | include(GNUInstallDirs) 7 | 8 | add_subdirectory(src) 9 | -add_subdirectory(md2html) 10 | +## add_subdirectory(md2html) 11 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/cxx14-pic.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2019 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | set(CMAKE_CXX_STANDARD 14) 6 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 7 | set(CMAKE_CXX_EXTENSIONS OFF) 8 | 9 | set(CMAKE_POSITION_INDEPENDENT_CODE ON) 10 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/cxx17-pic.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2019 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | set(CMAKE_CXX_STANDARD 17) 6 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 7 | set(CMAKE_CXX_EXTENSIONS OFF) 8 | 9 | set(CMAKE_POSITION_INDEPENDENT_CODE ON) 10 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/cxx11-pic.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | 5 | set(CMAKE_CXX_STANDARD 11) 6 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 7 | set(CMAKE_CXX_EXTENSIONS OFF) 8 | 9 | set(CMAKE_POSITION_INDEPENDENT_CODE ON) 10 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/cxx14-32bit.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2019 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | set(CMAKE_CXX_STANDARD 14) 6 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 7 | set(CMAKE_CXX_EXTENSIONS OFF) 8 | 9 | set(CMAKE_C_FLAGS_INIT -m32) 10 | set(CMAKE_CXX_FLAGS_INIT -m32) 11 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/cxx17-32bit.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2019 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | set(CMAKE_CXX_STANDARD 17) 6 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 7 | set(CMAKE_CXX_EXTENSIONS OFF) 8 | 9 | set(CMAKE_C_FLAGS_INIT -m32) 10 | set(CMAKE_CXX_FLAGS_INIT -m32) 11 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/cxx11-32bit.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018-2019 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | set(CMAKE_CXX_STANDARD 11) 6 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 7 | set(CMAKE_CXX_EXTENSIONS OFF) 8 | 9 | set(CMAKE_C_FLAGS_INIT -m32) 10 | set(CMAKE_CXX_FLAGS_INIT -m32) 11 | -------------------------------------------------------------------------------- /cmake/cable/buildinfo/buildinfo.json.in: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@PROJECT_NAME@", 3 | "version": "@PROJECT_VERSION@", 4 | "is_prerelease": @PROJECT_VERSION_IS_PRERELEASE@, 5 | "commit": "@GIT_COMMIT_HASH@", 6 | "branch": "@GIT_BRANCH@", 7 | "repo": "@GIT_ORIGIN_URL@", 8 | "system_name": "@SYSTEM_NAME@", 9 | "system_processor": "@SYSTEM_PROCESSOR@" 10 | } 11 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/cxx11-c99.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | 5 | set(CMAKE_CXX_STANDARD 11) 6 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 7 | set(CMAKE_CXX_EXTENSIONS OFF) 8 | 9 | set(CMAKE_C_STANDARD 99) 10 | set(CMAKE_C_EXTENSIONS OFF) 11 | -------------------------------------------------------------------------------- /src/devcore/Address.cpp: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | #include 5 | 6 | namespace dev 7 | { 8 | Address const ZeroAddress; 9 | Address const MaxAddress{"0xffffffffffffffffffffffffffffffffffffffff"}; 10 | Address const SystemAddress{"0xfffffffffffffffffffffffffffffffffffffffe"}; 11 | } 12 | -------------------------------------------------------------------------------- /cmake/cable/buildinfo/version.h.in: -------------------------------------------------------------------------------- 1 | /* Cable: CMake Bootstrap Library. 2 | * Copyright 2019 Pawel Bylica. 3 | * Licensed under the Apache License, Version 2.0. 4 | */ 5 | 6 | /* Generated by Cable Build Info on @TIMESTAMP@. Do not modify directly. */ 7 | 8 | #pragma once 9 | 10 | #define @PROJECT_NAME_UPPERCASE@_VERSION "@PROJECT_VERSION@" 11 | 12 | #ifdef __cplusplus 13 | constexpr auto @PROJECT_NAME@_version = "@PROJECT_VERSION@"; 14 | #endif 15 | -------------------------------------------------------------------------------- /include/web3cpp/devcrypto/Exceptions.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | 6 | #pragma once 7 | 8 | #include 9 | 10 | namespace dev 11 | { 12 | namespace crypto 13 | { 14 | 15 | /// Rare malfunction of cryptographic functions. 16 | DEV_SIMPLE_EXCEPTION(CryptoException); 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/cxx11-fpic.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | 5 | set(CMAKE_CXX_STANDARD 11) 6 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 7 | set(CMAKE_CXX_EXTENSIONS OFF) 8 | 9 | set(CMAKE_POSITION_INDEPENDENT_CODE ON) 10 | 11 | set(CMAKE_CXX_FLAGS_INIT "-fPIC" CACHE STRING "" FORCE) 12 | set(CMAKE_C_FLAGS_INIT "-fPIC" CACHE STRING "" FORCE) 13 | -------------------------------------------------------------------------------- /include/web3cpp/devcrypto/AES.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | /** 5 | * AES 6 | * todo: use openssl 7 | */ 8 | 9 | #pragma once 10 | 11 | #include "Common.h" 12 | 13 | namespace dev 14 | { 15 | 16 | bytes aesDecrypt(bytesConstRef _cipher, std::string const& _password, unsigned _rounds = 2000, bytesConstRef _salt = bytesConstRef()); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /include/web3cpp/devcrypto/Hash.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | /** 5 | * The FixedHash fixed-size "hash" container type. 6 | */ 7 | 8 | #pragma once 9 | 10 | #include "web3cpp/devcore/FixedHash.h" 11 | #include "web3cpp/devcore/vector_ref.h" 12 | 13 | namespace dev 14 | { 15 | 16 | h256 sha256(bytesConstRef _input) noexcept; 17 | 18 | h160 ripemd160(bytesConstRef _input); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /cmake/FindBip3x.cmake: -------------------------------------------------------------------------------- 1 | # Find the Bip3x library and define the following variables: 2 | # BIP3X_FOUND 3 | # BIP3X_INCLUDE_DIR 4 | # BIP3X_LIBRARY 5 | 6 | include(SelectLibraryConfigurations) 7 | include(FindPackageHandleStandardArgs) 8 | 9 | find_path(BIP3X_INCLUDE_DIR NAMES bip3x/bip39.h) 10 | find_library(BIP3X_LIBRARY NAMES libbip39.a) 11 | 12 | SELECT_LIBRARY_CONFIGURATIONS(Bip3x) 13 | 14 | FIND_PACKAGE_HANDLE_STANDARD_ARGS( 15 | Bip3x DEFAULT_MSG 16 | BIP3X_LIBRARY BIP3X_INCLUDE_DIR 17 | ) 18 | 19 | mark_as_advanced(BIP3X_INCLUDE_DIR BIP3X_LIBRARY) 20 | -------------------------------------------------------------------------------- /cmake/FindScrypt.cmake: -------------------------------------------------------------------------------- 1 | # Find the Scrypt library and define the following variables: 2 | # SCRYPT_FOUND 3 | # SCRYPT_INCLUDE_DIR 4 | # SCRYPT_LIBRARY 5 | 6 | include(SelectLibraryConfigurations) 7 | include(FindPackageHandleStandardArgs) 8 | 9 | find_path(SCRYPT_INCLUDE_DIR NAMES libscrypt.h) 10 | find_library(SCRYPT_LIBRARY NAMES libscrypt.a) 11 | 12 | SELECT_LIBRARY_CONFIGURATIONS(Scrypt) 13 | 14 | FIND_PACKAGE_HANDLE_STANDARD_ARGS( 15 | Scrypt DEFAULT_MSG 16 | SCRYPT_LIBRARY SCRYPT_INCLUDE_DIR 17 | ) 18 | 19 | mark_as_advanced(SCRYPT_INCLUDE_DIR SCRYPT_LIBRARY) 20 | -------------------------------------------------------------------------------- /cmake/FindSnappy.cmake: -------------------------------------------------------------------------------- 1 | # Find the Snappy library and define the following variables: 2 | # SNAPPY_FOUND 3 | # SNAPPY_INCLUDE_DIR 4 | # SNAPPY_LIBRARY 5 | 6 | include(SelectLibraryConfigurations) 7 | include(FindPackageHandleStandardArgs) 8 | 9 | find_path(SNAPPY_INCLUDE_DIR NAMES snappy.h) 10 | find_library(SNAPPY_LIBRARY NAMES libsnappy.a) 11 | 12 | SELECT_LIBRARY_CONFIGURATIONS(Snappy) 13 | 14 | FIND_PACKAGE_HANDLE_STANDARD_ARGS( 15 | Snappy DEFAULT_MSG 16 | SNAPPY_LIBRARY SNAPPY_INCLUDE_DIR 17 | ) 18 | 19 | mark_as_advanced(SNAPPY_INCLUDE_DIR SNAPPY_LIBRARY) 20 | -------------------------------------------------------------------------------- /cmake/FindLevelDB.cmake: -------------------------------------------------------------------------------- 1 | # Find the LevelDB library and define the following variables: 2 | # LEVELDB_FOUND 3 | # LEVELDB_INCLUDE_DIR 4 | # LEVELDB_LIBRARY 5 | 6 | include(SelectLibraryConfigurations) 7 | include(FindPackageHandleStandardArgs) 8 | 9 | find_path(LEVELDB_INCLUDE_DIR NAMES leveldb/db.h) 10 | find_library(LEVELDB_LIBRARY NAMES libleveldb.a) 11 | 12 | SELECT_LIBRARY_CONFIGURATIONS(LevelDB) 13 | 14 | FIND_PACKAGE_HANDLE_STANDARD_ARGS( 15 | LevelDB DEFAULT_MSG 16 | LEVELDB_LIBRARY LEVELDB_INCLUDE_DIR 17 | ) 18 | 19 | mark_as_advanced(LEVELDB_INCLUDE_DIR LEVELDB_LIBRARY) 20 | -------------------------------------------------------------------------------- /cmake/FindToolbox.cmake: -------------------------------------------------------------------------------- 1 | # Find the Toolbox library and define the following variables: 2 | # TOOLBOX_FOUND 3 | # TOOLBOX_INCLUDE_DIR 4 | # TOOLBOX_LIBRARY 5 | 6 | include(SelectLibraryConfigurations) 7 | include(FindPackageHandleStandardArgs) 8 | 9 | find_path(TOOLBOX_INCLUDE_DIR NAMES strings.hpp) 10 | find_library(TOOLBOX_LIBRARY NAMES libtoolbox.a) 11 | 12 | SELECT_LIBRARY_CONFIGURATIONS(Toolbox) 13 | 14 | FIND_PACKAGE_HANDLE_STANDARD_ARGS( 15 | Toolbox DEFAULT_MSG 16 | TOOLBOX_LIBRARY TOOLBOX_INCLUDE_DIR 17 | ) 18 | 19 | mark_as_advanced(TOOLBOX_INCLUDE_DIR TOOLBOX_LIBRARY) 20 | -------------------------------------------------------------------------------- /cmake/FindEthash.cmake: -------------------------------------------------------------------------------- 1 | # Find the Ethash library and define the following variables: 2 | # ETHASH_FOUND 3 | # ETHASH_INCLUDE_DIR 4 | # ETHASH_LIBRARY 5 | 6 | include(SelectLibraryConfigurations) 7 | include(FindPackageHandleStandardArgs) 8 | 9 | find_path(ETHASH_INCLUDE_DIR NAMES ethash/ethash.h) 10 | find_library(ETHASH_LIBRARY NAMES libethash.a libkeccak.a) 11 | 12 | SELECT_LIBRARY_CONFIGURATIONS(Ethash) 13 | 14 | FIND_PACKAGE_HANDLE_STANDARD_ARGS( 15 | Ethash DEFAULT_MSG 16 | ETHASH_LIBRARY ETHASH_INCLUDE_DIR 17 | ) 18 | 19 | mark_as_advanced(ETHASH_INCLUDE_DIR ETHASH_LIBRARY) 20 | -------------------------------------------------------------------------------- /cmake/FindSecp256k1.cmake: -------------------------------------------------------------------------------- 1 | # Find the Secp256k1 library and define the following variables: 2 | # SECP256K1_FOUND 3 | # SECP256K1_INCLUDE_DIR 4 | # SECP256K1_LIBRARY 5 | 6 | include(SelectLibraryConfigurations) 7 | include(FindPackageHandleStandardArgs) 8 | 9 | find_path(SECP256K1_INCLUDE_DIR NAMES secp256k1.h) 10 | find_library(SECP256K1_LIBRARY NAMES libsecp256k1.a) 11 | 12 | SELECT_LIBRARY_CONFIGURATIONS(Secp256k1) 13 | 14 | FIND_PACKAGE_HANDLE_STANDARD_ARGS( 15 | Secp256k1 DEFAULT_MSG 16 | SECP256K1_LIBRARY SECP256K1_INCLUDE_DIR 17 | ) 18 | 19 | mark_as_advanced(SECP256K1_INCLUDE_DIR SECP256K1_LIBRARY) 20 | -------------------------------------------------------------------------------- /cmake/FindBoostCertify.cmake: -------------------------------------------------------------------------------- 1 | # Find the BoostCertify library and define the following variables: 2 | # BOOSTCERTIFY_FOUND 3 | # BOOSTCERTIFY_INCLUDE_DIR 4 | # BOOSTCERTIFY_LIBRARY 5 | 6 | include(SelectLibraryConfigurations) 7 | include(FindPackageHandleStandardArgs) 8 | 9 | find_path(BOOSTCERTIFY_INCLUDE_DIR NAMES boost/certify/https_verification.hpp) 10 | find_library(BOOSTCERTIFY_LIBRARY NAMES libboostcertify.a) 11 | 12 | SELECT_LIBRARY_CONFIGURATIONS(BoostCertify) 13 | 14 | FIND_PACKAGE_HANDLE_STANDARD_ARGS( 15 | BoostCertify DEFAULT_MSG 16 | BOOSTCERTIFY_LIBRARY BOOSTCERTIFY_INCLUDE_DIR 17 | ) 18 | 19 | mark_as_advanced(BOOSTCERTIFY_INCLUDE_DIR BOOSTCERTIFY_LIBRARY) 20 | -------------------------------------------------------------------------------- /cmake/cable/defaults/HunterCacheServers-passwords.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | 5 | # Hunter passwords file used by HunterCacheServers.cmake. 6 | # Do not include directly. 7 | 8 | hunter_upload_password( 9 | # REPO_OWNER + REPO = https://github.com/ethereum/hunter-cache 10 | REPO_OWNER ethereum 11 | REPO hunter-cache 12 | 13 | # USERNAME = https://github.com/hunter-cache-bot 14 | USERNAME hunter-cache-bot 15 | 16 | # PASSWORD = GitHub token saved as a secure environment variable 17 | PASSWORD "$ENV{HUNTER_CACHE_TOKEN}" 18 | ) 19 | -------------------------------------------------------------------------------- /cmake/arm-apple-darwin21.cmake: -------------------------------------------------------------------------------- 1 | # Sample toolchain file for building for Darwin inside Darwin system 2 | # 3 | 4 | set(CMAKE_SYSTEM_NAME Darwin) 5 | set(TOOLCHAIN_PREFIX arm-apple-darwin21.2.0) 6 | 7 | # cross compilers to use for C, C++ and Fortran 8 | set(CMAKE_C_COMPILER clang) 9 | set(CMAKE_CXX_COMPILER clang++) 10 | #set(CMAKE_Fortran_COMPILER ${HOMEBREW_GCC_PATH}${TOOLCHAIN_PREFIX}-gfortran-10) 11 | 12 | # target environment on the build host system 13 | set(CMAKE_FIND_ROOT_PATH /usr/lib/) 14 | 15 | # modify default behavior of FIND_XXX() commands 16 | #set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 17 | #set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 18 | #set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 19 | -------------------------------------------------------------------------------- /cmake/x86_64-apple-darwin20.cmake: -------------------------------------------------------------------------------- 1 | # Sample toolchain file for building for Darwin inside Darwin system 2 | # 3 | 4 | set(CMAKE_SYSTEM_NAME Darwin) 5 | set(TOOLCHAIN_PREFIX x86_64-apple-darwin20) 6 | 7 | # cross compilers to use for C, C++ and Fortran 8 | set(CMAKE_C_COMPILER clang) 9 | set(CMAKE_CXX_COMPILER clang++) 10 | #set(CMAKE_Fortran_COMPILER ${HOMEBREW_GCC_PATH}${TOOLCHAIN_PREFIX}-gfortran-10) 11 | 12 | # target environment on the build host system 13 | set(CMAKE_FIND_ROOT_PATH /usr/lib/) 14 | 15 | # modify default behavior of FIND_XXX() commands 16 | #set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 17 | #set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 18 | #set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 19 | -------------------------------------------------------------------------------- /src/devcore/SHA3.cpp: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | namespace dev 11 | { 12 | h256 const EmptySHA3 = sha3(bytesConstRef()); 13 | h256 const EmptyListSHA3 = sha3(rlpList()); 14 | 15 | bool sha3(bytesConstRef _input, bytesRef o_output) noexcept 16 | { 17 | if (o_output.size() != 32) 18 | return false; 19 | ethash::hash256 h = ethash::keccak256(_input.data(), _input.size()); 20 | bytesConstRef{h.bytes, 32}.copyTo(o_output); 21 | return true; 22 | } 23 | } // namespace dev 24 | -------------------------------------------------------------------------------- /src/devcore/FixedHash.cpp: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | #include 5 | #include 6 | 7 | namespace dev 8 | { 9 | 10 | std::random_device s_fixedHashEngine; 11 | 12 | h128 fromUUID(std::string const& _uuid) 13 | { 14 | try 15 | { 16 | return h128(boost::replace_all_copy(_uuid, "-", "")); 17 | } 18 | catch (...) 19 | { 20 | return h128(); 21 | } 22 | } 23 | 24 | std::string toUUID(h128 const& _uuid) 25 | { 26 | std::string ret = toHex(_uuid.ref()); 27 | for (unsigned i: {20, 16, 12, 8}) 28 | ret.insert(ret.begin() + i, '-'); 29 | return ret; 30 | } 31 | 32 | } 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /include/web3cpp/devcore/TrieHash.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #pragma once 6 | 7 | #include 8 | 9 | #include 10 | 11 | namespace dev 12 | { 13 | 14 | bytes rlp256(BytesMap const& _s); 15 | h256 hash256(BytesMap const& _s); 16 | 17 | h256 orderedTrieRoot(std::vector const& _data); 18 | 19 | template inline h256 trieRootOver(unsigned _itemCount, T const& _getKey, U const& _getValue) 20 | { 21 | BytesMap m; 22 | for (unsigned i = 0; i < _itemCount; ++i) 23 | m[_getKey(i)] = _getValue(i); 24 | return hash256(m); 25 | } 26 | 27 | h256 orderedTrieRoot(std::vector const& _data); 28 | h256 orderedTrieRoot(std::vector const& _data); 29 | 30 | } 31 | -------------------------------------------------------------------------------- /cmake/cable/buildinfo/buildinfo.h.in: -------------------------------------------------------------------------------- 1 | /* Cable: CMake Bootstrap Library. 2 | * Copyright 2018 Pawel Bylica. 3 | * Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | */ 5 | 6 | /* Generated by Cable Build Info on @TIMESTAMP@. Do not modify directly. */ 7 | 8 | #pragma once 9 | 10 | #ifdef __cplusplus 11 | extern "C" 12 | { 13 | #endif 14 | 15 | struct buildinfo 16 | { 17 | const char* project_name; 18 | const char* project_version; 19 | const char* project_name_with_version; 20 | const char* git_commit_hash; 21 | const char* git_branch; 22 | const char* system_name; 23 | const char* system_processor; 24 | const char* compiler_id; 25 | const char* compiler_version; 26 | const char* build_type; 27 | }; 28 | 29 | const struct buildinfo* @FUNCTION_NAME@(); 30 | 31 | #ifdef __cplusplus 32 | } 33 | #endif 34 | -------------------------------------------------------------------------------- /include/web3cpp/devcore/Address.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2013-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | /// @file 6 | /// This file defines Address alias for FixedHash of 160 bits and some 7 | /// special Address constants. 8 | 9 | #pragma once 10 | 11 | #include "FixedHash.h" 12 | 13 | namespace dev 14 | { 15 | 16 | /// An Ethereum address: 20 bytes. 17 | /// @NOTE This is not endian-specific; it's just a bunch of bytes. 18 | using Address = h160; 19 | 20 | /// A vector of Ethereum addresses. 21 | using Addresses = h160s; 22 | 23 | /// A hash set of Ethereum addresses. 24 | using AddressHash = std::unordered_set; 25 | 26 | /// The zero address. 27 | extern Address const ZeroAddress; 28 | 29 | /// The last address. 30 | extern Address const MaxAddress; 31 | 32 | /// The SYSTEM address. 33 | extern Address const SystemAddress; 34 | 35 | } 36 | 37 | -------------------------------------------------------------------------------- /cmake/cable/buildinfo/buildinfo.c.in: -------------------------------------------------------------------------------- 1 | /* Cable: CMake Bootstrap Library. 2 | * Copyright 2018 Pawel Bylica. 3 | * Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | */ 5 | 6 | /* Generated by Cable Build Info on @TIMESTAMP@. Do not modify directly. */ 7 | 8 | #include "buildinfo.h" 9 | 10 | const struct buildinfo* @FUNCTION_NAME@() 11 | { 12 | static const struct buildinfo buildinfo = { 13 | .project_name = "@PROJECT_NAME@", 14 | .project_version = "@PROJECT_VERSION@", 15 | .project_name_with_version = "@PROJECT_NAME@-@PROJECT_VERSION@", 16 | .git_commit_hash = "@GIT_COMMIT_HASH@", 17 | .git_branch = "@GIT_BRANCH@", 18 | .system_name = "@SYSTEM_NAME@", 19 | .system_processor = "@SYSTEM_PROCESSOR@", 20 | .compiler_id = "@COMPILER_ID@", 21 | .compiler_version = "@COMPILER_VERSION@", 22 | .build_type = "@BUILD_TYPE@", 23 | }; 24 | return &buildinfo; 25 | } 26 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/mips64.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | 5 | set(CMAKE_SYSTEM_PROCESSOR mips64) 6 | set(CMAKE_SYSTEM_NAME Linux) 7 | set(CMAKE_C_COMPILER mips64-linux-gnuabi64-gcc) 8 | set(CMAKE_CXX_COMPILER mips64-linux-gnuabi64-g++) 9 | 10 | set(CMAKE_FIND_ROOT_PATH /usr/mips64-linux-gnuabi64) 11 | SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 12 | SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 13 | SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 14 | 15 | set(CMAKE_CXX_STANDARD 11) 16 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 17 | set(CMAKE_CXX_EXTENSIONS Off) 18 | 19 | if(${CMAKE_VERSION} VERSION_LESS 3.10.0) 20 | # Until CMake 3.10 the FindThreads uses try_run() check of -pthread flag, 21 | # what causes CMake error in crosscompiling mode. Avoid the try_run() check 22 | # by specifying the result up front. 23 | set(THREADS_PTHREAD_ARG TRUE) 24 | endif() 25 | -------------------------------------------------------------------------------- /cmake/cable/toolchains/powerpc64.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | 5 | set(CMAKE_SYSTEM_PROCESSOR powerpc64) 6 | set(CMAKE_SYSTEM_NAME Linux) 7 | set(CMAKE_C_COMPILER powerpc64-linux-gnu-gcc) 8 | set(CMAKE_CXX_COMPILER powerpc64-linux-gnu-g++) 9 | 10 | set(CMAKE_FIND_ROOT_PATH /usr/powerpc64-linux-gnu) 11 | SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 12 | SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 13 | SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 14 | 15 | set(CMAKE_CXX_STANDARD 11) 16 | set(CMAKE_CXX_STANDARD_REQUIRED TRUE) 17 | set(CMAKE_CXX_EXTENSIONS OFF) 18 | 19 | if(${CMAKE_VERSION} VERSION_LESS 3.10.0) 20 | # Until CMake 3.10 the FindThreads uses try_run() check of -pthread flag, 21 | # what causes CMake error in crosscompiling mode. Avoid the try_run() check 22 | # by specifying the result up front. 23 | set(THREADS_PTHREAD_ARG TRUE) 24 | endif() 25 | -------------------------------------------------------------------------------- /cmake/x86_64-w64-mingw32.cmake: -------------------------------------------------------------------------------- 1 | # Sample toolchain file for building for Windows from an Ubuntu Linux system. 2 | # 3 | # Typical usage: 4 | # *) install cross compiler: `sudo apt-get install mingw-w64` 5 | # *) cd build 6 | # *) cmake -DCMAKE_TOOLCHAIN_FILE=/x86_64-w64-mingw32.cmake .. 7 | 8 | set(CMAKE_SYSTEM_NAME Windows) 9 | set(TOOLCHAIN_PREFIX x86_64-w64-mingw32) 10 | 11 | # cross compilers to use for C, C++ and Fortran 12 | set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc-posix) 13 | set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++-posix) 14 | set(CMAKE_Fortran_COMPILER ${TOOLCHAIN_PREFIX}-gfortran) 15 | set(CMAKE_RC_COMPILER ${TOOLCHAIN_PREFIX}-windres) 16 | 17 | # target environment on the build host system 18 | set(CMAKE_FIND_ROOT_PATH /usr/${TOOLCHAIN_PREFIX}) 19 | 20 | # modify default behavior of FIND_XXX() commands 21 | set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 22 | set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 23 | set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 24 | -------------------------------------------------------------------------------- /src/Web3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Default Constructor 4 | Web3::Web3() : 5 | defaultProvider(std::make_unique(Provider(""))), 6 | defaultPath(Utils::getDefaultDataDir()), 7 | wallet(defaultProvider, defaultPath), 8 | eth(defaultProvider) {} 9 | 10 | // Custom provider overload 11 | Web3::Web3(Provider provider) : 12 | defaultProvider(std::make_unique(provider)), 13 | defaultPath(Utils::getDefaultDataDir()), 14 | wallet(defaultProvider, defaultPath), 15 | eth(defaultProvider) {} 16 | 17 | // Custom path overload 18 | Web3::Web3(boost::filesystem::path path) : 19 | defaultProvider(std::make_unique(Provider(""))), 20 | defaultPath(path), 21 | wallet(defaultProvider, defaultPath), 22 | eth(defaultProvider) {} 23 | 24 | // Custom path & provider overload 25 | Web3::Web3(Provider provider, boost::filesystem::path path) : 26 | defaultProvider(std::make_unique(provider)), 27 | defaultPath(path), 28 | wallet(defaultProvider, defaultPath), 29 | eth(defaultProvider) {} -------------------------------------------------------------------------------- /include/web3cpp/devcrypto/Blake2.h: -------------------------------------------------------------------------------- 1 | /// Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #pragma once 6 | 7 | #include 8 | 9 | namespace dev 10 | { 11 | namespace crypto 12 | { 13 | /// Calculates the compression function F used in the BLAKE2 cryptographic hashing algorithm 14 | /// Throws exception in case input data has incorrect size. 15 | /// @param _rounds the number of rounds 16 | /// @param _stateVector the state vector - 8 unsigned 64-bit little-endian words 17 | /// @param _t0, _t1 offset counters - unsigned 64-bit little-endian words 18 | /// @param _lastBlock the final block indicator flag 19 | /// @param _messageBlock the message block vector - 16 unsigned 64-bit little-endian words 20 | /// @returns updated state vector with unchanged encoding (little-endian) 21 | bytes blake2FCompression(uint32_t _rounds, bytesConstRef _stateVector, bytesConstRef _t0, 22 | bytesConstRef _t1, bool _lastBlock, bytesConstRef _messageBlock); 23 | } 24 | } // namespace dev 25 | -------------------------------------------------------------------------------- /cmake/ProjectMPIR.cmake: -------------------------------------------------------------------------------- 1 | include(ExternalProject) 2 | 3 | set(prefix "${CMAKE_BINARY_DIR}/deps") 4 | set(MPIR_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}mpir${CMAKE_STATIC_LIBRARY_SUFFIX}") 5 | set(MPIR_INCLUDE_DIR "${prefix}/include") 6 | 7 | ExternalProject_Add(mpir 8 | PREFIX "${prefix}" 9 | DOWNLOAD_NAME mpir-cmake.tar.gz 10 | DOWNLOAD_NO_PROGRESS TRUE 11 | URL https://github.com/chfast/mpir/archive/cmake.tar.gz 12 | URL_HASH SHA256=d32ea73cb2d8115a8e59b244f96f29bad7ff03367162b660bae6495826811e06 13 | CMAKE_ARGS 14 | -DCMAKE_INSTALL_PREFIX= 15 | -DCMAKE_INSTALL_LIBDIR=lib 16 | -DCMAKE_BUILD_TYPE=Release 17 | -DMPIR_GMP=On 18 | BUILD_BYPRODUCTS "${MPIR_LIBRARY}" 19 | DOWNLOAD_EXTRACT_TIMESTAMP 1 20 | ) 21 | 22 | add_library(MPIR::mpir STATIC IMPORTED GLOBAL) 23 | set_property(TARGET MPIR::mpir PROPERTY IMPORTED_CONFIGURATIONS Release) 24 | set_property(TARGET MPIR::mpir PROPERTY IMPORTED_LOCATION_RELEASE ${MPIR_LIBRARY}) 25 | set_property(TARGET MPIR::mpir PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${MPIR_INCLUDE_DIR}) 26 | add_dependencies(MPIR::mpir mpir) 27 | -------------------------------------------------------------------------------- /cmake/cable/defaults/HunterCacheServers.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | 5 | # This module, when included, sets default values for params related to 6 | # Hunter cache servers, including upload options. 7 | 8 | # Default Hunter cache servers. 9 | set(HUNTER_CACHE_SERVERS 10 | "https://github.com/ethereum/hunter-cache;https://github.com/ingenue/hunter-cache" 11 | CACHE STRING "Hunter cache servers") 12 | 13 | # Default path to Hunter passwords file containing information how to access 14 | # Ethereum's cache server. 15 | set(HUNTER_PASSWORDS_PATH 16 | ${CMAKE_CURRENT_LIST_DIR}/HunterCacheServers-passwords.cmake 17 | CACHE STRING "Hunter passwords file") 18 | 19 | # In CI builds upload the binaries if the HUNTER_CACHE_TOKEN was decrypted 20 | # (only for branches and internal PRs). 21 | if("$ENV{CI}" AND NOT "$ENV{HUNTER_CACHE_TOKEN}" STREQUAL "") 22 | set(run_upload YES) 23 | else() 24 | set(run_upload NO) 25 | endif() 26 | option(HUNTER_RUN_UPLOAD "Upload binaries to the Hunter cache server" ${run_upload}) 27 | unset(run_upload) 28 | -------------------------------------------------------------------------------- /cmake/cable/CableToolchains.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | 5 | set(cable_toolchain_dir ${CMAKE_CURRENT_LIST_DIR}/toolchains) 6 | 7 | function(cable_configure_toolchain) 8 | if(NOT PROJECT_IS_NESTED) 9 | # Do this configuration only in the top project. 10 | 11 | cmake_parse_arguments("" "" "DEFAULT" "" ${ARGN}) 12 | 13 | set(default_toolchain default) 14 | if(_DEFAULT) 15 | set(default_toolchain ${_DEFAULT}) 16 | endif() 17 | 18 | set(TOOLCHAIN ${default_toolchain} CACHE STRING "CMake toolchain") 19 | 20 | set(toolchain_file toolchains/${TOOLCHAIN}.cmake) 21 | foreach(path ${CMAKE_MODULE_PATH}) 22 | if(EXISTS "${path}/${toolchain_file}") 23 | set(toolchain_file "${path}/${toolchain_file}") 24 | break() 25 | endif() 26 | endforeach() 27 | 28 | cable_debug("Toolchain file: ${toolchain_file}") 29 | set(CMAKE_TOOLCHAIN_FILE ${toolchain_file} CACHE FILEPATH "CMake toolchain file") 30 | endif() 31 | endfunction() 32 | -------------------------------------------------------------------------------- /include/web3cpp/devcore/FileSystem.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #pragma once 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | namespace dev 13 | { 14 | 15 | /// Sets the data dir for the default ("ethereum") prefix. 16 | void setDataDir(boost::filesystem::path const& _dir); 17 | /// @returns the path for user data. 18 | boost::filesystem::path getDataDir(std::string _prefix = "ethereum"); 19 | /// @returns the default path for user data, ignoring the one set by `setDataDir`. 20 | boost::filesystem::path getDefaultDataDir(std::string _prefix = "ethereum"); 21 | /// Sets the ipc socket dir 22 | void setIpcPath(boost::filesystem::path const& _ipcPath); 23 | /// @returns the ipc path (default is DataDir) 24 | boost::filesystem::path getIpcPath(); 25 | 26 | /// @returns a new path whose file name is suffixed with the given suffix. 27 | boost::filesystem::path appendToFilename(boost::filesystem::path const& _orig, std::string const& _suffix); 28 | 29 | } 30 | -------------------------------------------------------------------------------- /cmake/ProjectScrypt.cmake: -------------------------------------------------------------------------------- 1 | include(ExternalProject) 2 | 3 | if (MSVC) 4 | set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) 5 | endif() 6 | 7 | set(prefix "${CMAKE_BINARY_DIR}/deps") 8 | set(SCRYPT_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}scrypt${CMAKE_STATIC_LIBRARY_SUFFIX}") 9 | set(SCRYPT_INCLUDE_DIR "${prefix}/include") 10 | 11 | ExternalProject_Add( 12 | libscrypt 13 | PREFIX "${prefix}" 14 | DOWNLOAD_NO_PROGRESS 1 15 | GIT_REPOSITORY https://github.com/itamarcps/libscrypt 16 | UPDATE_DISCONNECTED true 17 | BUILD_IN_SOURCE true 18 | CONFIGURE_COMMAND "" 19 | BUILD_COMMAND make PREFIX=${prefix} 20 | INSTALL_COMMAND make install install-static PREFIX=${prefix} 21 | LOG_CONFIGURE 1 22 | LOG_BUILD 1 23 | LOG_INSTALL 1 24 | BUILD_BYPRODUCTS "${SCRYPT_LIBRARY}" 25 | DOWNLOAD_EXTRACT_TIMESTAMP 1 26 | ) 27 | 28 | add_library(scrypt STATIC IMPORTED GLOBAL) 29 | file(MAKE_DIRECTORY "${SCRYPT_INCLUDE_DIR}") # Must exist. 30 | set_property(TARGET scrypt PROPERTY IMPORTED_CONFIGURATIONS Release) 31 | set_property(TARGET scrypt PROPERTY IMPORTED_LOCATION_RELEASE "${SCRYPT_LIBRARY}") 32 | set_property(TARGET scrypt PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${SCRYPT_INCLUDE_DIR}") 33 | 34 | -------------------------------------------------------------------------------- /cmake/cable/CablePackage.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library 2 | # Copyright 2019-2020 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | # Cable Package, version 1.0.0 6 | # 7 | # This CMake module provides default configuration for CPack 8 | # 9 | # CHANGELOG 10 | # 11 | # 1.0.0 - 2020-05-06 12 | 13 | if(cable_package_included) 14 | return() 15 | endif() 16 | set(cable_package_included TRUE) 17 | 18 | # Configures CPack to build the archive package. 19 | macro(cable_add_archive_package) 20 | if(WIN32) 21 | set(CPACK_GENERATOR ZIP) 22 | set(CPACK_SOURCE_GENERATOR ZIP) 23 | else() 24 | set(CPACK_GENERATOR TGZ) 25 | set(CPACK_SOURCE_GENERATOR TGZ) 26 | endif() 27 | string(TOLOWER ${CMAKE_SYSTEM_NAME} system_name) 28 | string(TOLOWER ${CMAKE_SYSTEM_PROCESSOR} system_processor) 29 | set(CPACK_PACKAGE_FILE_NAME ${PROJECT_NAME}-${PROJECT_VERSION}-${system_name}-${system_processor}) 30 | set(CPACK_SOURCE_PACKAGE_FILE_NAME ${PROJECT_NAME}-${PROJECT_VERSION}-source) 31 | set(CPACK_PACKAGE_CHECKSUM SHA256) 32 | set(CPACK_INCLUDE_TOPLEVEL_DIRECTORY FALSE) 33 | unset(system_name) 34 | unset(system_processor) 35 | include(CPack) 36 | endmacro() 37 | -------------------------------------------------------------------------------- /src/Bip39.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bip3x::Bip39Mnemonic::MnemonicResult BIP39::createNewMnemonic() { 4 | return bip3x::Bip39Mnemonic::generate(); 5 | } 6 | 7 | bip3x::HDKey BIP39::createKey(std::string &phrase, std::string derivPath) { 8 | bip3x::bytes_64 seed = bip3x::HDKeyEncoder::makeBip39Seed(phrase); 9 | bip3x::HDKey rootKey = bip3x::HDKeyEncoder::makeBip32RootKey(seed); 10 | bip3x::HDKeyEncoder::makeExtendedKey(rootKey, derivPath); 11 | return rootKey; 12 | } 13 | 14 | bool BIP39::wordExists(std::string word) { 15 | struct words* wordlist; 16 | bip39_get_wordlist(NULL, &wordlist); 17 | size_t idx = wordlist_lookup_word(wordlist, word); 18 | return (idx != 0); 19 | } 20 | 21 | std::vector> BIP39::generateAccountsFromSeed( 22 | std::string &seed, std::string derivPath, int64_t index 23 | ) { 24 | std::vector> ret; 25 | for (int64_t i = 0; i < 10; ++i, ++index) { 26 | std::string address; 27 | std::string deriv = derivPath + boost::lexical_cast(index); 28 | bip3x::HDKey rootKey = BIP39::createKey(seed, deriv); 29 | dev::KeyPair k(dev::Secret::frombip3x(rootKey.privateKey)); 30 | address += "0x" + k.address().hex(); 31 | ret.push_back(std::make_pair(address, deriv)); 32 | } 33 | return ret; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /tests/net.cpp: -------------------------------------------------------------------------------- 1 | #include "../src/libs/catch2/catch_amalgamated.hpp" 2 | #include "../include/web3cpp/Web3.h" 3 | #include "Tests.h" 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | using Catch::Matchers::Equals; 11 | 12 | namespace TNet 13 | { 14 | TEST_CASE("Standard HTTP Request") 15 | { 16 | SECTION("Normal HTTP Request") 17 | { 18 | std::unique_ptrweb3 = std::make_unique(); 19 | json reqBody = RPC::eth_blockNumber(); 20 | std::string reqStr = Net::HTTPRequest( 21 | web3->getProvider(), Net::RequestTypes::POST, reqBody.dump()); 22 | json respObj = json::parse(reqStr); 23 | 24 | REQUIRE(!respObj.count("error")); 25 | } 26 | } 27 | 28 | TEST_CASE("Custom HTTP Request") 29 | { 30 | SECTION("Custom HTTP Request") 31 | { 32 | std::string host = "api.avax.network"; 33 | std::string port = "443"; 34 | std::string target = "/ext/bc/C/rpc"; 35 | std::string reqType = "POST"; 36 | std::string reqCont = "application/json"; 37 | json reqBody = RPC::eth_blockNumber(); 38 | std::string reqStr = Net::customHTTPRequest( 39 | reqBody.dump(), host, port, target, reqType, reqCont); 40 | json respObj = json::parse(reqStr); 41 | 42 | REQUIRE(!respObj.count("error")); 43 | } 44 | } 45 | 46 | } -------------------------------------------------------------------------------- /src/devcrypto/AES.cpp: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | using namespace dev; 13 | using namespace dev::crypto; 14 | 15 | bytes dev::aesDecrypt(bytesConstRef _ivCipher, std::string const& _password, unsigned _rounds, bytesConstRef _salt) 16 | { 17 | bytes pw = asBytes(_password); 18 | 19 | if (!_salt.size()) 20 | _salt = &pw; 21 | 22 | bytes target(64); 23 | CryptoPP::PKCS5_PBKDF2_HMAC().DeriveKey(target.data(), target.size(), 0, pw.data(), pw.size(), _salt.data(), _salt.size(), _rounds); 24 | 25 | try 26 | { 27 | CryptoPP::AES::Decryption aesDecryption(target.data(), 16); 28 | auto cipher = _ivCipher.cropped(16); 29 | auto iv = _ivCipher.cropped(0, 16); 30 | CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, iv.data()); 31 | std::string decrypted; 32 | CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink(decrypted)); 33 | stfDecryptor.Put(cipher.data(), cipher.size()); 34 | stfDecryptor.MessageEnd(); 35 | return asBytes(decrypted); 36 | } 37 | catch (std::exception const& e) 38 | { 39 | // FIXME: Handle this error better. 40 | std::cerr << e.what() << '\n'; 41 | return bytes(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /cmake/ProjectCryptoPP.cmake: -------------------------------------------------------------------------------- 1 | include(ExternalProject) 2 | 3 | if (MSVC) 4 | set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) 5 | endif() 6 | 7 | set(prefix "${CMAKE_BINARY_DIR}/deps") 8 | set(CRYPTOPP_ROOT_DIR "${prefix}") 9 | set(CRYPTOPP_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}cryptopp${CMAKE_STATIC_LIBRARY_SUFFIX}") 10 | set(CRYPTOPP_INCLUDE_DIR "${prefix}/include") 11 | 12 | ExternalProject_Add( 13 | CryptoPP 14 | PREFIX "${prefix}" 15 | DOWNLOAD_NAME cryptopp-8.2.0.tar.gz 16 | DOWNLOAD_NO_PROGRESS 1 17 | URL https://github.com/weidai11/cryptopp/releases/download/CRYPTOPP_8_7_0/cryptopp870.zip 18 | URL_HASH SHA256=d0d3a28fcb5a1f6ed66b3adf57ecfaed234a7e194e42be465c2ba70c744538dd 19 | UPDATE_DISCONNECTED true 20 | BUILD_IN_SOURCE true 21 | CMAKE_ARGS -DNDEBUG 22 | CONFIGURE_COMMAND "" 23 | BUILD_COMMAND make static PREFIX=${prefix} CXXFLAGS=-std=c++${CMAKE_CXX_STANDARD} -j8 24 | INSTALL_COMMAND make install-lib PREFIX=${prefix} 25 | DOWNLOAD_EXTRACT_TIMESTAMP 1 26 | LOG_CONFIGURE 1 27 | LOG_BUILD 1 28 | LOG_INSTALL 1 29 | BUILD_BYPRODUCTS "${CRYPTOPP_LIBRARY}" 30 | ) 31 | 32 | add_library(cryptopp STATIC IMPORTED GLOBAL) 33 | file(MAKE_DIRECTORY "${CRYPTOPP_INCLUDE_DIR}") # Must exist. 34 | set_property(TARGET cryptopp PROPERTY IMPORTED_CONFIGURATIONS Release) 35 | set_property(TARGET cryptopp PROPERTY IMPORTED_LOCATION_RELEASE "${CRYPTOPP_LIBRARY}") 36 | set_property(TARGET cryptopp PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${CRYPTOPP_INCLUDE_DIR}") 37 | add_dependencies(cryptopp CryptoPP) 38 | -------------------------------------------------------------------------------- /include/web3cpp/devcore/Base64.h: -------------------------------------------------------------------------------- 1 | /* 2 | base64.cpp and base64.h 3 | 4 | Copyright (C) 2004-2008 René Nyffenegger 5 | 6 | This source code is provided 'as-is', without any express or implied 7 | warranty. In no event will the author be held liable for any damages 8 | arising from the use of this software. 9 | 10 | Permission is granted to anyone to use this software for any purpose, 11 | including commercial applications, and to alter it and redistribute it 12 | freely, subject to the following restrictions: 13 | 14 | 1. The origin of this source code must not be misrepresented; you must not 15 | claim that you wrote the original source code. If you use this source code 16 | in a product, an acknowledgment in the product documentation would be 17 | appreciated but is not required. 18 | 19 | 2. Altered source versions must be plainly marked as such, and must not be 20 | misrepresented as being the original source code. 21 | 22 | 3. This notice may not be removed or altered from any source distribution. 23 | 24 | René Nyffenegger rene.nyffenegger@adp-gmbh.ch 25 | */ 26 | /// Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c 27 | /// Originally by René Nyffenegger. 28 | /// DEVified by Gav Wood. 29 | #pragma once 30 | 31 | #include "FixedHash.h" 32 | #include 33 | 34 | namespace dev 35 | { 36 | std::string toBase64(bytesConstRef _in); 37 | std::string toBase64URLSafe(bytesConstRef _in); 38 | bytes fromBase64(std::string const& _in); 39 | 40 | } // namespace dev 41 | -------------------------------------------------------------------------------- /include/web3cpp/devcrypto/CryptoPP.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | /** 5 | * CryptoPP headers and primitive helper methods 6 | */ 7 | 8 | #pragma once 9 | 10 | #include "Common.h" 11 | 12 | namespace dev 13 | { 14 | namespace crypto 15 | { 16 | /// Amount of bytes added when encrypting with encryptECIES. 17 | static const unsigned c_eciesOverhead = 113; 18 | 19 | /** 20 | * CryptoPP secp256k1 algorithms. 21 | * @todo Collect ECIES methods into class. 22 | */ 23 | class Secp256k1PP 24 | { 25 | public: 26 | static Secp256k1PP* get(); 27 | 28 | /// Encrypts text (replace input). (ECIES w/XOR-SHA1) 29 | void encrypt(Public const& _k, bytes& io_cipher); 30 | 31 | /// Decrypts text (replace input). (ECIES w/XOR-SHA1) 32 | void decrypt(Secret const& _k, bytes& io_text); 33 | 34 | /// Encrypts text (replace input). (ECIES w/AES128-CTR-SHA256) 35 | void encryptECIES(Public const& _k, bytes& io_cipher); 36 | 37 | /// Encrypts text (replace input). (ECIES w/AES128-CTR-SHA256) 38 | void encryptECIES(Public const& _k, bytesConstRef _sharedMacData, bytes& io_cipher); 39 | 40 | /// Decrypts text (replace input). (ECIES w/AES128-CTR-SHA256) 41 | bool decryptECIES(Secret const& _k, bytes& io_text); 42 | 43 | /// Decrypts text (replace input). (ECIES w/AES128-CTR-SHA256) 44 | bool decryptECIES(Secret const& _k, bytesConstRef _sharedMacData, bytes& io_text); 45 | 46 | private: 47 | Secp256k1PP() = default; 48 | }; 49 | 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /include/web3cpp/Net.h: -------------------------------------------------------------------------------- 1 | #ifndef NET_H 2 | #define NET_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include 17 | #include 18 | #include 19 | 20 | /** 21 | * Namespace for making HTTP requests. 22 | */ 23 | 24 | namespace Net { 25 | /// Enum for the request types. 26 | enum RequestTypes { POST, GET }; 27 | 28 | /** 29 | * Make an HTTP request to a given provider. 30 | * @param *provider The provider to send the request to. 31 | * @param requestType The type of network request. 32 | * @param reqBody The body of the request. 33 | * @return The response of the request as a string. 34 | */ 35 | std::string HTTPRequest( 36 | const std::unique_ptr& provider, const RequestTypes& requestType, const std::string& reqBody 37 | ); 38 | 39 | /** 40 | * Make an HTTP request to a custom target. 41 | * @param reqBody The body of the request. 42 | * @param host The host to send the request to. 43 | * @param port The port of the host to send the request to. 44 | * @param target The %RPC endpoint target of the host to send the request to. 45 | * @param requestType The type of network request. 46 | * @param contentType The type of content the request body has (e.g. "application/json"). 47 | * @return The response of the request as a string. 48 | */ 49 | std::string customHTTPRequest( 50 | const std::string& reqBody, const std::string& host, const std::string& port, 51 | const std::string& target, const std::string& requestType, const std::string& contentType 52 | ); 53 | } 54 | 55 | #endif // NET_H 56 | -------------------------------------------------------------------------------- /include/web3cpp/ledger/comms.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020-2021 AVME Developers 2 | // Distributed under the MIT/X11 software license, see the accompanying 3 | // file LICENSE or http://www.opensource.org/licenses/mit-license.php. 4 | #ifndef COMMS_H 5 | #define COMMS_H 6 | 7 | #include 8 | #include 9 | 10 | #include 11 | 12 | #include "encoding.h" 13 | 14 | namespace ledger { 15 | namespace communicationSpecs { 16 | // Struct for abstracting device specs. 17 | struct usb_device_params { 18 | unsigned short vendor_id; 19 | unsigned short product_id; 20 | }; 21 | 22 | // Array of supported Ledger devices. 23 | const std::vector ledger_devices_ids { 24 | {usb_device_params{0x2c97, 0x0001}}, // Ledger Nano S 25 | {usb_device_params{0x2c97, 0x0004}}, // Ledger Nano X 26 | {usb_device_params{0x2c97, 0x1015}}, // Ledger Nano S Ethereum App 27 | {usb_device_params{0x2c97, 0x4015}}, // Ledger Nano X Ethereum App 28 | }; 29 | } 30 | 31 | class communication { 32 | private: 33 | unsigned short ledgerVID = 0x0000; 34 | unsigned short ledgerPID = 0x0000; 35 | // https://github.com/LedgerHQ/ledger-wallet-chrome/blob/master/app/src/dongle/manager.coffee 36 | unsigned short ledgerUsagePage = 0xffa0; 37 | 38 | hid_device *device_handle; 39 | bool messageHasError(encoding::receiveBuf message); 40 | 41 | public: 42 | bool isLedgerConnected(); // Check if Ledger is connected via USB. 43 | bool isAppOpen(); // Check if Ledger is opened in App. 44 | bool isAvaxOpen(); // Check if the correct App is open on the Ledger by getting a BIP32 address. 45 | std::vector exchangeMessage( 46 | std::vector sendBufferVector 47 | ); // Exchange messages with the device. 48 | }; 49 | } 50 | 51 | #endif // COMMS_H 52 | -------------------------------------------------------------------------------- /include/web3cpp/Bip39.h: -------------------------------------------------------------------------------- 1 | #ifndef BIP3X_H 2 | #define BIP3X_H 3 | 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include 13 | 14 | #include 15 | 16 | /** 17 | * Namespace for BIP39 functions. 18 | * Abstracts functions from the [bip3x](https://github.com/itamarcps/bip3x) library. 19 | */ 20 | 21 | namespace BIP39 { 22 | /** 23 | * Generate a new random mnemonic phrase. 24 | * @return A struct that contains details about the mnemonic phrase. 25 | */ 26 | bip3x::Bip39Mnemonic::MnemonicResult createNewMnemonic(); 27 | 28 | /** 29 | * Create a public/private key pair. 30 | * @param &phrase The full BIP39 mnemonic phrase string. 31 | * @param derivPath The full derivation path (e.g. "m/44'/60'/0'/0"). 32 | * @return An object that contains details about the key pair. 33 | */ 34 | bip3x::HDKey createKey(std::string &phrase, std::string derivPath); 35 | 36 | /** 37 | * Check if a word exists in the **English** BIP39 wordlist. 38 | * @return `true` if the word exists, `false` otherwise. 39 | */ 40 | bool wordExists(std::string word); 41 | 42 | /** 43 | * Generate a list with 10 addresses based on a given seed and a starting index. 44 | * @param &phrase The full BIP39 mnemonic phrase string. 45 | * @param derivPath The derivation path **without** the last digit (e.g. "m/44'/60'/0'/0/"). 46 | * @param start The derivation index to start counting from (e.g. "10" will count from indexes 10-19). 47 | * @return A vector of pairs of generated addresses and their respective full derivation paths. 48 | */ 49 | std::vector> generateAccountsFromSeed( 50 | std::string &phrase, std::string derivPath, int64_t start 51 | ); 52 | } 53 | 54 | #endif // BIP3X_H 55 | -------------------------------------------------------------------------------- /cmake/cable/buildinfo/gitinfo.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. See the LICENSE file. 4 | 5 | # Execute git only if the tool is available. 6 | if(GIT) 7 | execute_process( 8 | COMMAND ${GIT} describe --always --long --tags --first-parent --match=v* --abbrev=40 --dirty 9 | WORKING_DIRECTORY ${SOURCE_DIR} 10 | OUTPUT_VARIABLE gitinfo 11 | OUTPUT_STRIP_TRAILING_WHITESPACE 12 | ERROR_VARIABLE error 13 | ERROR_STRIP_TRAILING_WHITESPACE 14 | ) 15 | if(error) 16 | message(WARNING "Git ${error}") 17 | endif() 18 | 19 | execute_process( 20 | COMMAND ${GIT} rev-parse --abbrev-ref HEAD 21 | WORKING_DIRECTORY ${SOURCE_DIR} 22 | OUTPUT_VARIABLE gitbranch 23 | OUTPUT_STRIP_TRAILING_WHITESPACE 24 | ERROR_VARIABLE error 25 | ERROR_STRIP_TRAILING_WHITESPACE 26 | ) 27 | if(error) 28 | message(WARNING "Git ${error}") 29 | else() 30 | set(gitinfo "${gitinfo}\n${gitbranch}") 31 | endif() 32 | 33 | execute_process( 34 | COMMAND ${GIT} config --get remote.origin.url 35 | WORKING_DIRECTORY ${SOURCE_DIR} 36 | OUTPUT_VARIABLE gitorigin 37 | OUTPUT_STRIP_TRAILING_WHITESPACE 38 | ERROR_VARIABLE error 39 | ERROR_STRIP_TRAILING_WHITESPACE 40 | ) 41 | if(error) 42 | message(WARNING "Git ${error}") 43 | else() 44 | set(gitinfo "${gitinfo}\n${gitorigin}\n") 45 | endif() 46 | endif() 47 | 48 | set(gitinfo_file ${OUTPUT_DIR}/gitinfo.txt) 49 | 50 | if(EXISTS ${gitinfo_file}) 51 | file(READ ${gitinfo_file} prev_gitinfo) 52 | else() 53 | # Create empty file, because other targets expect it to exist. 54 | file(WRITE ${gitinfo_file} "") 55 | endif() 56 | 57 | if(NOT "${gitinfo}" STREQUAL "${prev_gitinfo}") 58 | file(WRITE ${gitinfo_file} ${gitinfo}) 59 | endif() 60 | -------------------------------------------------------------------------------- /cmake/ProjectBoostCertify.cmake: -------------------------------------------------------------------------------- 1 | include(ExternalProject) 2 | 3 | if (MSVC) 4 | set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) 5 | set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) 6 | endif() 7 | 8 | set(prefix "${CMAKE_BINARY_DIR}/deps") 9 | set(BOOSTCERTIFY_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}certify${CMAKE_STATIC_LIBRARY_SUFFIX}") 10 | set(BOOSTCERTIFY_INCLUDE_DIR "${prefix}/include") 11 | 12 | ExternalProject_Add( 13 | Certify 14 | PREFIX "${prefix}" 15 | URL https://github.com/djarek/certify/archive/97f5eebfd99a5d6e99d07e4820240994e4e59787.tar.gz 16 | URL_HASH SHA256=1c964b0aba47cd90081eaacc4946ea8e58d0c14fb267856f26515219e8ca1d68 17 | PATCH_COMMAND patch -p1 < ${CMAKE_CURRENT_SOURCE_DIR}/cmake/certifyPatch.patch 18 | CMAKE_ARGS -DCMAKE_INSTALL_PREFIX= 19 | -DCMAKE_POSITION_INDEPENDENT_CODE=${BUILD_SHARED_LIBS} 20 | -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} 21 | -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} 22 | -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} 23 | -DOPENSSL_ROOT_DIR=${OPENSSL_ROOT_DIR} 24 | ${_only_release_configuration} 25 | ${_windows_configuration} 26 | -DCMAKE_INSTALL_LIBDIR=lib 27 | DOWNLOAD_EXTRACT_TIMESTAMP 1 28 | LOG_CONFIGURE 1 29 | BUILD_COMMAND "" 30 | ${_overwrite_install_command} 31 | LOG_INSTALL 1 32 | BUILD_BYPRODUCTS "${CERTIFY_BYPRODUCTS}" 33 | ) 34 | 35 | # Create imported library 36 | add_library(certify STATIC IMPORTED GLOBAL) 37 | file(MAKE_DIRECTORY "${CERTIFY_INCLUDE_DIR}") # Must exist. 38 | set_property(TARGET certify PROPERTY IMPORTED_CONFIGURATIONS Release) 39 | set_property(TARGET certify PROPERTY IMPORTED_LOCATION_RELEASE "${CERTIFY_LIBRARY}") 40 | set_property(TARGET certify PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${CERTIFY_INCLUDE_DIR}") 41 | add_dependencies(certify Certify ${CERTIFY_BYPRODUCTS}) 42 | -------------------------------------------------------------------------------- /cmake/ProjectEthash.cmake: -------------------------------------------------------------------------------- 1 | include(ExternalProject) 2 | 3 | if (MSVC) 4 | set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) 5 | set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) 6 | endif() 7 | 8 | set(prefix "${CMAKE_BINARY_DIR}/deps") 9 | set(ETHASH_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}ethash${CMAKE_STATIC_LIBRARY_SUFFIX}") 10 | set(ETHASH_INCLUDE_DIR "${prefix}/include") 11 | set(ETHASH_BYPRODUCTS "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}keccak${CMAKE_STATIC_LIBRARY_SUFFIX}") 12 | 13 | ExternalProject_Add( 14 | Ethash 15 | PREFIX "${prefix}" 16 | DOWNLOAD_NAME ethash-v0.5.0.tar.gz 17 | DOWNLOAD_NO_PROGRESS 1 18 | URL https://github.com/chfast/ethash/archive/v0.5.0.tar.gz 19 | URL_HASH SHA256=16bce25f34b733a91530d22f31626fc1060f2fa5105165efdd9ba65e3e3e10ac 20 | CMAKE_ARGS -DCMAKE_INSTALL_PREFIX= 21 | -DCMAKE_POSITION_INDEPENDENT_CODE=${BUILD_SHARED_LIBS} 22 | -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} 23 | -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} 24 | -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} 25 | -DETHASH_BUILD_TESTS=OFF 26 | -DCMAKE_INSTALL_LIBDIR=lib 27 | ${_only_release_configuration} 28 | DOWNLOAD_EXTRACT_TIMESTAMP 1 29 | LOG_CONFIGURE 1 30 | BUILD_COMMAND "" 31 | ${_overwrite_install_command} 32 | LOG_INSTALL 1 33 | BUILD_BYPRODUCTS "${ETHASH_BYPRODUCTS}" 34 | ) 35 | 36 | # Create imported library 37 | add_library(ethash STATIC IMPORTED GLOBAL) 38 | file(MAKE_DIRECTORY "${ETHASH_INCLUDE_DIR}") # Must exist. 39 | set_property(TARGET ethash PROPERTY IMPORTED_CONFIGURATIONS Release) 40 | set_property(TARGET ethash PROPERTY IMPORTED_LOCATION_RELEASE "${ETHASH_LIBRARY}") 41 | set_property(TARGET ethash PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${ETHASH_INCLUDE_DIR}") 42 | add_dependencies(ethash Ethash ${ETHASH_BYPRODUCTS}) 43 | -------------------------------------------------------------------------------- /tests/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "Tests.h" 2 | #include "../include/web3cpp/Utils.h" 3 | #include "../src/libs/catch2/catch_amalgamated.hpp" 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | using Catch::Matchers::Equals; 11 | 12 | 13 | TEST_CASE("Test Utils Functionality") 14 | { 15 | 16 | SECTION("Test Utilities") 17 | { 18 | std::string password = "password"; 19 | Tests test(password); 20 | 21 | bool bigNumbers = test.testBigNumbers(); 22 | bool randomHexes = test.testRandomHexes(); 23 | bool sha3 = test.testSHA3(); 24 | bool solditySha3 = test.testSoliditySHA3(); 25 | bool soliditySha3Raw = test.testSoliditySHA3Raw(); 26 | bool hexes = test.testHexes(); 27 | bool addresses = test.testAddresses(); 28 | bool addressConversion = test.testAddressConversions(); 29 | bool addressChecksums = test.testAddressChecksums(); 30 | bool hexConversion = test.testHexConversions(); 31 | bool hexStriping = test.testHexStripping(); 32 | bool fromHextoType = test.testFromHexToTypes(); 33 | bool fromTypestoHex = test.testFromTypesToHex(); 34 | bool weiConversion = test.testWeiConversions(); 35 | bool hexPadding = test.testHexPadding(); 36 | 37 | REQUIRE(hexes); 38 | REQUIRE(bigNumbers); 39 | REQUIRE(sha3); 40 | REQUIRE(solditySha3); 41 | REQUIRE(soliditySha3Raw); 42 | REQUIRE(randomHexes); 43 | REQUIRE(addresses); 44 | REQUIRE(addressChecksums); 45 | REQUIRE(addressConversion); 46 | REQUIRE(hexConversion); 47 | REQUIRE(hexStriping); 48 | REQUIRE(fromHextoType); 49 | REQUIRE(fromTypestoHex); 50 | REQUIRE(hexPadding); 51 | REQUIRE(weiConversion); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Account.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | Account::Account( 4 | const boost::filesystem::path& walletPath, const std::string& __address, const std::string& __name, 5 | const std::string& __derivationPath, bool __isLedger, const std::unique_ptr& _provider 6 | ) : _address(__address), _name(__name), _derivationPath(__derivationPath), 7 | _isLedger(__isLedger), provider(_provider), 8 | transactionDB("transactions/" + __address, walletPath) 9 | { 10 | Error error; 11 | std::string nonceRequest = Net::HTTPRequest( 12 | this->provider, Net::RequestTypes::POST, 13 | RPC::eth_getTransactionCount(_address, "latest", error).dump() 14 | ); 15 | json nonceJson = json::parse(nonceRequest); 16 | _nonce = boost::lexical_cast>(nonceJson["result"].get()); 17 | } 18 | 19 | std::future Account::balance() const { 20 | return std::async([=]{ 21 | Error error; 22 | BigNumber ret; 23 | std::string balanceRequestStr = Net::HTTPRequest( 24 | this->provider, Net::RequestTypes::POST, 25 | RPC::eth_getBalance(this->_address, "latest", error).dump() 26 | ); 27 | if (error.getCode() != 0) { 28 | std::cout << "Error on getting balance for account " << this->_address 29 | << ": " << error.what() << std::endl; 30 | return ret; 31 | } 32 | json balanceRequest = json::parse(balanceRequestStr); 33 | ret = Utils::hexToBigNumber(balanceRequest["result"].get()); 34 | return ret; 35 | }); 36 | } 37 | 38 | bool Account::saveTxToHistory(std::string signedTx) { 39 | json txData = Utils::decodeRawTransaction(signedTx); 40 | return this->transactionDB.putKeyValue(txData["hash"], txData.dump()); 41 | } 42 | 43 | json Account::getTxHistory() const { 44 | json ret; 45 | std::map hist = this->transactionDB.getAllPairs(); 46 | for (std::pair item : hist) { 47 | ret[item.first] = item.second; 48 | } 49 | return ret; 50 | } 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /cmake/ProjectSecp256k1.cmake: -------------------------------------------------------------------------------- 1 | include(ExternalProject) 2 | 3 | if (MSVC) 4 | set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) 5 | set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) 6 | endif() 7 | 8 | set(prefix "${CMAKE_BINARY_DIR}/deps") 9 | set(SECP256K1_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}secp256k1${CMAKE_STATIC_LIBRARY_SUFFIX}") 10 | set(SECP256K1_INCLUDE_DIR "${prefix}/include") 11 | 12 | ExternalProject_Add( 13 | Secp256k1 14 | PREFIX "${prefix}" 15 | DOWNLOAD_NAME secp256k1-ac8ccf29.tar.gz 16 | DOWNLOAD_NO_PROGRESS 1 17 | URL https://github.com/itamarcps/secp256k1/archive/a74a75089ff65740cc14b3a084fa7c9d27a49174.tar.gz 18 | URL_HASH SHA256=3d5e56561690397862869e6d58f312db045709a9b7438c3462f865b4841aeac0 19 | PATCH_COMMAND ${CMAKE_COMMAND} -E copy_if_different 20 | ${CMAKE_CURRENT_LIST_DIR}/secp256k1/CMakeLists.txt 21 | CMAKE_ARGS -DCMAKE_INSTALL_PREFIX= 22 | -DCMAKE_POSITION_INDEPENDENT_CODE=${BUILD_SHARED_LIBS} 23 | -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} 24 | -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} 25 | -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} 26 | ${_only_release_configuration} 27 | -DCMAKE_INSTALL_LIBDIR=lib 28 | DOWNLOAD_EXTRACT_TIMESTAMP 1 29 | LOG_CONFIGURE 1 30 | BUILD_COMMAND "" 31 | ${_overwrite_install_command} 32 | LOG_INSTALL 1 33 | BUILD_BYPRODUCTS "${SECP256K1_LIBRARY}" 34 | ) 35 | 36 | # Create imported library 37 | add_library(secp256k1 STATIC IMPORTED GLOBAL) 38 | file(MAKE_DIRECTORY "${SECP256K1_INCLUDE_DIR}") # Must exist. 39 | set_property(TARGET secp256k1 PROPERTY IMPORTED_CONFIGURATIONS Release) 40 | set_property(TARGET secp256k1 PROPERTY IMPORTED_LOCATION_RELEASE "${SECP256K1_LIBRARY}") 41 | set_property(TARGET secp256k1 PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${SECP256K1_INCLUDE_DIR}") 42 | add_dependencies(secp256k1 Secp256k1) 43 | -------------------------------------------------------------------------------- /cmake/ProjectToolbox.cmake: -------------------------------------------------------------------------------- 1 | include(ExternalProject) 2 | 3 | if (MSVC) 4 | set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) 5 | set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) 6 | endif() 7 | 8 | set(prefix "${CMAKE_BINARY_DIR}/deps") 9 | set(TOOLBOX_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}toolbox${CMAKE_STATIC_LIBRARY_SUFFIX}") 10 | set(TOOLBOX_INCLUDE_DIR "${prefix}/include") 11 | 12 | ExternalProject_Add( 13 | Toolbox 14 | PREFIX "${prefix}" 15 | DOWNLOAD_NAME toolbox-3.1.2.tar.gz 16 | DOWNLOAD_NO_PROGRESS 1 17 | URL https://github.com/edwardstock/toolbox/archive/3.1.2.tar.gz 18 | URL_HASH SHA256=1eeba3174a09667ad04d4df667b177eb94e2bae7d79f346d3b3e84a317289376 19 | PATCH_COMMAND patch -p1 < ${CMAKE_CURRENT_SOURCE_DIR}/cmake/toolbox_limit.patch 20 | CMAKE_ARGS -DCMAKE_INSTALL_PREFIX= 21 | -DCMAKE_POSITION_INDEPENDENT_CODE=${BUILD_SHARED_LIBS} 22 | -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} 23 | -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} 24 | -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} 25 | -DCMAKE_SYSTEM_NAME=Generic # https://github.com/commonmark/cmark/pull/300#issuecomment-496286133 26 | -DENABLE_CONAN=OFF 27 | ${_only_release_configuration} 28 | -DCMAKE_INSTALL_LIBDIR=lib 29 | DOWNLOAD_EXTRACT_TIMESTAMP 1 30 | LOG_CONFIGURE 1 31 | BUILD_COMMAND "" 32 | ${_overwrite_install_command} 33 | LOG_INSTALL 1 34 | BUILD_BYPRODUCTS "${TOOLBOX_LIBRARY}" 35 | ) 36 | 37 | add_library(toolbox STATIC IMPORTED GLOBAL) 38 | file(MAKE_DIRECTORY "${TOOLBOX_INCLUDE_DIR}") # Must exist. 39 | set_property(TARGET toolbox PROPERTY IMPORTED_CONFIGURATIONS Release) 40 | set_property(TARGET toolbox PROPERTY IMPORTED_LOCATION_RELEASE "${TOOLBOX_LIBRARY}") 41 | set_property(TARGET toolbox PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${TOOLBOX_INCLUDE_DIR}") 42 | add_dependencies(toolbox Toolbox) 43 | -------------------------------------------------------------------------------- /cmake/ProjectLibFF.cmake: -------------------------------------------------------------------------------- 1 | # Aleth: Ethereum C++ client, tools and libraries. 2 | # Copyright 2017-2019 Aleth Authors. 3 | # Licensed under the GNU General Public License, Version 3. 4 | include(ProjectMPIR) 5 | 6 | set(prefix "${CMAKE_BINARY_DIR}/deps") 7 | set(libff_library "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}ff${CMAKE_STATIC_LIBRARY_SUFFIX}") 8 | set(libff_inlcude_dir "${prefix}/include/libff") 9 | 10 | ExternalProject_Add(libff 11 | PREFIX "${prefix}" 12 | DOWNLOAD_NAME libff-03b719a7.tar.gz 13 | DOWNLOAD_NO_PROGRESS TRUE 14 | URL https://github.com/scipr-lab/libff/archive/03b719a7c81757071f99fc60be1f7f7694e51390.tar.gz 15 | URL_HASH SHA256=81b476089af43025c8f253cb1a9b5038a1c375baccffea402fa82042e608ab02 16 | CMAKE_ARGS 17 | -DCMAKE_BUILD_TYPE=Release 18 | -DCMAKE_INSTALL_PREFIX= 19 | -DGMP_INCLUDE_DIR=${MPIR_INCLUDE_DIR} 20 | -DGMP_LIBRARY=${MPIR_LIBRARY} 21 | -DCURVE=ALT_BN128 -DPERFORMANCE=Off -DWITH_PROCPS=Off 22 | -DUSE_PT_COMPRESSION=Off 23 | -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} 24 | -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} 25 | -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} 26 | -DCMAKE_INSTALL_LIBDIR=lib 27 | BUILD_COMMAND ${CMAKE_COMMAND} --build --config Release 28 | LOG_BUILD 1 29 | INSTALL_COMMAND ${CMAKE_COMMAND} --build --config Release --target install 30 | BUILD_BYPRODUCTS "${libff_library}" 31 | DOWNLOAD_EXTRACT_TIMESTAMP 1 32 | ) 33 | add_dependencies(libff mpir) 34 | 35 | # Create snark imported library 36 | add_library(libff::ff STATIC IMPORTED GLOBAL) 37 | file(MAKE_DIRECTORY ${libff_inlcude_dir}) 38 | set_property(TARGET libff::ff PROPERTY IMPORTED_CONFIGURATIONS Release) 39 | set_property(TARGET libff::ff PROPERTY IMPORTED_LOCATION_RELEASE ${libff_library}) 40 | set_property(TARGET libff::ff PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${libff_inlcude_dir}) 41 | set_property(TARGET libff::ff PROPERTY INTERFACE_LINK_LIBRARIES MPIR::mpir) 42 | add_dependencies(libff::ff libff) 43 | -------------------------------------------------------------------------------- /cmake/cable/CableBuildType.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library 2 | # Copyright 2018 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | # Cable Build Type, version 1.0.1 6 | # 7 | # This CMake module helps with setting default build type 8 | # and build configurations for multi-configuration generators. 9 | # Use cable_set_build_type(). 10 | # 11 | # CHANGELOG 12 | # 13 | # 1.0.1 - 2021-05-20 14 | # - Fix usage in CMake sub-project. 15 | # 16 | # 1.0.0 - 2020-01-02 17 | 18 | 19 | if(cable_build_type_included) 20 | return() 21 | endif() 22 | set(cable_build_type_included TRUE) 23 | 24 | macro(cable_set_build_type) 25 | if(NOT PROJECT_SOURCE_DIR) # Before the main project(). 26 | cmake_parse_arguments(build_type "" DEFAULT CONFIGURATION_TYPES ${ARGN}) 27 | 28 | if(CMAKE_CONFIGURATION_TYPES) 29 | if(build_type_CONFIGURATION_TYPES) 30 | set( 31 | CMAKE_CONFIGURATION_TYPES 32 | ${build_type_CONFIGURATION_TYPES} 33 | CACHE 34 | STRING 35 | "Available configurations for multi-configuration generators" 36 | FORCE 37 | ) 38 | endif() 39 | message(STATUS "Configurations: ${CMAKE_CONFIGURATION_TYPES}") 40 | else() 41 | if(build_type_DEFAULT AND NOT CMAKE_BUILD_TYPE) 42 | set( 43 | CMAKE_BUILD_TYPE 44 | ${build_type_DEFAULT} 45 | CACHE STRING 46 | "Build type for single-configuration generators" 47 | FORCE 48 | ) 49 | endif() 50 | message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") 51 | endif() 52 | elseif(PROJECT_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) # After the main project(). 53 | message(FATAL_ERROR "cable_set_build_type() must be used before project()") 54 | endif() # Sub-project - silently ignore. 55 | endmacro() 56 | -------------------------------------------------------------------------------- /cmake/secp256k1/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This CMake config file for secp256k1 project from https://github.com/bitcoin-core/secp256k1 2 | # 3 | # The secp256k1 project has been configured following official docs with following options: 4 | # 5 | # ./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 6 | # 7 | # Build static context: 8 | # make src/ecmult_static_context.h 9 | # 10 | # Copy src/ecmult_static_context.h and src/libsecp256k1-config.h 11 | # 12 | # Copy CFLAGS from Makefile to COMPILE_OPTIONS. 13 | 14 | list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/modules) 15 | include(NativeExecutable) 16 | 17 | cmake_minimum_required(VERSION 3.4) 18 | project(secp256k1 LANGUAGES C) 19 | 20 | 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) 21 | if (MSVC) 22 | set(COMPILE_FLAGS USE_FIELD_10X26 USE_SCALAR_8X32) 23 | set(COMPILE_OPTIONS "") 24 | else() 25 | set(COMPILE_FLAGS USE_FIELD_5X52 USE_SCALAR_4X64 HAVE_BUILTIN_EXPECT HAVE___INT128) 26 | set(COMPILE_OPTIONS -O3 -W -std=c89 -pedantic -Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes -Wno-unused-function -Wno-long-long -Wno-overlength-strings -fvisibility=hidden) 27 | endif() 28 | 29 | add_native_executable(gen_context src/gen_context.c) 30 | native_target_include_directories(gen_context PRIVATE ${CMAKE_SOURCE_DIR}) 31 | 32 | add_custom_target(ecmult_static_context gen_context WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) 33 | 34 | add_library(secp256k1 STATIC src/secp256k1.c) 35 | target_compile_definitions(secp256k1 PRIVATE ${COMMON_COMPILE_FLAGS} ${COMPILE_FLAGS}) 36 | target_include_directories(secp256k1 PRIVATE ${CMAKE_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src) 37 | target_compile_options(secp256k1 PRIVATE ${COMPILE_OPTIONS}) 38 | add_dependencies(secp256k1 ecmult_static_context) 39 | 40 | install(TARGETS secp256k1 ARCHIVE DESTINATION lib) 41 | install(DIRECTORY include/ DESTINATION include) 42 | 43 | -------------------------------------------------------------------------------- /include/web3cpp/ledger/ledger.h: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2020-2021 AVME Developers 2 | // Distributed under the MIT/X11 software license, see the accompanying 3 | // file LICENSE or http://www.opensource.org/licenses/mit-license.php. 4 | #ifndef LEDGER_H 5 | #define LEDGER_H 6 | 7 | #include 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | #include "comms.h" 14 | #include "encoding.h" 15 | 16 | // For convenience. 17 | using json = nlohmann::ordered_json; 18 | 19 | /** 20 | * Namespace for Ledger-related functions. 21 | */ 22 | namespace ledger { 23 | struct account { 24 | std::string address; // e.g. 0x123456789ABCDEF... 25 | std::string index; // Derivation path (e.g. "m/60'/40'/0'/0") 26 | }; 27 | 28 | class device { 29 | private: 30 | communication ledgerDevice; 31 | std::vector ledgerAccounts; 32 | 33 | public: 34 | // Get the list of accounts inside the Ledger device. 35 | std::vector getAccountList() { return ledgerAccounts; } 36 | 37 | // Clean the account vector 38 | void cleanAccountList() { ledgerAccounts.clear(); } 39 | 40 | // Check if Ledger device is connected. 41 | std::pair checkForDevice(); 42 | 43 | // Generate a BIP32 account in the Ledger device. 44 | std::pair generateBip32Account(std::string path); 45 | 46 | // Sign a transaction using the Ledger device. 47 | std::pair signTransaction( 48 | dev::eth::TransactionSkeleton transactionSkl, std::string path 49 | ); 50 | 51 | // Sign a personal message using the Ledger device. 52 | std::pair signPersonalMessage( 53 | std::string message, std::string path 54 | ); 55 | 56 | // Encode to JSON a account from the ledger struct 57 | json encodeToJson(account ledgerAccount); 58 | 59 | // Decode to ledger struct from JSON 60 | account decodeFromJson(json ledgerAccount); 61 | 62 | }; 63 | } 64 | 65 | #endif // LEDGER_H 66 | -------------------------------------------------------------------------------- /cmake/ProjectLevelDB.cmake: -------------------------------------------------------------------------------- 1 | include(ExternalProject) 2 | 3 | if (MSVC) 4 | set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) 5 | set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) 6 | endif() 7 | 8 | if (DEPENDS_PREFIX STREQUAL "x86_64-w64-mingw32") 9 | set(_windows_configuration -DLEVELDB_PLATFORM_NAME=LEVELDB_PLATFORM_WINDOWS -DCMAKE_CROSSCOMPILING=1 -DRUN_HAVE_STD_REGEX=0 -DRUN_HAVE_POSIX_REGEX=0 -DWIN32=ON -DLEVELDB_BUILD_TESTS=OFF -DLEVELDB_BUILD_BENCHMARKS=OFF) 10 | endif() 11 | 12 | set(prefix "${CMAKE_BINARY_DIR}/deps") 13 | set(LEVELDB_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}leveldb${CMAKE_STATIC_LIBRARY_SUFFIX}") 14 | set(LEVELDB_INCLUDE_DIR "${prefix}/include") 15 | 16 | ExternalProject_Add( 17 | LevelDB 18 | PREFIX "${prefix}" 19 | GIT_REPOSITORY https://github.com/itamarcps/leveldb 20 | CMAKE_ARGS -DCMAKE_INSTALL_PREFIX= 21 | -DCMAKE_POSITION_INDEPENDENT_CODE=${BUILD_SHARED_LIBS} 22 | -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} 23 | -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} 24 | -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} 25 | -DLEVELDB_BUILD_TESTS=OFF 26 | -DLEVELDB_BUILD_BENCHMARKS=OFF 27 | ${_only_release_configuration} 28 | ${_windows_configuration} 29 | -DCMAKE_INSTALL_LIBDIR=lib 30 | UPDATE_DISCONNECTED true 31 | LOG_CONFIGURE 1 32 | BUILD_COMMAND "" 33 | ${_overwrite_install_command} 34 | LOG_INSTALL 1 35 | BUILD_BYPRODUCTS "${LEVELDB_BYPRODUCTS}" 36 | DOWNLOAD_EXTRACT_TIMESTAMP 1 37 | DEPENDS Snappy 38 | ) 39 | 40 | # Create imported library 41 | add_library(leveldb STATIC IMPORTED GLOBAL) 42 | file(MAKE_DIRECTORY "${LEVELDB_INCLUDE_DIR}") # Must exist. 43 | set_property(TARGET leveldb PROPERTY IMPORTED_CONFIGURATIONS Release) 44 | set_property(TARGET leveldb PROPERTY IMPORTED_LOCATION_RELEASE "${LEVELDB_LIBRARY}") 45 | set_property(TARGET leveldb PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${LEVELDB_INCLUDE_DIR}") 46 | add_dependencies(leveldb LevelDB Snappy ${LEVELDB_BYPRODUCTS}) 47 | -------------------------------------------------------------------------------- /include/web3cpp/Cipher.h: -------------------------------------------------------------------------------- 1 | #ifndef CIPHER_H 2 | #define CIPHER_H 3 | 4 | #define BOOST_BIND_GLOBAL_PLACEHOLDERS 5 | 6 | #include 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | using json = nlohmann::ordered_json; 16 | 17 | /** 18 | * Namespace for encrypting/decrypting any kind of data. 19 | * Originally assimilated and adapted from Ethereum's Aleth libs 20 | * (specifically from devcrypto/SecretStore.cpp). 21 | */ 22 | 23 | namespace Cipher { 24 | /** 25 | * Encrypts a given data string. 26 | * @param &plainText The data string to be encrypted. 27 | * @param &password The password used for encrypting. 28 | * @param &error Error object. 29 | * @return A JSON string with the encrypted data and parameters for decrypting. 30 | */ 31 | std::string encrypt( 32 | std::string const& plainText, std::string const& password, Error& error 33 | ); 34 | 35 | /** 36 | * Decrypts data from a JSON string. 37 | * @param &cipherText The JSON string with encrypted data and parameters for decrypting. 38 | * @param &password The password used for decrypting. 39 | * @param &error Error object. 40 | * @return The decrypted data string. 41 | */ 42 | std::string decrypt( 43 | std::string const& cipherText, std::string const& password, Error& error 44 | ); 45 | 46 | /** 47 | * **LEGACY/UNMAINTAINED**. Same as Cipher::encrypt(), but calls the 48 | * original Aleth `dev::SecretStore::encrypt()` implementation directly. 49 | * Use only if absolutely required. 50 | */ 51 | std::string encryptAleth( 52 | std::string const& plainText, std::string const& password 53 | ); 54 | 55 | /** 56 | * **LEGACY/UNMAINTAINED**. Same as Cipher::decrypt(), but calls the 57 | * original Aleth `dev::SecretStore::decrypt()` implementation directly. 58 | * Use only if absolutely required. 59 | */ 60 | std::string decryptAleth( 61 | std::string const& cipherText, std::string const& password 62 | ); 63 | } 64 | 65 | #endif // CIPHER_H 66 | -------------------------------------------------------------------------------- /include/web3cpp/devcore/StateCacheDB.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | #pragma once 5 | 6 | #include "Common.h" 7 | #include "RLP.h" 8 | 9 | namespace dev 10 | { 11 | class StateCacheDB 12 | { 13 | friend class EnforceRefs; 14 | 15 | public: 16 | StateCacheDB() {} 17 | StateCacheDB(StateCacheDB const& _c) { operator=(_c); } 18 | 19 | StateCacheDB& operator=(StateCacheDB const& _c); 20 | 21 | virtual ~StateCacheDB() = default; 22 | 23 | void clear() 24 | { 25 | m_main.clear(); 26 | m_aux.clear(); 27 | } // WARNING !!!! didn't originally clear m_refCount!!! 28 | std::unordered_map get() const; 29 | 30 | std::string lookup(h256 const& _h) const; 31 | bool exists(h256 const& _h) const; 32 | void insert(h256 const& _h, bytesConstRef _v); 33 | bool kill(h256 const& _h); 34 | void purge(); 35 | 36 | bytes lookupAux(h256 const& _h) const; 37 | void removeAux(h256 const& _h); 38 | void insertAux(h256 const& _h, bytesConstRef _v); 39 | 40 | h256Hash keys() const; 41 | 42 | protected: 43 | #if DEV_GUARDED_DB 44 | mutable SharedMutex x_this; 45 | #endif 46 | std::unordered_map> m_main; 47 | std::unordered_map> m_aux; 48 | 49 | mutable bool m_enforceRefs = false; 50 | }; 51 | 52 | class EnforceRefs 53 | { 54 | public: 55 | EnforceRefs(StateCacheDB const& _o, bool _r) : m_o(_o), m_r(_o.m_enforceRefs) 56 | { 57 | _o.m_enforceRefs = _r; 58 | } 59 | ~EnforceRefs() { m_o.m_enforceRefs = m_r; } 60 | 61 | private: 62 | StateCacheDB const& m_o; 63 | bool m_r; 64 | }; 65 | 66 | inline std::ostream& operator<<(std::ostream& _out, StateCacheDB const& _m) 67 | { 68 | for (auto const& i : _m.get()) 69 | { 70 | _out << i.first << ": "; 71 | _out << RLP(i.second); 72 | _out << " " << toHex(i.second); 73 | _out << std::endl; 74 | } 75 | return _out; 76 | } 77 | 78 | } // namespace dev 79 | -------------------------------------------------------------------------------- /cmake/ProjectBip3x.cmake: -------------------------------------------------------------------------------- 1 | include(ExternalProject) 2 | 3 | if (MSVC) 4 | set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) 5 | set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) 6 | endif() 7 | 8 | set(prefix "${CMAKE_BINARY_DIR}/deps") 9 | set(BIP3X_LIBRARY "${prefix}/lib/bip3x-2.1/${CMAKE_STATIC_LIBRARY_PREFIX}bip39${CMAKE_STATIC_LIBRARY_SUFFIX}") 10 | set(BIP3X_INCLUDE_DIR "${prefix}/include") 11 | 12 | 13 | ExternalProject_Add( 14 | Bip3x 15 | PREFIX "${prefix}" 16 | DOWNLOAD_NAME bip3x-9363c7b.tar.gz 17 | DOWNLOAD_NO_PROGRESS 1 18 | URL https://github.com/itamarcps/bip3x/archive/9363c7b20ccf3318eb04354547aacedc907e9ad0.tar.gz 19 | URL_HASH SHA256=26691fcf3532afac1798c2651fc2d8f9afe16c1b37c1cd7b0a9906edf995fd25 20 | PATCH_COMMAND patch -p1 < ${CMAKE_CURRENT_SOURCE_DIR}/cmake/bip3x_strings_fix.patch 21 | CMAKE_ARGS -DCMAKE_INSTALL_PREFIX= 22 | -DCMAKE_POSITION_INDEPENDENT_CODE=${BUILD_SHARED_LIBS} 23 | -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} 24 | -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} 25 | -DCMAKE_C_FLAGS=-I${BIP3X_INCLUDE_DIR} 26 | -DCMAKE_CXX_FLAGS=-I${BIP3X_INCLUDE_DIR}\ -I${OPENSSL_INCLUDE_DIR}\ ${CMAKE_CXX_FLAGS} 27 | -DENABLE_CONAN=OFF 28 | -DENABLE_BIP39_JNI=OFF 29 | ${_only_release_configuration} 30 | -DCMAKE_INSTALL_LIBDIR=lib 31 | DOWNLOAD_EXTRACT_TIMESTAMP 1 32 | LOG_CONFIGURE 1 33 | BUILD_COMMAND "" 34 | ${_overwrite_install_command} 35 | LOG_INSTALL 1 36 | BUILD_BYPRODUCTS "${BIP3X_LIBRARY}" 37 | DEPENDS toolbox OpenSSL::Crypto 38 | ) 39 | 40 | add_library(bip3x STATIC IMPORTED GLOBAL) 41 | file(MAKE_DIRECTORY "${BIP3X_INCLUDE_DIR}") # Must exist. 42 | set_property(TARGET bip3x PROPERTY IMPORTED_CONFIGURATIONS Release) 43 | set_property(TARGET bip3x PROPERTY IMPORTED_LOCATION_RELEASE "${BIP3X_LIBRARY}") 44 | set_property(TARGET Bip3x PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${BIP3X_INCLUDE_DIR}") 45 | add_dependencies(bip3x toolbox Bip3x ${OPENSSL_LIBRARIES}) 46 | 47 | -------------------------------------------------------------------------------- /include/web3cpp/Web3.h: -------------------------------------------------------------------------------- 1 | #ifndef WEB3_H 2 | #define WEB3_H 3 | 4 | #include 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "version.h" 15 | 16 | /** 17 | * Main/Umbrella class for %Web3. 18 | * Entry point for accessing the wallet and other classes. 19 | */ 20 | 21 | class Web3 { 22 | private: 23 | const std::unique_ptr defaultProvider; ///< Provider used for the whole %Web3 library. 24 | const boost::filesystem::path defaultPath; ///< Path for the %Web3 wallet. 25 | 26 | public: 27 | /** 28 | * Constructor. 29 | * @param *provider (optional) The provider that will be used. Defaults to 30 | * whatever the Provider constructor sets as the default. 31 | * @param *path (optional) The folder where the wallet is and will be 32 | * opened/created. Defaults to Utils::getDefaultDataDir(). 33 | */ 34 | 35 | // Default Constructor 36 | Web3(); 37 | 38 | /// Constructor overload that uses a custom Provider. 39 | Web3(Provider provider); 40 | 41 | /// Constructor overload that uses a custom wallet path. 42 | Web3(boost::filesystem::path path); 43 | 44 | /// Constructor overload that uses both custom Provider & custom Path. 45 | Web3(Provider provider, boost::filesystem::path path); 46 | 47 | std::string version; ///< Current version of the library. 48 | Wallet wallet; ///< Object for accessing the wallet. 49 | Eth eth; ///< Object for accessing functions from the Eth class. 50 | 51 | /** 52 | * Getter for the library provider. 53 | * @returns A pointer to Web3::defaultProvider. 54 | */ 55 | const std::unique_ptr& getProvider() const { return this->defaultProvider; } 56 | 57 | /** 58 | * Setter for the library provider. 59 | * @param p The provider to use. 60 | */ 61 | void setProvider(Provider p) { this->defaultProvider->setProvider(p); } 62 | }; 63 | 64 | #endif // WEB3_H 65 | -------------------------------------------------------------------------------- /cmake/ProjectLibmd4c.cmake: -------------------------------------------------------------------------------- 1 | include(ExternalProject) 2 | 3 | if (MSVC) 4 | set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) 5 | set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) 6 | endif() 7 | 8 | if (DEPENDS_PREFIX STREQUAL "x86_64-w64-mingw32") 9 | set(_windows_configuration -DCMAKE_CROSSCOMPILING=1 -DRUN_HAVE_STD_REGEX=0 -DRUN_HAVE_POSIX_REGEX=0 -DWIN32=ON) 10 | endif() 11 | 12 | set(prefix "${CMAKE_BINARY_DIR}/deps") 13 | set(MD4C_LIBRARY "${prefix}/lib/md4c/${CMAKE_STATIC_LIBRARY_PREFIX}md4c${CMAKE_STATIC_LIBRARY_SUFFIX}") 14 | set(MD4C_INCLUDE_DIR "${prefix}/include") 15 | 16 | ExternalProject_Add( 17 | libmd4c 18 | PREFIX "${prefix}" 19 | DOWNLOAD_NAME 20 | DOWNLOAD_NO_PROGRESS 1 21 | URL https://github.com/mity/md4c/archive/release-0.4.8.zip 22 | URL_HASH SHA256=bc7910a0ac6ca4863353d585a1ddc150d1e9b9c4dd02bc55520c5a6620e1e211 23 | PATCH_COMMAND patch -p1 < ${CMAKE_CURRENT_SOURCE_DIR}/cmake/libmd4c_no_md2html.patch 24 | CMAKE_ARGS -DCMAKE_INSTALL_PREFIX= 25 | -DBUILD_SHARED_LIBS=OFF 26 | -DCMAKE_POSITION_INDEPENDENT_CODE=${BUILD_SHARED_LIBS} 27 | -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} 28 | -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} 29 | -DCMAKE_C_FLAGS=-I${MD4C_INCLUDE_DIR} 30 | -DCMAKE_CXX_FLAGS=-I${MD4C_INCLUDE_DIR}\ -I${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/include\ ${CMAKE_CXX_FLAGS} 31 | ${_only_release_configuration} 32 | ${_windows_configuration} 33 | -DCMAKE_INSTALL_LIBDIR=lib/md4c 34 | LOG_CONFIGURE 1 35 | ${_overwrite_install_command} 36 | BUILD_BYPRODUCTS "${MD4C_LIBRARY}" 37 | DOWNLOAD_EXTRACT_TIMESTAMP 1 38 | ) 39 | 40 | add_library(md4c STATIC IMPORTED GLOBAL) 41 | file(MAKE_DIRECTORY "${MD4C_INCLUDE_DIR}") # Must exist. 42 | set_property(TARGET md4c PROPERTY IMPORTED_CONFIGURATIONS Release) 43 | set_property(TARGET md4c PROPERTY IMPORTED_LOCATION_RELEASE "${MD4C_LIBRARY}") 44 | set_property(TARGET md4c PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${MD4C_INCLUDE_DIR}") 45 | add_dependencies(md4c libmd4c) 46 | -------------------------------------------------------------------------------- /src/Provider.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | json Provider::presets = { 4 | {"avax-c-main", { 5 | {"name", "Avalanche Mainnet (C-Chain)"}, 6 | {"host", "api.avax.network"}, 7 | {"target", "/ext/bc/C/rpc"}, 8 | {"port", 443}, 9 | {"chainId", 43114}, 10 | {"currency", "AVAX"}, 11 | {"explorerUrl", "https://snowtrace.io"}, 12 | }}, 13 | {"avax-c-test", { 14 | {"name", "Avalanche Testnet (C-Chain)"}, 15 | {"host", "api.avax-test.network"}, 16 | {"target", "/ext/bc/C/rpc"}, 17 | {"port", 443}, 18 | {"chainId", 43113}, 19 | {"currency", "AVAX"}, 20 | {"explorerUrl", "https://testnet.snowtrace.io"}, 21 | }} 22 | }; 23 | 24 | void Provider::_setData(json data) { 25 | this->name = data["name"].get(); 26 | this->host = data["host"].get(); 27 | this->target = data["target"].get(); 28 | this->port = data["port"].get(); 29 | this->chainId = data["chainId"].get(); 30 | this->currency = data["currency"].get(); 31 | this->explorerUrl = data["explorerUrl"].get(); 32 | } 33 | 34 | Provider::Provider(std::string id) { 35 | if (!presets.count(id)) { 36 | std::cout << "Provider preset " << id << " does not exist, " 37 | << "falling back to avax-c-main" << std::endl; 38 | id = "avax-c-main"; 39 | } 40 | _setData(presets[id]); 41 | } 42 | 43 | Provider::Provider(const Provider &p) : 44 | _id(p._id), 45 | name(p.name), host(p.host), target(p.target), port(p.port), 46 | chainId(p.chainId), currency(p.currency), explorerUrl(p.explorerUrl) 47 | {} 48 | 49 | Provider::Provider( 50 | std::string name, std::string host, std::string target, uint64_t port, 51 | uint64_t chainId, std::string currency, std::string explorerUrl) 52 | : name(name), host(host), target(target), port(port), chainId(chainId), 53 | currency(currency), explorerUrl(explorerUrl) { } 54 | 55 | void Provider::setProvider(const Provider &p) { 56 | json pJ = { 57 | {"name", p.name}, {"host", p.host}, {"target", p.target}, {"port", p.port}, 58 | {"chainId", p.chainId}, {"currency", p.currency}, {"explorerUrl", p.explorerUrl} 59 | }; 60 | this->_setData(pJ); 61 | }; -------------------------------------------------------------------------------- /src/Error.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const std::map Error::codeMap = { 4 | {0, "No Error"}, 5 | {1, "Incorrect Password"}, 6 | {2, "Database Insert Failed"}, 7 | {3, "Account Exists"}, 8 | {4, "Invalid Hex Data"}, 9 | {5, "Invalid Address"}, 10 | {6, "Invalid Hash Length"}, 11 | {7, "Key Derivation Failed"}, 12 | {8, "Key Encryption Failed"}, 13 | {9, "Invalid Block Number"}, 14 | {10, "Invalid Number"}, 15 | {11, "Transaction Build Error"}, 16 | {12, "Transaction Sign Error"}, 17 | {13, "Transaction Send Error"}, 18 | {14, "Key Derivation Invalid Length"}, 19 | {15, "Key Decryption MAC Mismatch"}, 20 | {16, "Key Decryption Failed"}, 21 | {17, "ABI Functor Not Found"}, 22 | {18, "ABI Invalid Arguments Length"}, 23 | {19, "ABI Invalid JSON Array"}, 24 | {20, "ABI Invalid Uint256 Array"}, 25 | {21, "ABI Invalid Address Array"}, 26 | {22, "ABI Invalid Boolean Array"}, 27 | {23, "ABI Invalid Bytes Array"}, 28 | {24, "ABI Invalid String Array"}, 29 | {25, "ABI Invalid Uint256"}, 30 | {26, "ABI Invalid Address"}, 31 | {27, "ABI Invalid Boolean"}, 32 | {28, "ABI Invalid Bytes"}, 33 | {29, "ABI Invalid String"}, 34 | {30, "ABI Invalid Function"}, 35 | {31, "ABI Unsupported Or Invalid Type"}, 36 | {32, "ABI Missing Type Or Value"}, 37 | {33, "JSON File Does Not Exist"}, 38 | {34, "JSON File Read Error"}, 39 | {35, "JSON File Write Error"}, 40 | {999, "Unknown Error"} 41 | }; 42 | 43 | void Error::setCode(uint64_t errorCode) { 44 | this->lock.lock(); 45 | if (isSet) { 46 | this->lock.unlock(); 47 | std::cout << "Error already set" << std::endl; 48 | return; 49 | }; 50 | auto match = codeMap.find(errorCode); 51 | if (match != codeMap.end()) { 52 | code = match->first; 53 | message = match->second; 54 | isSet = true; 55 | } else { 56 | code = 999; 57 | message = codeMap.find(code)->second; 58 | isSet = true; 59 | } 60 | this->lock.unlock(); 61 | } 62 | 63 | uint64_t Error::getCode() { 64 | this->lock.lock(); 65 | uint64_t ret = this->code; 66 | this->lock.unlock(); 67 | return ret; 68 | } 69 | 70 | std::string Error::what() { 71 | this->lock.lock(); 72 | std::string ret = this->message; 73 | this->lock.unlock(); 74 | return ret; 75 | } 76 | 77 | -------------------------------------------------------------------------------- /cmake/cable/cable.cmake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S cmake -P 2 | 3 | # Cable: CMake Bootstrap Library 4 | # Copyright 2019-2020 Pawel Bylica. 5 | # Licensed under the Apache License, Version 2.0. 6 | 7 | # The cable command-line tool, version 1.0.0 8 | # 9 | # This CMake script allows installing or updating Cable modules. 10 | # Commands: 11 | # - list 12 | # - install 13 | # - update 14 | # 15 | # You can also include it from CMakeLists.txt to add Cable modules to 16 | # CMAKE_MODULE_PATH. 17 | 18 | if(NOT CMAKE_SCRIPT_MODE_FILE) 19 | # Setup Cable modules when included as include(cable.cmake). 20 | list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) 21 | return() 22 | endif() 23 | 24 | set(repo_url https://github.com/ethereum/cable) 25 | set(download_url ${repo_url}/raw/master) 26 | set(cable_dir ${CMAKE_CURRENT_LIST_DIR}) 27 | 28 | function(get_modules_list OUTPUT_LIST) 29 | file(GLOB modules_files RELATIVE ${cable_dir} "${cable_dir}/Cable*.cmake") 30 | string(REPLACE ".cmake" "" modules "${modules_files}") 31 | set(${OUTPUT_LIST} "${modules}" PARENT_SCOPE) 32 | endfunction() 33 | 34 | function(download MODULE_NAME) 35 | set(module_file ${MODULE_NAME}.cmake) 36 | set(src "${download_url}/${module_file}") 37 | set(dst "${cable_dir}/${module_file}") 38 | file(DOWNLOAD "${src}" "${dst}" STATUS status) 39 | list(GET status 0 status_code) 40 | list(GET status 1 error_msg) 41 | if(status EQUAL 0) 42 | set(msg DONE) 43 | else() 44 | file(REMOVE "${dst}") 45 | set(msg "${status_code} ${error_msg}\n ${src}") 46 | endif() 47 | message("Downloading ${MODULE_NAME}: ${msg}") 48 | endfunction() 49 | 50 | set(cmd ${CMAKE_ARGV3}) # cmake -P cable.cmake ARGV3 ARGV4 ... 51 | if(NOT cmd) 52 | set(cmd list) 53 | endif() 54 | 55 | if(cmd STREQUAL list) 56 | get_modules_list(modules) 57 | string(REPLACE ";" "\n " modules "${modules}") 58 | message("Installed modules:\n ${modules}") 59 | elseif(cmd STREQUAL update) 60 | get_modules_list(modules) 61 | foreach(module ${modules}) 62 | download(${module}) 63 | endforeach() 64 | elseif(cmd STREQUAL install) 65 | download(${CMAKE_ARGV4}) 66 | else() 67 | message(FATAL_ERROR "Unknown command '${cmd}'") 68 | endif() 69 | -------------------------------------------------------------------------------- /cmake/ProjectSnappy.cmake: -------------------------------------------------------------------------------- 1 | include(ExternalProject) 2 | 3 | if (MSVC) 4 | set(_only_release_configuration -DCMAKE_CONFIGURATION_TYPES=Release) 5 | set(_overwrite_install_command INSTALL_COMMAND cmake --build --config Release --target install) 6 | endif() 7 | 8 | if (DEPENDS_PREFIX STREQUAL "x86_64-w64-mingw32") 9 | set(_windows_configuration -DCMAKE_CROSSCOMPILING=1 -DRUN_HAVE_STD_REGEX=0 -DRUN_HAVE_POSIX_REGEX=0 -DWIN32=ON) 10 | endif() 11 | 12 | set(prefix "${CMAKE_BINARY_DIR}/deps") 13 | set(SNAPPY_LIBRARY "${prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}snappy${CMAKE_STATIC_LIBRARY_SUFFIX}") 14 | set(SNAPPY_INCLUDE_DIR "${prefix}/include") 15 | 16 | ExternalProject_Add( 17 | Snappy 18 | PREFIX "${prefix}" 19 | DOWNLOAD_NAME snappy-1.1.9.tar.gz 20 | DOWNLOAD_NO_PROGRESS 1 21 | URL https://github.com/google/snappy/archive/refs/tags/1.1.9.zip 22 | URL_HASH SHA256=e170ce0def2c71d0403f5cda61d6e2743373f9480124bcfcd0fa9b3299d428d9 23 | CMAKE_ARGS -DCMAKE_INSTALL_PREFIX= 24 | -DCMAKE_POSITION_INDEPENDENT_CODE=${BUILD_SHARED_LIBS} 25 | -DCMAKE_SYSTEM_NAME=${CMAKE_SYSTEM_NAME} 26 | -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} 27 | -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} 28 | -DCMAKE_C_FLAGS=-I${SNAPPY_INCLUDE_DIR} 29 | -DCMAKE_CXX_FLAGS=-I${SNAPPY_INCLUDE_DIR}\ -I${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/include\ ${CMAKE_CXX_FLAGS} 30 | ${_only_release_configuration} 31 | ${_windows_configuration} 32 | -DSNAPPY_BUILD_TESTS=OFF 33 | -DSNAPPY_BUILD_BENCHMARKS=OFF 34 | -DCMAKE_INSTALL_LIBDIR=lib 35 | DOWNLOAD_EXTRACT_TIMESTAMP 1 36 | LOG_CONFIGURE 1 37 | BUILD_COMMAND "" 38 | ${_overwrite_install_command} 39 | LOG_INSTALL 1 40 | BUILD_BYPRODUCTS "${SNAPPY_LIBRARY}" 41 | ) 42 | 43 | add_library(snappy STATIC IMPORTED GLOBAL) 44 | file(MAKE_DIRECTORY "${SNAPPY_INCLUDE_DIR}") # Must exist. 45 | set_property(TARGET snappy PROPERTY IMPORTED_CONFIGURATIONS Release) 46 | set_property(TARGET snappy PROPERTY IMPORTED_LOCATION_RELEASE "${SNAPPY_LIBRARY}") 47 | set_property(TARGET snappy PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${SNAPPY_INCLUDE_DIR}") 48 | add_dependencies(snappy Snappy) 49 | 50 | -------------------------------------------------------------------------------- /cmake/cable/bootstrap.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library 2 | # Copyright 2019-2020 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | # Bootstrap the Cable - CMake Bootstrap Library by including this file. 6 | # e.g. include(cmake/cable/bootstrap.cmake). 7 | 8 | 9 | # Cable version. 10 | # 11 | # This is internal variable automatically updated with external tools. 12 | # Use CABLE_VERSION variable if you need this information. 13 | set(version 0.5.0) 14 | 15 | # For convenience, add the project CMake module dir to module path. 16 | set(module_dir ${CMAKE_CURRENT_SOURCE_DIR}/cmake) 17 | if(EXISTS ${module_dir}) 18 | list(APPEND CMAKE_MODULE_PATH ${module_dir}) 19 | endif() 20 | 21 | # Always add this Cable instance modules to the CMake module path. 22 | list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) 23 | 24 | if(CABLE_VERSION) 25 | # Some other instance of Cable has been initialized in the top project. 26 | 27 | # Mark this project as nested. 28 | set(PROJECT_IS_NESTED TRUE) 29 | 30 | # Compare versions of the top project and this instances. 31 | if(CABLE_VERSION VERSION_LESS version) 32 | set(comment " (version older than ${version})") 33 | elseif(CABLE_VERSION VERSION_GREATER version) 34 | set(comment " (version newer than ${version})") 35 | endif() 36 | 37 | # Log information about initialization in the top project. 38 | file(RELATIVE_PATH subproject_dir ${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}) 39 | cable_debug("${subproject_dir}: Cable ${CABLE_VERSION}${comment} already initialized in the top project") 40 | cable_debug("Project CMake modules directory: ${module_dir}") 41 | 42 | unset(version) 43 | unset(module_dir) 44 | unset(comment) 45 | return() 46 | endif() 47 | 48 | 49 | option(CABLE_DEBUG "Enable Cable debug logs" OFF) 50 | 51 | function(cable_log) 52 | message(STATUS "[cable ] ${ARGN}") 53 | endfunction() 54 | 55 | function(cable_debug) 56 | if(CABLE_DEBUG) 57 | message(STATUS "[cable*] ${ARGN}") 58 | endif() 59 | endfunction() 60 | 61 | # Export Cable version. 62 | set(CABLE_VERSION ${version}) 63 | 64 | # Mark this project as non-nested. 65 | set(PROJECT_IS_NESTED FALSE) 66 | 67 | cable_log("Cable ${CABLE_VERSION} initialized") 68 | cable_debug("Project CMake modules directory: ${module_dir}") 69 | 70 | unset(version) 71 | unset(module_dir) 72 | -------------------------------------------------------------------------------- /tests/cipher.cpp: -------------------------------------------------------------------------------- 1 | #include "../src/libs/catch2/catch_amalgamated.hpp" 2 | #include "../include/web3cpp/Cipher.h" 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | using Catch::Matchers::Equals; 9 | 10 | namespace TCipher 11 | { 12 | TEST_CASE("Cipher is normal") 13 | { 14 | SECTION("Cipher Test") 15 | { 16 | std::string pass = "password"; 17 | std::string msg1 = "Test Message"; 18 | std::string msg2 = "0x1234567890123456789012345678901234567890"; 19 | std::string msg3 = "{\"object\": \"testJson\", \"params\": [\"aaa\", \"bbb\", \"ccc\"]}"; 20 | Error e1, e2, e3, e4, e5, e6; 21 | std::string enc1 = Cipher::encrypt(msg1, pass, e1); 22 | std::string dec1 = Cipher::decrypt(enc1, pass, e2); 23 | std::string enc2 = Cipher::encrypt(msg2, pass, e3); 24 | std::string dec2 = Cipher::decrypt(enc2, pass, e4); 25 | std::string enc3 = Cipher::encrypt(msg3, pass, e5); 26 | std::string dec3 = Cipher::decrypt(enc3, pass, e6); 27 | REQUIRE(e1.getCode() == 0); 28 | REQUIRE(e2.getCode() == 0); 29 | REQUIRE(e3.getCode() == 0); 30 | REQUIRE(e4.getCode() == 0); 31 | REQUIRE(e5.getCode() == 0); 32 | REQUIRE(e6.getCode() == 0); 33 | 34 | REQUIRE(dec1 == msg1); 35 | REQUIRE(dec2 == msg2); 36 | REQUIRE(dec3 == msg3); 37 | } 38 | } 39 | TEST_CASE("Legacy Cipher Test") 40 | { 41 | SECTION("Legacy Cipher ") 42 | { 43 | std::string pass = "password"; 44 | std::string msg1 = "Test Message"; 45 | std::string msg2 = "0x1234567890123456789012345678901234567890"; 46 | std::string msg3 = "{\"object\": \"testJson\", \"params\": [\"aaa\", \"bbb\", \"ccc\"]}"; 47 | std::string enc1 = Cipher::encryptAleth(msg1, pass); 48 | std::string dec1 = Cipher::decryptAleth(enc1, pass); 49 | std::string enc2 = Cipher::encryptAleth(msg2, pass); 50 | std::string dec2 = Cipher::decryptAleth(enc2, pass); 51 | std::string enc3 = Cipher::encryptAleth(msg3, pass); 52 | std::string dec3 = Cipher::decryptAleth(enc3, pass); 53 | 54 | REQUIRE(!dec1.empty()); 55 | REQUIRE(!dec2.empty()); 56 | REQUIRE(!dec3.empty()); 57 | 58 | } 59 | } 60 | 61 | } -------------------------------------------------------------------------------- /src/devcore/FileSystem.cpp: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | 6 | #include 7 | #include 8 | 9 | #if defined(_WIN32) 10 | #include 11 | #else 12 | #include 13 | #include 14 | #include 15 | #include 16 | #endif 17 | #include 18 | using namespace dev; 19 | 20 | namespace fs = boost::filesystem; 21 | 22 | static_assert(BOOST_VERSION >= 106400, "Wrong boost headers version"); 23 | 24 | // Should be written to only once during startup 25 | static fs::path s_ethereumDatadir; 26 | static fs::path s_ethereumIpcPath; 27 | 28 | void dev::setDataDir(fs::path const& _dataDir) 29 | { 30 | s_ethereumDatadir = _dataDir; 31 | } 32 | 33 | void dev::setIpcPath(fs::path const& _ipcDir) 34 | { 35 | s_ethereumIpcPath = _ipcDir; 36 | } 37 | 38 | fs::path dev::getIpcPath() 39 | { 40 | // Strip "geth.ipc" suffix if provided. 41 | if (s_ethereumIpcPath.filename() == "geth.ipc") 42 | return s_ethereumIpcPath.parent_path(); 43 | else 44 | return s_ethereumIpcPath; 45 | } 46 | 47 | fs::path dev::getDataDir(std::string _prefix) 48 | { 49 | if (_prefix.empty()) 50 | _prefix = "ethereum"; 51 | if (_prefix == "ethereum" && !s_ethereumDatadir.empty()) 52 | return s_ethereumDatadir; 53 | return getDefaultDataDir(_prefix); 54 | } 55 | 56 | fs::path dev::getDefaultDataDir(std::string _prefix) 57 | { 58 | if (_prefix.empty()) 59 | _prefix = "ethereum"; 60 | 61 | #if defined(_WIN32) 62 | _prefix[0] = toupper(_prefix[0]); 63 | char path[1024] = ""; 64 | if (SHGetSpecialFolderPathA(NULL, path, CSIDL_APPDATA, true)) 65 | return fs::path(path) / _prefix; 66 | else 67 | { 68 | #ifndef _MSC_VER // todo? 69 | // cwarn << "getDataDir(): SHGetSpecialFolderPathA() failed."; 70 | #endif 71 | BOOST_THROW_EXCEPTION(std::runtime_error("getDataDir() - SHGetSpecialFolderPathA() failed.")); 72 | } 73 | #else 74 | fs::path dataDirPath; 75 | char const* homeDir = getenv("HOME"); 76 | if (!homeDir || strlen(homeDir) == 0) 77 | { 78 | struct passwd* pwd = getpwuid(getuid()); 79 | if (pwd) 80 | homeDir = pwd->pw_dir; 81 | } 82 | 83 | if (!homeDir || strlen(homeDir) == 0) 84 | dataDirPath = fs::path("/"); 85 | else 86 | dataDirPath = fs::path(homeDir); 87 | 88 | return dataDirPath / ("." + _prefix); 89 | #endif 90 | } 91 | 92 | fs::path dev::appendToFilename(fs::path const& _orig, std::string const& _suffix) 93 | { 94 | if (_orig.filename() == fs::path(".") || _orig.filename() == fs::path("..")) 95 | return _orig / fs::path(_suffix); 96 | else 97 | return _orig.parent_path() / fs::path( _orig.filename().string() + _suffix); 98 | } 99 | -------------------------------------------------------------------------------- /include/web3cpp/devcore/Assertions.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2015-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | /// @file 6 | /// Assertion handling. 7 | #pragma once 8 | 9 | #include 10 | #include 11 | 12 | namespace dev 13 | { 14 | 15 | #if defined(_MSC_VER) 16 | #define ETH_FUNC __FUNCSIG__ 17 | #elif defined(__GNUC__) 18 | #define ETH_FUNC __PRETTY_FUNCTION__ 19 | #else 20 | #define ETH_FUNC __func__ 21 | #endif 22 | 23 | #define asserts(A) ::dev::assertAux(A, #A, __LINE__, __FILE__, ETH_FUNC) 24 | #define assertsEqual(A, B) ::dev::assertEqualAux(A, B, #A, #B, __LINE__, __FILE__, ETH_FUNC) 25 | 26 | inline bool assertAux(bool _a, char const* _aStr, unsigned _line, char const* _file, char const* _func) 27 | { 28 | if (!_a) 29 | std::cerr << "Assertion failed:" << _aStr << " [func=" << _func << ", line=" << _line << ", file=" << _file << "]" << std::endl; 30 | return !_a; 31 | } 32 | 33 | template 34 | inline bool assertEqualAux(A const& _a, B const& _b, char const* _aStr, char const* _bStr, unsigned _line, char const* _file, char const* _func) 35 | { 36 | bool c = _a == _b; 37 | if (!c) 38 | { 39 | std::cerr << "Assertion failed: " << _aStr << " == " << _bStr << " [func=" << _func << ", line=" << _line << ", file=" << _file << "]" << std::endl; 40 | std::cerr << " Fail equality: " << _a << "==" << _b << std::endl; 41 | } 42 | return !c; 43 | } 44 | 45 | /// Assertion that throws an exception containing the given description if it is not met. 46 | /// Use it as assertThrow(1 == 1, ExceptionType, "Mathematics is wrong."); 47 | /// Do NOT supply an exception object as the second parameter. 48 | #define assertThrow(_condition, _ExceptionType, _description) \ 49 | ::dev::assertThrowAux<_ExceptionType>(_condition, _description, __LINE__, __FILE__, ETH_FUNC) 50 | 51 | using errinfo_comment = boost::error_info; 52 | 53 | template 54 | inline void assertThrowAux( 55 | bool _condition, 56 | ::std::string const& _errorDescription, 57 | unsigned _line, 58 | char const* _file, 59 | char const* _function 60 | ) 61 | { 62 | if (!_condition) 63 | ::boost::throw_exception( 64 | _ExceptionType() << 65 | ::dev::errinfo_comment(_errorDescription) << 66 | ::boost::throw_function(_function) << 67 | ::boost::throw_file(_file) << 68 | ::boost::throw_line(_line) 69 | ); 70 | } 71 | 72 | template 73 | inline void assertThrowAux( 74 | void const* _pointer, 75 | ::std::string const& _errorDescription, 76 | unsigned _line, 77 | char const* _file, 78 | char const* _function 79 | ) 80 | { 81 | assertThrowAux<_ExceptionType>(_pointer != nullptr, _errorDescription, _line, _file, _function); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/devcore/CommonData.cpp: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | 6 | #include 7 | #include 8 | 9 | #include 10 | 11 | using namespace dev; 12 | 13 | namespace 14 | { 15 | int fromHexChar(char _i) noexcept 16 | { 17 | if (_i >= '0' && _i <= '9') 18 | return _i - '0'; 19 | if (_i >= 'a' && _i <= 'f') 20 | return _i - 'a' + 10; 21 | if (_i >= 'A' && _i <= 'F') 22 | return _i - 'A' + 10; 23 | return -1; 24 | } 25 | } 26 | 27 | bool dev::isHex(std::string const& _s) noexcept 28 | { 29 | auto it = _s.begin(); 30 | if (_s.compare(0, 2, "0x") == 0) 31 | it += 2; 32 | return std::all_of(it, _s.end(), [](char c){ return fromHexChar(c) != -1; }); 33 | } 34 | 35 | std::string dev::escaped(std::string const& _s, bool _all) 36 | { 37 | static const std::map prettyEscapes{{'\r', 'r'}, {'\n', 'n'}, {'\t', 't'}, {'\v', 'v'}}; 38 | std::string ret; 39 | ret.reserve(_s.size() + 2); 40 | ret.push_back('"'); 41 | for (auto i: _s) 42 | if (i == '"' && !_all) 43 | ret += "\\\""; 44 | else if (i == '\\' && !_all) 45 | ret += "\\\\"; 46 | else if (prettyEscapes.count(i) && !_all) 47 | { 48 | ret += '\\'; 49 | ret += prettyEscapes.find(i)->second; 50 | } 51 | else if (i < ' ' || _all) 52 | { 53 | ret += "\\x"; 54 | ret.push_back("0123456789abcdef"[(uint8_t)i / 16]); 55 | ret.push_back("0123456789abcdef"[(uint8_t)i % 16]); 56 | } 57 | else 58 | ret.push_back(i); 59 | ret.push_back('"'); 60 | return ret; 61 | } 62 | 63 | 64 | bytes dev::fromHex(std::string const& _s, WhenError _throw) 65 | { 66 | unsigned s = (_s.size() >= 2 && _s[0] == '0' && _s[1] == 'x') ? 2 : 0; 67 | std::vector ret; 68 | ret.reserve((_s.size() - s + 1) / 2); 69 | 70 | if (_s.size() % 2) 71 | { 72 | int h = fromHexChar(_s[s++]); 73 | if (h != -1) 74 | ret.push_back(h); 75 | else if (_throw == WhenError::Throw) 76 | BOOST_THROW_EXCEPTION(BadHexCharacter()); 77 | else 78 | return bytes(); 79 | } 80 | for (unsigned i = s; i < _s.size(); i += 2) 81 | { 82 | int h = fromHexChar(_s[i]); 83 | int l = fromHexChar(_s[i + 1]); 84 | if (h != -1 && l != -1) 85 | ret.push_back((byte)(h * 16 + l)); 86 | else if (_throw == WhenError::Throw) 87 | BOOST_THROW_EXCEPTION(BadHexCharacter()); 88 | else 89 | return bytes(); 90 | } 91 | return ret; 92 | } 93 | 94 | bytes dev::asNibbles(bytesConstRef const& _s) 95 | { 96 | std::vector ret; 97 | ret.reserve(_s.size() * 2); 98 | for (auto i: _s) 99 | { 100 | ret.push_back(i / 16); 101 | ret.push_back(i % 16); 102 | } 103 | return ret; 104 | } 105 | -------------------------------------------------------------------------------- /include/web3cpp/ethcore/ABI.h: -------------------------------------------------------------------------------- 1 | #ifndef ABI_H 2 | #define ABI_H 3 | 4 | #include 5 | 6 | #include 7 | 8 | using json = nlohmann::ordered_json; 9 | 10 | // Module that encodes/decodes ABI parameters for function calls. 11 | // https://web3js.readthedocs.io/en/v1.7.0/web3-eth-abi.html 12 | 13 | // TODO: 14 | // - Check if "array" types would actually be "mixed" 15 | // - Docs sometimes shows examples using only strings, other times with ints mixed in 16 | 17 | class ABI { 18 | public: 19 | // Encodes the function name to its ABI signature (first 4 bytes of the 20 | // sha3 hash of the function name including types). 21 | // If using the function name as string, it has to be in the form 22 | // `function(type,type,...)`, e.g. `myFunction(uint256,uint32[],bytes10,bytes)`. 23 | // If using a JSON interface object, please refer to 24 | // https://web3js.readthedocs.io/en/v1.7.0/glossary.html#json-interface 25 | std::string encodeFunctionSignature(std::string functionName); 26 | std::string encodeFunctionSignature(json functionObj); 27 | 28 | // Encodes the event name to its ABI signature (sha3 hash of the event 29 | // name including input types). Same details as above. 30 | std::string encodeEventSignature(std::string eventName); 31 | std::string encodeEventSignature(json eventObj); 32 | 33 | // Encodes a parameter based on its type to its ABI representation. 34 | // See https://docs.soliditylang.org/en/develop/types.html 35 | // for a list of types. 36 | //std::string encodeParameter(std::string type, mixed parameter); 37 | //std::string encodeParameter(json type, mixed parameter); 38 | 39 | // Encodes a function's parameters based on its JSON interface object. 40 | // Same details as above. 41 | //std::string encodeParameters(std::vector typesArray, array parameters); 42 | //std::string encodeParameters(std::vector typesArray, array parameters); 43 | //std::string encodeParameters(json typesArray, array parameters); 44 | 45 | // Encodes a function call using its JSON interface object and given parameters. 46 | //std::string encodeFunctionCall(json jsonInterface, array parameters); 47 | 48 | // Decodes an ABI encoded parameter to its intended type. 49 | //mixed decodeParameter(std::string type, std::string hexString); 50 | //mixed decodeParameter(json type, std::string hexString); 51 | 52 | // Decodes ABI encoded parameters to their intended types. 53 | json decodeParameters(std::vector typesArray, std::string hexString); 54 | json decodeParameters(std::vector typesArray, std::string hexString); 55 | json decodeParameters(json typesArray, std::string hexString); 56 | 57 | // Decodes ABI-encoded log data and indexed topic data. 58 | //json decodeLog(json inputs, std::string hexString, array topics); 59 | }; 60 | 61 | #endif // ABI_H 62 | -------------------------------------------------------------------------------- /tests/SolidityTest.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "inputs": [{"internalType": "uint256", "name": "item", "type": "uint256"}], 4 | "name": "testUint256", 5 | "outputs": [], 6 | "stateMutability": "nonpayable", 7 | "type": "function" 8 | }, 9 | { 10 | "inputs": [{"internalType": "address", "name": "item", "type": "address"}], 11 | "name": "testAddress", 12 | "outputs": [], 13 | "stateMutability": "nonpayable", 14 | "type": "function" 15 | }, 16 | { 17 | "inputs": [{"internalType": "bool", "name": "item", "type": "bool"}], 18 | "name": "testBool", 19 | "outputs": [], 20 | "stateMutability": "nonpayable", 21 | "type": "function" 22 | }, 23 | { 24 | "inputs": [{"internalType": "bytes", "name": "item", "type": "bytes"}], 25 | "name": "testBytes", 26 | "outputs": [], 27 | "stateMutability": "nonpayable", 28 | "type": "function" 29 | }, 30 | { 31 | "inputs": [{"internalType": "string", "name": "item", "type": "string"}], 32 | "name": "testString", 33 | "outputs": [], 34 | "stateMutability": "nonpayable", 35 | "type": "function" 36 | }, 37 | { 38 | "inputs": [{"internalType": "uint256[]", "name": "item", "type": "uint256[]"}], 39 | "name": "testUint256Array", 40 | "outputs": [], 41 | "stateMutability": "nonpayable", 42 | "type": "function" 43 | }, 44 | { 45 | "inputs": [{"internalType": "address[]", "name": "item", "type": "address[]"}], 46 | "name": "testAddressArray", 47 | "outputs": [], 48 | "stateMutability": "nonpayable", 49 | "type": "function" 50 | }, 51 | { 52 | "inputs": [{"internalType": "bool[]", "name": "item", "type": "bool[]"}], 53 | "name": "testBoolArray", 54 | "outputs": [], 55 | "stateMutability": "nonpayable", 56 | "type": "function" 57 | }, 58 | { 59 | "inputs": [{"internalType": "bytes[]", "name": "item", "type": "bytes[]"}], 60 | "name": "testBytesArray", 61 | "outputs": [], 62 | "stateMutability": "nonpayable", 63 | "type": "function" 64 | }, 65 | { 66 | "inputs": [{"internalType": "string[]", "name": "item", "type": "string[]"}], 67 | "name": "testStringArray", 68 | "outputs": [], 69 | "stateMutability": "nonpayable", 70 | "type": "function" 71 | }, 72 | { 73 | "inputs": [ 74 | { "internalType": "uint256", "name": "item1", "type": "uint256" }, 75 | { "internalType": "address", "name": "item2", "type": "address" }, 76 | { "internalType": "bool", "name": "item3", "type": "bool" }, 77 | { "internalType": "bytes", "name": "item4", "type": "bytes" }, 78 | { "internalType": "string", "name": "item5", "type": "string" }, 79 | { "internalType": "uint256[]", "name": "item6", "type": "uint256[]" }, 80 | { "internalType": "address[]", "name": "item7", "type": "address[]" }, 81 | { "internalType": "bool[]", "name": "item8", "type": "bool[]" }, 82 | { "internalType": "bytes[]", "name": "item9", "type": "bytes[]" }, 83 | { "internalType": "string[]", "name": "item10", "type": "string[]" } 84 | ], 85 | "name": "testAll", 86 | "outputs": [], 87 | "stateMutability": "nonpayable", 88 | "type": "function" 89 | } 90 | ] 91 | -------------------------------------------------------------------------------- /cmake/cable/README.md: -------------------------------------------------------------------------------- 1 | # Cable 2 | 3 | [![readme style: standard][readme style standard badge]][standard readme] 4 | 5 | > Cable: CMake Bootstrap Library 6 | 7 | Cable is a set of CMake modules and scripts containing common patterns used 8 | in CMake-based C++ projects. The design goal is to be pragmatic rather than 9 | generic so the number of provided options is minimal. The Cable modules are 10 | independent and it is easy to use them individually. 11 | 12 | 13 | ## Table of Contents 14 | 15 | - [Install](#install) 16 | - [Usage](#usage) 17 | - [Maintainer](#maintainer) 18 | - [License](#license) 19 | 20 | 21 | ## Install 22 | 23 | The suggested Cable location is `cmake/cable` relative to your project root directory. 24 | 25 | 26 | ### With cable.cmake script 27 | 28 | Copy [cable.cmake](cable.cmake) script to your project. 29 | Then use it to download individual Cable CMake modules. 30 | 31 | ```bash 32 | ./cable.cmake install CableBuildType 33 | ``` 34 | 35 | 36 | ### As git subtree 37 | 38 | Adding a dependency project as a [git subtree] is just a copy of the source code 39 | done in a bit more systematic way. 40 | 41 | If you are not familiar with managing dependencies with git subtree read the 42 | [Git subtree: the alternative to Git submodule][git subtree tutorial]. 43 | 44 | #### To install 45 | 46 | ```sh 47 | git remote add cable https://github.com/ethereum/cable 48 | git subtree add --prefix cmake/cable cable master --squash 49 | ``` 50 | 51 | #### To update 52 | 53 | ```sh 54 | git subtree pull --prefix cmake/cable cable master --squash 55 | ``` 56 | 57 | ### As git submodule 58 | 59 | Include the Cable library as [git submodule] in your project. 60 | 61 | ```sh 62 | git submodule add https://github.com/ethereum/cable cmake/cable 63 | ``` 64 | 65 | ## Usage 66 | 67 | Cable contains the `bootstrap.cmake` file that initializes the library. 68 | Start by including this file in your main `CMakeLists.txt` from the Cable 69 | submodule/subtree or any other location. The `bootstrap.cmake` must be included 70 | before the `project()` command. After that, you can include and use other 71 | Cable modules. 72 | 73 | ### Example 74 | 75 | ```cmake 76 | cmake_minimum_required(VERSION 3.5) 77 | 78 | include(cmake/cable/bootstrap.cmake) 79 | include(CableBuildType) 80 | 81 | project(tothemoon) 82 | 83 | cable_set_build_type(DEFAULT RelWithDebInfo CONFIGURATION_TYPES Debug Release RelWithDebInfo) 84 | ``` 85 | 86 | 87 | ## Maintainer 88 | 89 | Paweł Bylica [@chfast] 90 | 91 | ## License 92 | 93 | Licensed under the [Apache License, Version 2.0]. 94 | 95 | 96 | [@chfast]: https://github.com/chfast 97 | [Apache License, Version 2.0]: LICENSE 98 | [git submodule]: https://git-scm.com/book/en/v2/Git-Tools-Submodules 99 | [git subtree]: https://github.com/git/git/blob/master/contrib/subtree/git-subtree.txt 100 | [git subtree tutorial]: https://www.atlassian.com/blog/git/alternatives-to-git-submodule-git-subtree 101 | [standard readme]: https://github.com/RichardLitt/standard-readme 102 | 103 | [readme style standard badge]: https://img.shields.io/badge/readme%20style-standard-brightgreen.svg?style=flat-square 104 | -------------------------------------------------------------------------------- /include/web3cpp/Provider.h: -------------------------------------------------------------------------------- 1 | #ifndef PROVIDER_H 2 | #define PROVIDER_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include 10 | 11 | using json = nlohmann::ordered_json; 12 | 13 | // Forward declaration 14 | class Web3; 15 | 16 | /** 17 | * Abstraction for a single provider. 18 | */ 19 | 20 | class Provider { 21 | private: 22 | const std::string _id; ///< The ID of the provider. 23 | std::string name; ///< The name of the provider. 24 | std::string host; ///< The host of the provider. 25 | std::string target; ///< The RPC target of the provider. 26 | uint64_t port; ///< The port of the provider. 27 | uint64_t chainId; ///< The chain ID of the provider. 28 | std::string currency; ///< The currency the provider uses. 29 | std::string explorerUrl; ///< The block explorer URL the provider uses. 30 | 31 | /** 32 | * A JSON object with predefined provider templates. 33 | * Each provider template is linked to a short alias. 34 | * Use getPresets() to check all available aliases/templates. 35 | */ 36 | static json presets; 37 | 38 | /** 39 | * Sets the current provider to a template. 40 | * @param data The provider template object. 41 | */ 42 | void _setData(json data); 43 | void setProvider(const Provider &p); 44 | 45 | public: 46 | std::mutex mutable lock; ///< Mutex to manage read/write access to the provider object. 47 | 48 | /** 49 | * Default constructor. 50 | * @param id (optional) A template alias. Defaults to "avax-c-main" (Avalanche Mainnet). 51 | */ 52 | Provider(std::string id = "avax-c-main"); 53 | 54 | /// Copy constructor. 55 | Provider(const Provider &p); 56 | 57 | /** 58 | * Custom constructor. 59 | * @param name The provider's name. 60 | * @param host The provider's host. 61 | * @param target The provider's %RPC endpoint target. 62 | * @param port The provider's port. 63 | * @param chainId The provider's chain ID. 64 | * @param currency The provider's used currency. 65 | * @param explorerUrl The provider's used block explorer URL. 66 | */ 67 | Provider( 68 | std::string name, std::string host, std::string target, uint64_t port, 69 | uint64_t chainId, std::string currency, std::string explorerUrl 70 | ); 71 | 72 | const std::string& getName() const { return this->name; } ///< Getter for provider name. 73 | const std::string& getHost() const { return this->host; } ///< Getter for provider host. 74 | const std::string& getTarget() const { return this->target; } ///< Getter for provider %RPC endpoint target. 75 | const uint64_t& getPort() const { return this->port; } ///< Getter for provider port. 76 | const uint64_t& getChainId() const { return this->chainId; } ///< Getter for provider chain ID. 77 | const std::string& getCurrency() const { return this->currency; } ///< Getter for provider currency. 78 | const std::string& getExplorerUrl() const { return this->explorerUrl; } ///< Getter for provider block explorer URL. 79 | const static json& getPresets() { return Provider::presets; } ///< Getter for provider presets. 80 | 81 | friend class Web3; 82 | }; 83 | 84 | #endif // PROVIDER_H 85 | -------------------------------------------------------------------------------- /tests/provider.cpp: -------------------------------------------------------------------------------- 1 | #include "../src/libs/catch2/catch_amalgamated.hpp" 2 | #include "../include/web3cpp/Provider.h" 3 | 4 | 5 | namespace TProvider { 6 | TEST_CASE("Provider Class Tests","[provider]") { 7 | SECTION("Provider std::string constructor") { 8 | Provider providerAvaxCCHain("avax-c-main"); 9 | REQUIRE(providerAvaxCCHain.getName() == "Avalanche Mainnet (C-Chain)"); 10 | REQUIRE(providerAvaxCCHain.getHost() == "api.avax.network"); 11 | REQUIRE(providerAvaxCCHain.getTarget() == "/ext/bc/C/rpc"); 12 | REQUIRE(providerAvaxCCHain.getPort() == 443); 13 | REQUIRE(providerAvaxCCHain.getChainId() == 43114); 14 | REQUIRE(providerAvaxCCHain.getCurrency() == "AVAX"); 15 | REQUIRE(providerAvaxCCHain.getExplorerUrl() == "https://snowtrace.io"); 16 | 17 | Provider providerAvaxCCHainTest("avax-c-test"); 18 | REQUIRE(providerAvaxCCHainTest.getName() == "Avalanche Testnet (C-Chain)"); 19 | REQUIRE(providerAvaxCCHainTest.getHost() == "api.avax-test.network"); 20 | REQUIRE(providerAvaxCCHainTest.getTarget() == "/ext/bc/C/rpc"); 21 | REQUIRE(providerAvaxCCHainTest.getPort() == 443); 22 | REQUIRE(providerAvaxCCHainTest.getChainId() == 43113); 23 | REQUIRE(providerAvaxCCHainTest.getCurrency() == "AVAX"); 24 | REQUIRE(providerAvaxCCHainTest.getExplorerUrl() == "https://testnet.snowtrace.io"); 25 | 26 | // Provider defaults to avax-c-main if preset does not exist 27 | Provider providerFallback("aaaaaaaa"); 28 | REQUIRE(providerAvaxCCHain.getName() == "Avalanche Mainnet (C-Chain)"); 29 | REQUIRE(providerAvaxCCHain.getHost() == "api.avax.network"); 30 | REQUIRE(providerAvaxCCHain.getTarget() == "/ext/bc/C/rpc"); 31 | REQUIRE(providerAvaxCCHain.getPort() == 443); 32 | REQUIRE(providerAvaxCCHain.getChainId() == 43114); 33 | REQUIRE(providerAvaxCCHain.getCurrency() == "AVAX"); 34 | REQUIRE(providerAvaxCCHain.getExplorerUrl() == "https://snowtrace.io"); 35 | 36 | } 37 | 38 | SECTION("Provider Copy Constructor") { 39 | Provider provider("avax-c-test"); 40 | Provider providerCopy(provider); 41 | REQUIRE(providerCopy.getName() == provider.getName()); 42 | REQUIRE(providerCopy.getHost() == provider.getHost()); 43 | REQUIRE(providerCopy.getTarget() == provider.getTarget()); 44 | REQUIRE(providerCopy.getPort() == provider.getPort()); 45 | REQUIRE(providerCopy.getChainId() == provider.getChainId()); 46 | REQUIRE(providerCopy.getCurrency() == provider.getCurrency()); 47 | REQUIRE(providerCopy.getExplorerUrl() == provider.getExplorerUrl()); 48 | } 49 | 50 | SECTION("Provider complete constructor") { 51 | std::string name = "Avalanche Testnet (C-Chain)"; 52 | std::string host = "api.avax-test.network"; 53 | std::string target = "/ext/bc/C/rpc"; 54 | uint64_t port = 443; 55 | uint64_t chainId = 43113; 56 | std::string currency = "AVAX"; 57 | std::string explorerUrl = "https://testnet.snowtrace.io"; 58 | Provider provider( 59 | name, host, target, port, chainId, currency, explorerUrl 60 | ); 61 | REQUIRE(provider.getName() == name); 62 | REQUIRE(provider.getHost() == host); 63 | REQUIRE(provider.getTarget() == target); 64 | REQUIRE(provider.getPort() == port); 65 | REQUIRE(provider.getChainId() == chainId); 66 | REQUIRE(provider.getCurrency() == currency); 67 | REQUIRE(provider.getExplorerUrl() == explorerUrl); 68 | } 69 | } 70 | } -------------------------------------------------------------------------------- /src/devcore/TrieCommon.cpp: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #include 6 | #include 7 | 8 | namespace dev 9 | { 10 | 11 | h256 const EmptyTrie = sha3(rlp("")); 12 | 13 | /* 14 | * Hex-prefix Notation. First nibble has flags: oddness = 2^0 & termination = 2^1 15 | * NOTE: the "termination marker" and "leaf-node" specifier are completely equivalent. 16 | * [0,0,1,2,3,4,5] 0x10012345 17 | * [0,1,2,3,4,5] 0x00012345 18 | * [1,2,3,4,5] 0x112345 19 | * [0,0,1,2,3,4] 0x00001234 20 | * [0,1,2,3,4] 0x101234 21 | * [1,2,3,4] 0x001234 22 | * [0,0,1,2,3,4,5,T] 0x30012345 23 | * [0,0,1,2,3,4,T] 0x20001234 24 | * [0,1,2,3,4,5,T] 0x20012345 25 | * [1,2,3,4,5,T] 0x312345 26 | * [1,2,3,4,T] 0x201234 27 | */ 28 | 29 | std::string hexPrefixEncode(bytes const& _hexVector, bool _leaf, int _begin, int _end) 30 | { 31 | unsigned begin = _begin; 32 | unsigned end = _end < 0 ? _hexVector.size() + 1 + _end : _end; 33 | bool odd = ((end - begin) % 2) != 0; 34 | 35 | std::string ret(1, ((_leaf ? 2 : 0) | (odd ? 1 : 0)) * 16); 36 | if (odd) 37 | { 38 | ret[0] |= _hexVector[begin]; 39 | ++begin; 40 | } 41 | for (unsigned i = begin; i < end; i += 2) 42 | ret += _hexVector[i] * 16 + _hexVector[i + 1]; 43 | return ret; 44 | } 45 | 46 | std::string hexPrefixEncode(bytesConstRef _data, bool _leaf, int _beginNibble, int _endNibble, unsigned _offset) 47 | { 48 | unsigned begin = _beginNibble + _offset; 49 | unsigned end = (_endNibble < 0 ? ((int)(_data.size() * 2 - _offset) + 1) + _endNibble : _endNibble) + _offset; 50 | bool odd = (end - begin) & 1; 51 | 52 | std::string ret(1, ((_leaf ? 2 : 0) | (odd ? 1 : 0)) * 16); 53 | ret.reserve((end - begin) / 2 + 1); 54 | 55 | unsigned d = odd ? 1 : 2; 56 | for (auto i = begin; i < end; ++i, ++d) 57 | { 58 | byte n = nibble(_data, i); 59 | if (d & 1) // odd 60 | ret.back() |= n; // or the nibble onto the back 61 | else 62 | ret.push_back(n << 4); // push the nibble on to the back << 4 63 | } 64 | return ret; 65 | } 66 | 67 | std::string hexPrefixEncode(bytesConstRef _d1, unsigned _o1, bytesConstRef _d2, unsigned _o2, bool _leaf) 68 | { 69 | unsigned begin1 = _o1; 70 | unsigned end1 = _d1.size() * 2; 71 | unsigned begin2 = _o2; 72 | unsigned end2 = _d2.size() * 2; 73 | 74 | bool odd = (end1 - begin1 + end2 - begin2) & 1; 75 | 76 | std::string ret(1, ((_leaf ? 2 : 0) | (odd ? 1 : 0)) * 16); 77 | ret.reserve((end1 - begin1 + end2 - begin2) / 2 + 1); 78 | 79 | unsigned d = odd ? 1 : 2; 80 | for (auto i = begin1; i < end1; ++i, ++d) 81 | { 82 | byte n = nibble(_d1, i); 83 | if (d & 1) // odd 84 | ret.back() |= n; // or the nibble onto the back 85 | else 86 | ret.push_back(n << 4); // push the nibble on to the back << 4 87 | } 88 | for (auto i = begin2; i < end2; ++i, ++d) 89 | { 90 | byte n = nibble(_d2, i); 91 | if (d & 1) // odd 92 | ret.back() |= n; // or the nibble onto the back 93 | else 94 | ret.push_back(n << 4); // push the nibble on to the back << 4 95 | } 96 | return ret; 97 | } 98 | 99 | byte uniqueInUse(RLP const& _orig, byte except) 100 | { 101 | byte used = 255; 102 | for (unsigned i = 0; i < 17; ++i) 103 | if (i != except && !_orig[i].isEmpty()) 104 | { 105 | if (used == 255) 106 | used = (byte)i; 107 | else 108 | return 255; 109 | } 110 | return used; 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /include/web3cpp/devcore/Exceptions.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #pragma once 6 | 7 | #include "FixedHash.h" 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | namespace dev 20 | { 21 | /// Base class for all exceptions. 22 | struct Exception : virtual std::exception, virtual boost::exception 23 | { 24 | const char* what() const noexcept override { return boost::diagnostic_information_what(*this); } 25 | }; 26 | 27 | #define DEV_SIMPLE_EXCEPTION(X) \ 28 | struct X : virtual Exception \ 29 | { \ 30 | } 31 | 32 | /// Base class for all RLP exceptions. 33 | struct RLPException : virtual Exception 34 | { 35 | }; 36 | #define DEV_SIMPLE_EXCEPTION_RLP(X) \ 37 | struct X : virtual RLPException \ 38 | { \ 39 | } 40 | 41 | DEV_SIMPLE_EXCEPTION_RLP(BadCast); 42 | DEV_SIMPLE_EXCEPTION_RLP(BadRLP); 43 | DEV_SIMPLE_EXCEPTION_RLP(OversizeRLP); 44 | DEV_SIMPLE_EXCEPTION_RLP(UndersizeRLP); 45 | 46 | DEV_SIMPLE_EXCEPTION(BadHexCharacter); 47 | DEV_SIMPLE_EXCEPTION(NoNetworking); 48 | DEV_SIMPLE_EXCEPTION(NoUPnPDevice); 49 | DEV_SIMPLE_EXCEPTION(RootNotFound); 50 | DEV_SIMPLE_EXCEPTION(BadRoot); 51 | DEV_SIMPLE_EXCEPTION(FileError); 52 | DEV_SIMPLE_EXCEPTION(Overflow); 53 | DEV_SIMPLE_EXCEPTION(FailedInvariant); 54 | DEV_SIMPLE_EXCEPTION(ValueTooLarge); 55 | DEV_SIMPLE_EXCEPTION(UnknownField); 56 | DEV_SIMPLE_EXCEPTION(MissingField); 57 | DEV_SIMPLE_EXCEPTION(SyntaxError); 58 | DEV_SIMPLE_EXCEPTION(WrongFieldType); 59 | DEV_SIMPLE_EXCEPTION(InterfaceNotSupported); 60 | DEV_SIMPLE_EXCEPTION(ExternalFunctionFailure); 61 | DEV_SIMPLE_EXCEPTION(WaitTimeout); 62 | 63 | // error information to be added to exceptions 64 | using errinfo_invalidSymbol = boost::error_info; 65 | using errinfo_wrongAddress = boost::error_info; 66 | using errinfo_comment = boost::error_info; 67 | using errinfo_required = boost::error_info; 68 | using errinfo_got = boost::error_info; 69 | using errinfo_min = boost::error_info; 70 | using errinfo_max = boost::error_info; 71 | using RequirementError = boost::tuple; 72 | using RequirementErrorComment = boost::tuple; 73 | using errinfo_hash256 = boost::error_info; 74 | using errinfo_required_h256 = boost::error_info; 75 | using errinfo_got_h256 = boost::error_info; 76 | using Hash256RequirementError = boost::tuple; 77 | using errinfo_extraData = boost::error_info; 78 | using errinfo_externalFunction = boost::errinfo_api_function; 79 | using errinfo_interface = boost::error_info; 80 | using errinfo_path = boost::error_info; 81 | using errinfo_nodeID = boost::error_info; 82 | using errinfo_nestedException = boost::errinfo_nested_exception; 83 | } 84 | -------------------------------------------------------------------------------- /cmake/cable/buildinfo/buildinfo.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library. 2 | # Copyright 2018-2019 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | string(TOUPPER "${PROJECT_NAME}" PROJECT_NAME_UPPERCASE) 6 | string(TOLOWER "${SYSTEM_NAME}" SYSTEM_NAME) 7 | string(TOLOWER "${SYSTEM_PROCESSOR}" SYSTEM_PROCESSOR) 8 | string(TOLOWER "${COMPILER_ID}" COMPILER_ID) 9 | string(TOLOWER "${BUILD_TYPE}" BUILD_TYPE) 10 | string(TIMESTAMP TIMESTAMP) 11 | 12 | # Read the git info from a file. The gitinfo is suppose to update the file 13 | # only if the information has changed. 14 | file(STRINGS ${OUTPUT_DIR}/gitinfo.txt gitinfo) 15 | list(LENGTH gitinfo gitinfo_len) 16 | if(gitinfo_len LESS 3) 17 | message(WARNING "Git info not available") 18 | else() 19 | list(GET gitinfo 0 describe) 20 | list(GET gitinfo 1 GIT_BRANCH) 21 | list(GET gitinfo 2 GIT_ORIGIN_URL) 22 | endif() 23 | 24 | # The output of `git describe --always --long --tags --match=v*`. 25 | string(REGEX MATCH "(v(.+)-([0-9]+)-g)?([0-9a-f]+)(-dirty)?" match "${describe}") 26 | 27 | if(DEFINED describe AND NOT match) 28 | message(WARNING "Cannot parse git describe: ${describe}") 29 | endif() 30 | 31 | set(GIT_LATEST_PROJECT_VERSION ${CMAKE_MATCH_2}) 32 | set(GIT_LATEST_PROJECT_VERSION_DISTANCE ${CMAKE_MATCH_3}) 33 | set(GIT_COMMIT_HASH ${CMAKE_MATCH_4}) 34 | if(CMAKE_MATCH_5) 35 | set(GIT_DIRTY TRUE) 36 | set(dirty_msg " (dirty)") 37 | else() 38 | set(GIT_DIRTY FALSE) 39 | endif() 40 | 41 | if(GIT_COMMIT_HASH) 42 | string(SUBSTRING ${GIT_COMMIT_HASH} 0 8 abbrev) 43 | set(version_commit "+commit.${abbrev}") 44 | if(GIT_DIRTY) 45 | set(version_commit "${version_commit}.dirty") 46 | endif() 47 | endif() 48 | 49 | if(NOT PROJECT_VERSION) 50 | message(WARNING "PROJECT_VERSION not specified") 51 | endif() 52 | 53 | if(PROJECT_VERSION STREQUAL GIT_LATEST_PROJECT_VERSION) 54 | if(${GIT_LATEST_PROJECT_VERSION_DISTANCE} GREATER 0) 55 | set(PROJECT_VERSION "${PROJECT_VERSION}-${GIT_LATEST_PROJECT_VERSION_DISTANCE}${version_commit}") 56 | endif() 57 | else() 58 | if(GIT_LATEST_PROJECT_VERSION) 59 | message(WARNING "Git project version mismatch: '${GIT_LATEST_PROJECT_VERSION}' vs '${PROJECT_VERSION}'") 60 | endif() 61 | set(PROJECT_VERSION "${PROJECT_VERSION}${version_commit}") 62 | endif() 63 | 64 | if(PROJECT_VERSION MATCHES "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$") 65 | set(PROJECT_VERSION_IS_PRERELEASE false) 66 | else() 67 | set(PROJECT_VERSION_IS_PRERELEASE true) 68 | set(prerelease_comment " (prerelease)") 69 | endif() 70 | 71 | message( 72 | " Project Version: ${PROJECT_VERSION}${prerelease_comment}\n" 73 | " System Name: ${SYSTEM_NAME}\n" 74 | " System Processor: ${SYSTEM_PROCESSOR}\n" 75 | " Compiler ID: ${COMPILER_ID}\n" 76 | " Compiler Version: ${COMPILER_VERSION}\n" 77 | " Build Type: ${BUILD_TYPE}\n" 78 | " Git Info: ${GIT_LATEST_PROJECT_VERSION}/${GIT_LATEST_PROJECT_VERSION_DISTANCE}/${GIT_COMMIT_HASH}${dirty_msg}\n" 79 | " Git Branch: ${GIT_BRANCH}\n" 80 | " Git Origin URL: ${GIT_ORIGIN_URL}\n" 81 | " Timestamp: ${TIMESTAMP}" 82 | ) 83 | 84 | configure_file(${CMAKE_CURRENT_LIST_DIR}/buildinfo.c.in ${OUTPUT_DIR}/buildinfo.c) 85 | configure_file(${CMAKE_CURRENT_LIST_DIR}/buildinfo.json.in ${OUTPUT_DIR}/buildinfo.json) 86 | configure_file(${CMAKE_CURRENT_LIST_DIR}/buildinfo.sh.in ${OUTPUT_DIR}/buildinfo.sh) 87 | configure_file(${CMAKE_CURRENT_LIST_DIR}/buildinfo.ps1.in ${OUTPUT_DIR}/buildinfo.ps1) 88 | 89 | configure_file(${CMAKE_CURRENT_LIST_DIR}/version.h.in ${OUTPUT_DIR}/version.h) 90 | -------------------------------------------------------------------------------- /src/devcore/TrieHash.cpp: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #include 6 | #include 7 | #include // @TODO replace ASAP! 8 | 9 | namespace dev 10 | { 11 | 12 | void hash256aux(HexMap const& _s, HexMap::const_iterator _begin, HexMap::const_iterator _end, unsigned _preLen, RLPStream& _rlp); 13 | 14 | void hash256rlp(HexMap const& _s, HexMap::const_iterator _begin, HexMap::const_iterator _end, unsigned _preLen, RLPStream& _rlp) 15 | { 16 | if (_begin == _end) 17 | _rlp << ""; // NULL 18 | else if (std::next(_begin) == _end) 19 | { 20 | // only one left - terminate with the pair. 21 | _rlp.appendList(2) << hexPrefixEncode(_begin->first, true, _preLen) << _begin->second; 22 | } 23 | else 24 | { 25 | // find the number of common prefix nibbles shared 26 | // i.e. the minimum number of nibbles shared at the beginning between the first hex string and each successive. 27 | unsigned sharedPre = (unsigned)-1; 28 | unsigned c = 0; 29 | for (auto i = std::next(_begin); i != _end && sharedPre; ++i, ++c) 30 | { 31 | unsigned x = std::min(sharedPre, std::min((unsigned)_begin->first.size(), (unsigned)i->first.size())); 32 | unsigned shared = _preLen; 33 | for (; shared < x && _begin->first[shared] == i->first[shared]; ++shared) {} 34 | sharedPre = std::min(shared, sharedPre); 35 | } 36 | if (sharedPre > _preLen) 37 | { 38 | // if they all have the same next nibble, we also want a pair. 39 | _rlp.appendList(2) << hexPrefixEncode(_begin->first, false, _preLen, (int)sharedPre); 40 | hash256aux(_s, _begin, _end, (unsigned)sharedPre, _rlp); 41 | } 42 | else 43 | { 44 | // otherwise enumerate all 16+1 entries. 45 | _rlp.appendList(17); 46 | auto b = _begin; 47 | if (_preLen == b->first.size()) 48 | ++b; 49 | for (auto i = 0; i < 16; ++i) 50 | { 51 | auto n = b; 52 | for (; n != _end && n->first[_preLen] == i; ++n) {} 53 | if (b == n) 54 | _rlp << ""; 55 | else 56 | hash256aux(_s, b, n, _preLen + 1, _rlp); 57 | b = n; 58 | } 59 | if (_preLen == _begin->first.size()) 60 | _rlp << _begin->second; 61 | else 62 | _rlp << ""; 63 | 64 | } 65 | } 66 | } 67 | 68 | void hash256aux(HexMap const& _s, HexMap::const_iterator _begin, HexMap::const_iterator _end, unsigned _preLen, RLPStream& _rlp) 69 | { 70 | RLPStream rlp; 71 | hash256rlp(_s, _begin, _end, _preLen, rlp); 72 | if (rlp.out().size() < 32) 73 | { 74 | // RECURSIVE RLP 75 | _rlp.appendRaw(rlp.out()); 76 | } 77 | else 78 | _rlp << sha3(rlp.out()); 79 | } 80 | 81 | bytes rlp256(BytesMap const& _s) 82 | { 83 | // build patricia tree. 84 | if (_s.empty()) 85 | return rlp(""); 86 | HexMap hexMap; 87 | for (auto i = _s.rbegin(); i != _s.rend(); ++i) 88 | hexMap[asNibbles(bytesConstRef(&i->first))] = i->second; 89 | RLPStream s; 90 | hash256rlp(hexMap, hexMap.cbegin(), hexMap.cend(), 0, s); 91 | return s.out(); 92 | } 93 | 94 | h256 hash256(BytesMap const& _s) 95 | { 96 | return sha3(rlp256(_s)); 97 | } 98 | 99 | h256 orderedTrieRoot(std::vector const& _data) 100 | { 101 | BytesMap m; 102 | unsigned j = 0; 103 | for (auto i: _data) 104 | m[rlp(j++)] = i; 105 | return hash256(m); 106 | } 107 | 108 | h256 orderedTrieRoot(std::vector const& _data) 109 | { 110 | BytesMap m; 111 | unsigned j = 0; 112 | for (auto i: _data) 113 | m[rlp(j++)] = i.toBytes(); 114 | return hash256(m); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /include/web3cpp/devcore/SHA3.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #pragma once 6 | 7 | #include "FixedHash.h" 8 | #include "vector_ref.h" 9 | 10 | #include 11 | 12 | #include 13 | 14 | namespace dev 15 | { 16 | 17 | // SHA-3 convenience routines. 18 | 19 | /// Calculate SHA3-256 hash of the given input and load it into the given output. 20 | /// @returns false if o_output.size() != 32. 21 | bool sha3(bytesConstRef _input, bytesRef o_output) noexcept; 22 | 23 | /// Calculate SHA3-256 hash of the given input, returning as a 256-bit hash. 24 | inline h256 sha3(bytesConstRef _input) noexcept 25 | { 26 | h256 ret; 27 | sha3(_input, ret.ref()); 28 | return ret; 29 | } 30 | 31 | inline SecureFixedHash<32> sha3Secure(bytesConstRef _input) noexcept 32 | { 33 | SecureFixedHash<32> ret; 34 | sha3(_input, ret.writable().ref()); 35 | return ret; 36 | } 37 | 38 | /// Calculate SHA3-256 hash of the given input, returning as a 256-bit hash. 39 | inline h256 sha3(bytes const& _input) noexcept 40 | { 41 | return sha3(bytesConstRef(&_input)); 42 | } 43 | 44 | inline SecureFixedHash<32> sha3Secure(bytes const& _input) noexcept 45 | { 46 | return sha3Secure(bytesConstRef(&_input)); 47 | } 48 | 49 | /// Calculate SHA3-256 hash of the given input (presented as a binary-filled string), returning as a 256-bit hash. 50 | inline h256 sha3(std::string const& _input) noexcept 51 | { 52 | return sha3(bytesConstRef(_input)); 53 | } 54 | 55 | inline SecureFixedHash<32> sha3Secure(std::string const& _input) noexcept 56 | { 57 | return sha3Secure(bytesConstRef(_input)); 58 | } 59 | 60 | /// Keccak hash variant optimized for hashing 256-bit hashes. 61 | inline h256 sha3(h256 const& _input) noexcept 62 | { 63 | ethash::hash256 hash = ethash::keccak256_32(_input.data()); 64 | return h256{hash.bytes, h256::ConstructFromPointer}; 65 | } 66 | 67 | /// Calculate SHA3-256 hash of the given input (presented as a FixedHash), returns a 256-bit hash. 68 | template 69 | inline h256 sha3(FixedHash const& _input) noexcept 70 | { 71 | return sha3(_input.ref()); 72 | } 73 | 74 | template 75 | inline SecureFixedHash<32> sha3Secure(FixedHash const& _input) noexcept 76 | { 77 | return sha3Secure(_input.ref()); 78 | } 79 | 80 | /// Fully secure variants are equivalent for sha3 and sha3Secure. 81 | inline SecureFixedHash<32> sha3(bytesSec const& _input) noexcept 82 | { 83 | return sha3Secure(_input.ref()); 84 | } 85 | 86 | inline SecureFixedHash<32> sha3Secure(bytesSec const& _input) noexcept 87 | { 88 | return sha3Secure(_input.ref()); 89 | } 90 | 91 | template 92 | inline SecureFixedHash<32> sha3(SecureFixedHash const& _input) noexcept 93 | { 94 | return sha3Secure(_input.ref()); 95 | } 96 | 97 | template 98 | inline SecureFixedHash<32> sha3Secure(SecureFixedHash const& _input) noexcept 99 | { 100 | return sha3Secure(_input.ref()); 101 | } 102 | 103 | /// Calculate SHA3-256 hash of the given input, possibly interpreting it as nibbles, and return the hash as a string filled with binary data. 104 | inline std::string sha3(std::string const& _input, bool _isNibbles) 105 | { 106 | return asString((_isNibbles ? sha3(fromHex(_input)) : sha3(bytesConstRef(&_input))).asBytes()); 107 | } 108 | 109 | /// Calculate SHA3-256 MAC 110 | inline void sha3mac(bytesConstRef _secret, bytesConstRef _plain, bytesRef _output) 111 | { 112 | sha3(_secret.toBytes() + _plain.toBytes()).ref().populate(_output); 113 | } 114 | 115 | extern h256 const EmptySHA3; 116 | 117 | extern h256 const EmptyListSHA3; 118 | 119 | } 120 | -------------------------------------------------------------------------------- /include/web3cpp/Error.h: -------------------------------------------------------------------------------- 1 | #ifndef ERROR_H 2 | #define ERROR_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | /** 10 | * Class for handling custom error codes and messages. 11 | * When an error object is created, it can only be set *once*, so it's assumed 12 | * that when an error object is passed as an argument to a function, it will 13 | * always be set to something and can't be reused after. 14 | */ 15 | 16 | class Error { 17 | private: 18 | /** 19 | * Fixed map for all the known error codes that can be set. 20 | * List of error codes is as follows: 21 | * \arg \c 0 - **No %Error** 22 | * \arg \c 1 - **Incorrect Password** 23 | * \arg \c 2 - **%Database Insert Failed** 24 | * \arg \c 3 - **%Account Exists** 25 | * \arg \c 4 - **Invalid Hex Data** 26 | * \arg \c 5 - **Invalid Address** 27 | * \arg \c 6 - **Invalid Hash Length** 28 | * \arg \c 7 - **Key Derivation Failed** 29 | * \arg \c 8 - **Key Encryption Failed** 30 | * \arg \c 9 - **Invalid Block Number** 31 | * \arg \c 10 - **Invalid Number** 32 | * \arg \c 11 - **Transaction Build %Error** 33 | * \arg \c 12 - **Transaction Sign %Error** 34 | * \arg \c 13 - **Transaction Send %Error** 35 | * \arg \c 14 - **Key Derivation Invalid Length** 36 | * \arg \c 15 - **Key Decryption MAC Mismatch** 37 | * \arg \c 16 - **Key Decryption Failed** 38 | * \arg \c 17 - **ABI Functor Not Found** 39 | * \arg \c 18 - **ABI Invalid Arguments Length** 40 | * \arg \c 19 - **ABI Invalid JSON Array** 41 | * \arg \c 20 - **ABI Invalid Uint256 Array** 42 | * \arg \c 21 - **ABI Invalid Address Array** 43 | * \arg \c 22 - **ABI Invalid Boolean Array** 44 | * \arg \c 23 - **ABI Invalid Bytes Array** 45 | * \arg \c 24 - **ABI Invalid String Array** 46 | * \arg \c 25 - **ABI Invalid Uint256** 47 | * \arg \c 26 - **ABI Invalid Address** 48 | * \arg \c 27 - **ABI Invalid Boolean** 49 | * \arg \c 28 - **ABI Invalid Bytes** 50 | * \arg \c 29 - **ABI Invalid String** 51 | * \arg \c 30 - **ABI Invalid Function** 52 | * \arg \c 31 - **ABI Unsupported Or Invalid Type** 53 | * \arg \c 32 - **ABI Missing Type Or Value** 54 | * \arg \c 33 - **JSON File Does Not Exist** 55 | * \arg \c 34 - **JSON File Read %Error** 56 | * \arg \c 35 - **JSON File Write %Error** 57 | * \arg \c 999 - **Unknown %Error** 58 | */ 59 | static const std::map codeMap; 60 | 61 | uint64_t code = 0; ///< Code for the set error object. 62 | std::string message; ///< Message for the set error object. 63 | bool isSet = false; ///< Indicates if error object is already set. 64 | std::mutex lock; ///< Mutex for managing read/write access to the error object. 65 | 66 | public: 67 | /** 68 | * Set the error code in the object, if it isn't already set. 69 | * @param errorCode The code that will be set. If it doesn't exist in the code map, 70 | * it'll be automatically set to the last one ("Unknown Error"). 71 | */ 72 | void setCode(uint64_t errorCode); 73 | 74 | /** 75 | * Get the error code that was set. 76 | * @return The error code. 77 | */ 78 | uint64_t getCode(); 79 | 80 | /** 81 | * Get the message for the error code that was set. 82 | * @return The message string. 83 | */ 84 | std::string what(); 85 | 86 | bool operator==(uint64_t code) const { return this->code == code; } ///< Checks if the error code on two Error objects are equal. 87 | bool operator!=(uint64_t code) const { return this->code != code; } ///< Checks if the error code on two Error objects are not equal. 88 | bool operator!() const { return this->code != 0; } ///< Checks if the error code on the Error object is different from 0. 89 | }; 90 | 91 | #endif // ERROR_H 92 | -------------------------------------------------------------------------------- /cmake/cable/CableBuildInfo.cmake: -------------------------------------------------------------------------------- 1 | # Cable: CMake Bootstrap Library 2 | # Copyright 2019 Pawel Bylica. 3 | # Licensed under the Apache License, Version 2.0. 4 | 5 | # Cable Build Info, version 1.0.0 6 | # 7 | # This CMake module collects build information and provides it in different 8 | # forms: static librar, JSON file, shell scripts. 9 | # 10 | # CHANGELOG 11 | # 12 | # 1.0.0 - 2022-02-12 13 | 14 | include_guard(GLOBAL) 15 | 16 | include(GNUInstallDirs) 17 | 18 | # TODO: From CMake 3.17 the CMAKE_CURRENT_FUNCTION_LIST_DIR can be used instead. 19 | set(cable_buildinfo_template_dir ${CMAKE_CURRENT_LIST_DIR}/buildinfo) 20 | 21 | function(cable_add_buildinfo_library) 22 | 23 | cmake_parse_arguments("" "" PROJECT_NAME;EXPORT "" ${ARGN}) 24 | 25 | if(NOT _PROJECT_NAME) 26 | message(FATAL_ERROR "The PROJECT_NAME argument missing") 27 | endif() 28 | 29 | # Come up with the target and the C function names. 30 | set(name ${_PROJECT_NAME}-buildinfo) 31 | set(FUNCTION_NAME ${_PROJECT_NAME}_get_buildinfo) 32 | 33 | set(output_dir ${CMAKE_CURRENT_BINARY_DIR}/${_PROJECT_NAME}) 34 | set(header_file ${output_dir}/buildinfo.h) 35 | set(source_file ${output_dir}/buildinfo.c) 36 | 37 | if(CMAKE_CONFIGURATION_TYPES) 38 | set(build_type ${CMAKE_CFG_INTDIR}) 39 | else() 40 | set(build_type ${CMAKE_BUILD_TYPE}) 41 | endif() 42 | 43 | # Find git here to allow the user to provide hints. 44 | find_package(Git) 45 | 46 | # Git info target. 47 | # 48 | # This target is named -git and is always built. 49 | # The executed script gitinfo.cmake check git status and updates files 50 | # containing git information if anything has changed. 51 | add_custom_target( 52 | ${name}-git 53 | COMMAND ${CMAKE_COMMAND} 54 | -DGIT=${GIT_EXECUTABLE} 55 | -DSOURCE_DIR=${PROJECT_SOURCE_DIR} 56 | -DOUTPUT_DIR=${output_dir} 57 | -P ${cable_buildinfo_template_dir}/gitinfo.cmake 58 | BYPRODUCTS ${output_dir}/gitinfo.txt 59 | ) 60 | 61 | add_custom_command( 62 | COMMENT "Updating ${name}:" 63 | OUTPUT ${source_file} ${output_dir}/buildinfo.json 64 | COMMAND ${CMAKE_COMMAND} 65 | -DOUTPUT_DIR=${output_dir} 66 | -DPROJECT_NAME=${_PROJECT_NAME} 67 | -DFUNCTION_NAME=${FUNCTION_NAME} 68 | -DPROJECT_VERSION=${PROJECT_VERSION} 69 | -DSYSTEM_NAME=${CMAKE_SYSTEM_NAME} 70 | -DSYSTEM_PROCESSOR=${CMAKE_SYSTEM_PROCESSOR} 71 | -DCOMPILER_ID=${CMAKE_CXX_COMPILER_ID} 72 | -DCOMPILER_VERSION=${CMAKE_CXX_COMPILER_VERSION} 73 | -DBUILD_TYPE=${build_type} 74 | -P ${cable_buildinfo_template_dir}/buildinfo.cmake 75 | DEPENDS 76 | ${cable_buildinfo_template_dir}/buildinfo.cmake 77 | ${cable_buildinfo_template_dir}/buildinfo.c.in 78 | ${cable_buildinfo_template_dir}/buildinfo.json.in 79 | ${cable_buildinfo_template_dir}/version.h.in 80 | ${name}-git 81 | ${output_dir}/gitinfo.txt 82 | ) 83 | 84 | string(TIMESTAMP TIMESTAMP) 85 | configure_file(${cable_buildinfo_template_dir}/buildinfo.h.in ${header_file}) 86 | 87 | # Add buildinfo library under given name. 88 | # Make is static and do not build by default until some other target will actually use it. 89 | add_library(${name} STATIC ${source_file} ${header_file}) 90 | 91 | target_include_directories(${name} PUBLIC $) 92 | set_target_properties( 93 | ${name} PROPERTIES 94 | LIBRARY_OUTPUT_DIRECTORY ${output_dir} 95 | ARCHIVE_OUTPUT_DIRECTORY ${output_dir} 96 | ) 97 | 98 | if(_EXPORT) 99 | install(TARGETS ${name} EXPORT ${_EXPORT} 100 | RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} 101 | LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} 102 | ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} 103 | ) 104 | endif() 105 | 106 | endfunction() 107 | -------------------------------------------------------------------------------- /src/devcore/StateCacheDB.cpp: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | #include 5 | #include 6 | #include 7 | using namespace dev; 8 | 9 | namespace dev 10 | { 11 | 12 | std::unordered_map StateCacheDB::get() const 13 | { 14 | #if DEV_GUARDED_DB 15 | ReadGuard l(x_this); 16 | #endif 17 | std::unordered_map ret; 18 | for (auto const& i: m_main) 19 | if (!m_enforceRefs || i.second.second > 0) 20 | ret.insert(make_pair(i.first, i.second.first)); 21 | return ret; 22 | } 23 | 24 | StateCacheDB& StateCacheDB::operator=(StateCacheDB const& _c) 25 | { 26 | if (this == &_c) 27 | return *this; 28 | #if DEV_GUARDED_DB 29 | ReadGuard l(_c.x_this); 30 | WriteGuard l2(x_this); 31 | #endif 32 | m_main = _c.m_main; 33 | m_aux = _c.m_aux; 34 | return *this; 35 | } 36 | 37 | std::string StateCacheDB::lookup(h256 const& _h) const 38 | { 39 | #if DEV_GUARDED_DB 40 | ReadGuard l(x_this); 41 | #endif 42 | auto it = m_main.find(_h); 43 | if (it != m_main.end()) 44 | { 45 | if (!m_enforceRefs || it->second.second > 0) 46 | return it->second.first; 47 | // else 48 | // cwarn << "Lookup required for value with refcount == 0. This is probably a critical trie issue" << _h; 49 | } 50 | return std::string(); 51 | } 52 | 53 | bool StateCacheDB::exists(h256 const& _h) const 54 | { 55 | #if DEV_GUARDED_DB 56 | ReadGuard l(x_this); 57 | #endif 58 | auto it = m_main.find(_h); 59 | if (it != m_main.end() && (!m_enforceRefs || it->second.second > 0)) 60 | return true; 61 | return false; 62 | } 63 | 64 | void StateCacheDB::insert(h256 const& _h, bytesConstRef _v) 65 | { 66 | #if DEV_GUARDED_DB 67 | WriteGuard l(x_this); 68 | #endif 69 | auto it = m_main.find(_h); 70 | if (it != m_main.end()) 71 | { 72 | it->second.first = _v.toString(); 73 | it->second.second++; 74 | } 75 | else 76 | m_main[_h] = make_pair(_v.toString(), 1); 77 | } 78 | 79 | bool StateCacheDB::kill(h256 const& _h) 80 | { 81 | #if DEV_GUARDED_DB 82 | ReadGuard l(x_this); 83 | #endif 84 | if (m_main.count(_h)) 85 | { 86 | if (m_main[_h].second > 0) 87 | { 88 | m_main[_h].second--; 89 | return true; 90 | } 91 | } 92 | return false; 93 | } 94 | 95 | bytes StateCacheDB::lookupAux(h256 const& _h) const 96 | { 97 | #if DEV_GUARDED_DB 98 | ReadGuard l(x_this); 99 | #endif 100 | auto it = m_aux.find(_h); 101 | if (it != m_aux.end() && (!m_enforceRefs || it->second.second)) 102 | return it->second.first; 103 | return bytes(); 104 | } 105 | 106 | void StateCacheDB::removeAux(h256 const& _h) 107 | { 108 | #if DEV_GUARDED_DB 109 | WriteGuard l(x_this); 110 | #endif 111 | m_aux[_h].second = false; 112 | } 113 | 114 | void StateCacheDB::insertAux(h256 const& _h, bytesConstRef _v) 115 | { 116 | #if DEV_GUARDED_DB 117 | WriteGuard l(x_this); 118 | #endif 119 | m_aux[_h] = make_pair(_v.toBytes(), true); 120 | } 121 | 122 | void StateCacheDB::purge() 123 | { 124 | #if DEV_GUARDED_DB 125 | WriteGuard l(x_this); 126 | #endif 127 | // purge m_main 128 | for (auto it = m_main.begin(); it != m_main.end(); ) 129 | if (it->second.second) 130 | ++it; 131 | else 132 | it = m_main.erase(it); 133 | 134 | // purge m_aux 135 | for (auto it = m_aux.begin(); it != m_aux.end(); ) 136 | if (it->second.second) 137 | ++it; 138 | else 139 | it = m_aux.erase(it); 140 | } 141 | 142 | h256Hash StateCacheDB::keys() const 143 | { 144 | #if DEV_GUARDED_DB 145 | ReadGuard l(x_this); 146 | #endif 147 | h256Hash ret; 148 | for (auto const& i: m_main) 149 | if (i.second.second) 150 | ret.insert(i.first); 151 | return ret; 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /include/web3cpp/DB.h: -------------------------------------------------------------------------------- 1 | #ifndef DATABASE_H 2 | #define DATABASE_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | using json = nlohmann::ordered_json; 12 | 13 | /** 14 | * Abstraction of a single [LevelDB](https://github.com/google/leveldb) database. 15 | */ 16 | 17 | class Database { 18 | private: 19 | std::string name; ///< Name for the database. 20 | boost::filesystem::path path; ///< Full path for the database (includes name). 21 | leveldb::DB* db = nullptr; ///< Pointer to the actual LevelDB database object. 22 | leveldb::Options dbOpts; ///< Struct with options for the database. 23 | leveldb::Status dbStatus; ///< Struct with the status of the last database operation. 24 | std::string tmpValue; ///< Buffer for a temporary value. 25 | std::mutex mutable dbMutex; ///< Mutex for managing read/write access to the database. 26 | 27 | /** 28 | * Opens the proper database object. 29 | * @return `true` on success, `false` on failure. 30 | */ 31 | bool openDB(); 32 | 33 | /** 34 | * Closes the proper database object. 35 | * "Closing" a LevelDB database actually means just deleting the database object. 36 | * @return `true` on success, `false` on failure. 37 | */ 38 | bool closeDB(); 39 | 40 | public: 41 | /// Empty constructor. 42 | Database(){} 43 | 44 | /** 45 | * Default constructor. 46 | * @param _name The database's name. 47 | * @param rootPath The parent folder of the database. 48 | */ 49 | Database(const std::string& _name, const boost::filesystem::path& rootPath) 50 | : name(_name), path(rootPath.string() + "/" + name) { 51 | this->dbOpts.create_if_missing = true; 52 | openDB(); 53 | } 54 | 55 | /// Copy constructor. 56 | Database(const Database& other) noexcept : 57 | name(other.name), path(other.path), db(other.db), 58 | dbOpts(other.dbOpts), dbStatus(other.dbStatus), tmpValue(other.tmpValue) 59 | {} 60 | 61 | /// Destructor. 62 | ~Database() { closeDB(); } 63 | 64 | /** 65 | * Check if a key exists in the database. 66 | * @param &key The key to search for. 67 | * @return `true` if the key exists, `false` otherwise. 68 | */ 69 | bool keyExists(std::string const &key) const; 70 | 71 | /** 72 | * Get the value of a key from the database. 73 | * @param &key The key to get the value from. 74 | * @return The value linked to the given key. 75 | */ 76 | std::string getKeyValue(std::string const &key); 77 | 78 | /** 79 | * Insert a key/value pair into the database. 80 | * @param &key The key to insert. 81 | * @param &value The value to insert under the given key. 82 | * @return `true` if insertion was successful, `false` otherwise. 83 | */ 84 | bool putKeyValue(std::string const &key, std::string const &value); 85 | 86 | /** 87 | * Delete a key/value pair from the database. 88 | * @param &key The key to delete. 89 | * @return `true` if deletion was successful or if the key didn't exist 90 | * anyway prior to requesting deletion, `false` otherwise. 91 | */ 92 | bool deleteKeyValue(std::string const &key); 93 | 94 | /** 95 | * Get all the individual keys stored in the database. 96 | * @return A vector with all the key strings. 97 | */ 98 | std::vector getAllKeys() const; 99 | 100 | /** 101 | * Get all the individual values stored in the database. 102 | * @return A vector with all the value strings. 103 | */ 104 | std::vector getAllValues() const; 105 | 106 | /** 107 | * Get all the key/value pairs stored in the database. 108 | * @return A list with all the key/value strings. 109 | */ 110 | std::map getAllPairs() const; 111 | 112 | /// Clear all entries stored in the database. 113 | void dropDatabase(); 114 | }; 115 | 116 | #endif // DATABASE_H 117 | -------------------------------------------------------------------------------- /src/DB.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool Database::openDB() { 4 | this->dbMutex.lock(); 5 | if (!boost::filesystem::exists(this->path)) { 6 | boost::filesystem::create_directories(this->path); 7 | } 8 | this->dbStatus = leveldb::DB::Open(this->dbOpts, this->path.string(), &this->db); 9 | if (!this->dbStatus.ok()) { 10 | this->dbMutex.unlock(); 11 | std::cout << "Error opening " << this->name << " database!" 12 | << this->dbStatus.ToString() << std::endl; 13 | return false; 14 | } 15 | this->dbMutex.unlock(); 16 | return true; 17 | } 18 | 19 | bool Database::closeDB() { 20 | this->dbMutex.lock(); 21 | if (this->db == nullptr) { 22 | return true; 23 | } 24 | delete this->db; 25 | this->db = nullptr; 26 | this->dbMutex.unlock(); 27 | return true; 28 | } 29 | 30 | bool Database::keyExists(std::string const &key) const { 31 | this->dbMutex.lock(); 32 | leveldb::Iterator* it = this->db->NewIterator(leveldb::ReadOptions()); 33 | for (it->SeekToFirst(); it->Valid(); it->Next()) { 34 | if (it->key().ToString() == key) { 35 | delete it; 36 | this->dbMutex.unlock(); 37 | return true; 38 | } 39 | } 40 | delete it; 41 | this->dbMutex.unlock(); 42 | return false; 43 | } 44 | 45 | std::string Database::getKeyValue(std::string const &key) { 46 | this->dbMutex.lock(); 47 | this->dbStatus = this->db->Get(leveldb::ReadOptions(), key, &this->tmpValue); 48 | if (!this->dbStatus.ok()) { 49 | this->dbMutex.unlock(); 50 | return ""; 51 | } 52 | this->dbMutex.unlock(); 53 | return this->tmpValue; 54 | } 55 | 56 | bool Database::putKeyValue(std::string const &key, std::string const &value) { 57 | this->dbMutex.lock(); 58 | this->dbStatus = this->db->Put(leveldb::WriteOptions(), key, value); 59 | if (!this->dbStatus.ok()) { 60 | this->dbMutex.unlock(); 61 | std::cout << "Error putting key " << key << " at database " << this->name 62 | << ": " << this->dbStatus.ToString(); 63 | return false; 64 | } 65 | this->dbMutex.unlock(); 66 | return this->dbStatus.ok(); 67 | } 68 | 69 | bool Database::deleteKeyValue(std::string const &key) { 70 | this->dbMutex.lock(); 71 | this->dbStatus = this->db->Delete(leveldb::WriteOptions(), key); 72 | if(!this->dbStatus.ok()) { 73 | this->dbMutex.unlock(); 74 | std::cout << "Error deleting key " << key << " at database " << this->name 75 | << ": " << this->dbStatus.ToString(); 76 | return false; 77 | } 78 | this->dbMutex.unlock(); 79 | return this->dbStatus.ok(); 80 | } 81 | 82 | std::vector Database::getAllKeys() const { 83 | this->dbMutex.lock(); 84 | std::vector ret; 85 | leveldb::Iterator* it = this->db->NewIterator(leveldb::ReadOptions()); 86 | for (it->SeekToFirst(); it->Valid(); it->Next()) { 87 | ret.push_back(it->key().ToString()); 88 | } 89 | delete it; 90 | this->dbMutex.unlock(); 91 | return ret; 92 | } 93 | 94 | std::vector Database::getAllValues() const { 95 | this->dbMutex.lock(); 96 | std::vector ret; 97 | leveldb::Iterator* it = this->db->NewIterator(leveldb::ReadOptions()); 98 | for (it->SeekToFirst(); it->Valid(); it->Next()) { 99 | ret.push_back(it->value().ToString()); 100 | } 101 | delete it; 102 | this->dbMutex.unlock(); 103 | return ret; 104 | } 105 | 106 | std::map Database::getAllPairs() const { 107 | this->dbMutex.lock(); 108 | std::map ret; 109 | leveldb::Iterator* it = this->db->NewIterator(leveldb::ReadOptions()); 110 | for (it->SeekToFirst(); it->Valid(); it->Next()) { 111 | ret.emplace(it->key().ToString(), it->value().ToString()); 112 | } 113 | delete it; 114 | this->dbMutex.unlock(); 115 | return ret; 116 | } 117 | 118 | void Database::dropDatabase() { 119 | this->dbMutex.lock(); 120 | leveldb::Iterator* it = this->db->NewIterator(leveldb::ReadOptions()); 121 | for (it->SeekToFirst(); it->Valid(); it->Next()) { 122 | this->db->Delete(leveldb::WriteOptions(), it->key().ToString()); 123 | } 124 | this->dbMutex.unlock(); 125 | delete it; 126 | } 127 | 128 | -------------------------------------------------------------------------------- /include/web3cpp/ethcore/Exceptions.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | 6 | #pragma once 7 | 8 | #include 9 | 10 | namespace dev 11 | { 12 | namespace eth 13 | { 14 | 15 | // information to add to exceptions 16 | using errinfo_name = boost::error_info; 17 | using errinfo_field = boost::error_info; 18 | using errinfo_data = boost::error_info; 19 | using errinfo_nonce = boost::error_info; 20 | using errinfo_difficulty = boost::error_info; 21 | using errinfo_target = boost::error_info; 22 | using errinfo_seedHash = boost::error_info; 23 | using errinfo_mixHash = boost::error_info; 24 | using errinfo_ethashResult = boost::error_info>; 25 | using BadFieldError = boost::tuple; 26 | 27 | DEV_SIMPLE_EXCEPTION(OutOfGasBase); 28 | DEV_SIMPLE_EXCEPTION(OutOfGasIntrinsic); 29 | DEV_SIMPLE_EXCEPTION(NotEnoughAvailableSpace); 30 | DEV_SIMPLE_EXCEPTION(NotEnoughCash); 31 | DEV_SIMPLE_EXCEPTION(GasPriceTooLow); 32 | DEV_SIMPLE_EXCEPTION(BlockGasLimitReached); 33 | DEV_SIMPLE_EXCEPTION(FeeTooSmall); 34 | DEV_SIMPLE_EXCEPTION(TooMuchGasUsed); 35 | DEV_SIMPLE_EXCEPTION(ExtraDataTooBig); 36 | DEV_SIMPLE_EXCEPTION(ExtraDataIncorrect); 37 | DEV_SIMPLE_EXCEPTION(TransactionIsUnsigned); 38 | DEV_SIMPLE_EXCEPTION(InvalidSignature); 39 | DEV_SIMPLE_EXCEPTION(InvalidTransactionFormat); 40 | DEV_SIMPLE_EXCEPTION(InvalidBlockFormat); 41 | DEV_SIMPLE_EXCEPTION(InvalidUnclesHash); 42 | DEV_SIMPLE_EXCEPTION(TooManyUncles); 43 | DEV_SIMPLE_EXCEPTION(UncleTooOld); 44 | DEV_SIMPLE_EXCEPTION(UncleIsBrother); 45 | DEV_SIMPLE_EXCEPTION(UncleInChain); 46 | DEV_SIMPLE_EXCEPTION(UncleParentNotInChain); 47 | DEV_SIMPLE_EXCEPTION(InvalidStateRoot); 48 | DEV_SIMPLE_EXCEPTION(InvalidGasUsed); 49 | DEV_SIMPLE_EXCEPTION(InvalidTransactionsRoot); 50 | DEV_SIMPLE_EXCEPTION(InvalidDifficulty); 51 | DEV_SIMPLE_EXCEPTION(InvalidGasLimit); 52 | DEV_SIMPLE_EXCEPTION(InvalidReceiptsStateRoot); 53 | DEV_SIMPLE_EXCEPTION(InvalidTimestamp); 54 | DEV_SIMPLE_EXCEPTION(InvalidLogBloom); 55 | DEV_SIMPLE_EXCEPTION(InvalidNonce); 56 | DEV_SIMPLE_EXCEPTION(InvalidBlockHeaderItemCount); 57 | DEV_SIMPLE_EXCEPTION(InvalidBlockNonce); 58 | DEV_SIMPLE_EXCEPTION(InvalidParentHash); 59 | DEV_SIMPLE_EXCEPTION(InvalidUncleParentHash); 60 | DEV_SIMPLE_EXCEPTION(InvalidNumber); 61 | DEV_SIMPLE_EXCEPTION(InvalidZeroSignatureTransaction); 62 | DEV_SIMPLE_EXCEPTION(InvalidTransactionReceiptFormat); 63 | DEV_SIMPLE_EXCEPTION(TransactionReceiptVersionError); 64 | DEV_SIMPLE_EXCEPTION(PendingTransactionAlreadyExists); 65 | DEV_SIMPLE_EXCEPTION(TransactionAlreadyInChain); 66 | DEV_SIMPLE_EXCEPTION(BlockNotFound); 67 | DEV_SIMPLE_EXCEPTION(UnknownParent); 68 | DEV_SIMPLE_EXCEPTION(DisjointChain); 69 | DEV_SIMPLE_EXCEPTION(AddressAlreadyUsed); 70 | DEV_SIMPLE_EXCEPTION(ZeroSignatureTransaction); 71 | DEV_SIMPLE_EXCEPTION(UnknownTransactionValidationError); 72 | DEV_SIMPLE_EXCEPTION(UnknownError); 73 | 74 | DEV_SIMPLE_EXCEPTION(InvalidDatabaseKind); 75 | DEV_SIMPLE_EXCEPTION(DatabaseAlreadyOpen); 76 | DEV_SIMPLE_EXCEPTION(DatabaseCorruption); 77 | DEV_SIMPLE_EXCEPTION(DatabaseExists); 78 | DEV_SIMPLE_EXCEPTION(DatabaseRebuildFailed); 79 | 80 | DEV_SIMPLE_EXCEPTION(DAGCreationFailure); 81 | DEV_SIMPLE_EXCEPTION(DAGComputeFailure); 82 | 83 | DEV_SIMPLE_EXCEPTION(UnsupportedSnapshotManifestVersion); 84 | DEV_SIMPLE_EXCEPTION(InvalidSnapshotManifest); 85 | DEV_SIMPLE_EXCEPTION(StateTrieReconstructionFailed); 86 | DEV_SIMPLE_EXCEPTION(InvalidStateChunkData); 87 | DEV_SIMPLE_EXCEPTION(InvalidBlockChunkData); 88 | DEV_SIMPLE_EXCEPTION(AccountAlreadyImported); 89 | DEV_SIMPLE_EXCEPTION(InvalidWarpStatusPacket); 90 | DEV_SIMPLE_EXCEPTION(FailedToDownloadManifest); 91 | DEV_SIMPLE_EXCEPTION(FailedToDownloadDaoForkBlockHeader); 92 | 93 | DEV_SIMPLE_EXCEPTION(AccountLocked); 94 | DEV_SIMPLE_EXCEPTION(TransactionRefused); 95 | DEV_SIMPLE_EXCEPTION(UnknownAccount); 96 | 97 | DEV_SIMPLE_EXCEPTION(PeerDisconnected); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /include/web3cpp/Account.h: -------------------------------------------------------------------------------- 1 | #ifndef ACCOUNTS_H 2 | #define ACCOUNTS_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | using json = nlohmann::ordered_json; 18 | 19 | /** 20 | * Abstraction for a single account. 21 | * Contains details such as address, nonce, transaction history, etc.. 22 | */ 23 | 24 | class Account { 25 | private: 26 | std::string _address; ///< Address for the account. 27 | std::string _name; ///< Custom name/label for the account. 28 | std::string _derivationPath; ///< Complete derivation path for the account (e.g. "m/44'/60'/0'/0"). 29 | uint64_t _nonce; ///< Current nonce for the account. 30 | bool _isLedger; ///< Indicates the account is imported from a Ledger device. 31 | const std::unique_ptr& provider; ///< Pointer to Web3::defaultProvider. 32 | mutable std::mutex accountLock; ///< Mutex for managing read/write access to the account object. 33 | Database transactionDB; ///< Database of transactions made with the account. 34 | 35 | public: 36 | 37 | /** 38 | * Default constructor. 39 | * @param walletPath The path for the wallet from which the account comes from. 40 | * @param name Custom name/label for the account. 41 | * @param __address Address for the account. 42 | * @param __derivationPath Full derivation path for the account (e.g. `m/44'/60'/0'/0`). 43 | * @param __isLedger Flag to set whether the account comes from a Ledger device or not. 44 | * @param *_provider Pointer to the provider used by the account. 45 | */ 46 | Account( 47 | const boost::filesystem::path& walletPath, const std::string& __address, const std::string& __name, 48 | const std::string& __derivationPath, bool __isLedger, const std::unique_ptr& _provider 49 | ); 50 | 51 | /// Copy constructor. 52 | Account(const Account& other) noexcept : 53 | _address(other._address), 54 | _name(other._name), 55 | _derivationPath(other._derivationPath), 56 | _isLedger(other._isLedger), 57 | _nonce(other._nonce), 58 | provider(other.provider), 59 | transactionDB(other.transactionDB) 60 | {} 61 | 62 | /// Copy constructor from pointer. 63 | Account(const std::unique_ptr& other) noexcept : 64 | _address(other->_address), 65 | _name(other->_name), 66 | _derivationPath(other->_derivationPath), 67 | _isLedger(other->_isLedger), 68 | _nonce(other->_nonce), 69 | provider(other->provider), 70 | transactionDB(other->transactionDB) 71 | {} 72 | 73 | const std::string& address() const { return _address; } ///< Getter for the address. 74 | const std::string& name() const { return _name; } ///< Getter for the custom name/label. 75 | const std::string& derivationPath() const { return _derivationPath; } ///< Getter for the derivation path. 76 | const uint64_t& nonce() const { return _nonce; } ///< Getter for the nonce. 77 | bool isLedger() const { return _isLedger; } ///< Getter for the Ledger flag. 78 | 79 | /** 80 | * Request the account's balance from the network. 81 | * @return The balance in Wei as a BigNumber, or 0 if the request fails. 82 | */ 83 | std::future balance() const; 84 | 85 | /** 86 | * Save a transaction to the account's local history database. 87 | * @param signedTx The raw transaction signature that will be decoded and stored. 88 | * @return `true` on success, `false` on failure. 89 | */ 90 | bool saveTxToHistory(std::string signedTx); 91 | 92 | /** 93 | * Get all saved transactions from this account's local history database. 94 | * @return The account's transaction history as a JSON object. 95 | */ 96 | json getTxHistory() const; 97 | }; 98 | 99 | #endif // ACCOUNTS_H 100 | -------------------------------------------------------------------------------- /src/devcore/Common.cpp: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #include 6 | #include 7 | 8 | #if defined(_WIN32) 9 | #include 10 | #endif 11 | 12 | //#include 13 | 14 | namespace dev 15 | { 16 | //char const* Version = web3cpp_get_buildinfo()->project_version; 17 | bytes const NullBytes; 18 | std::string const EmptyString; 19 | 20 | void InvariantChecker::checkInvariants(HasInvariants const* _this, char const* _fn, char const* _file, int _line, bool _pre) 21 | { 22 | if (!_this->invariants()) 23 | { 24 | // cwarn << (_pre ? "Pre" : "Post") << "invariant failed in" << _fn << "at" << _file << ":" << _line; 25 | BOOST_THROW_EXCEPTION(FailedInvariant() << errinfo_comment(std::string("_fn: ") + _fn + " _file: " + _file + " _line: " + std::to_string(_line))); 26 | } 27 | } 28 | 29 | TimerHelper::~TimerHelper() 30 | { 31 | auto e = std::chrono::high_resolution_clock::now() - m_t; 32 | // if (!m_ms || e > chrono::milliseconds(m_ms)) 33 | // clog(VerbosityDebug, "timer") 34 | // << m_id << " " << chrono::duration_cast(e).count() << " ms"; 35 | } 36 | 37 | int64_t utcTime() 38 | { 39 | // TODO: Fix if possible to not use time(0) and merge only after testing in all platforms 40 | // time_t t = time(0); 41 | // return mktime(gmtime(&t)); 42 | return time(0); 43 | } 44 | 45 | std::string inUnits(bigint const& _b, strings const& _units) 46 | { 47 | std::ostringstream ret; 48 | u256 b; 49 | if (_b < 0) 50 | { 51 | ret << "-"; 52 | b = (u256)-_b; 53 | } 54 | else 55 | b = (u256)_b; 56 | 57 | u256 biggest = 1; 58 | for (unsigned i = _units.size() - 1; !!i; --i) 59 | biggest *= 1000; 60 | 61 | if (b > biggest * 1000) 62 | { 63 | ret << (b / biggest) << " " << _units.back(); 64 | return ret.str(); 65 | } 66 | ret << std::setprecision(3); 67 | 68 | u256 unit = biggest; 69 | for (auto it = _units.rbegin(); it != _units.rend(); ++it) 70 | { 71 | auto i = *it; 72 | if (i != _units.front() && b >= unit) 73 | { 74 | ret << (double(b / (unit / 1000)) / 1000.0) << " " << i; 75 | return ret.str(); 76 | } 77 | else 78 | unit /= 1000; 79 | } 80 | ret << b << " " << _units.front(); 81 | return ret.str(); 82 | } 83 | 84 | u256 raiseToPow(u256 x, u256 power) 85 | { 86 | u256 result; 87 | u256 i; 88 | result = 1; 89 | for (i=1; i<=power;i++) 90 | { 91 | result = result*x; 92 | } 93 | return(result); 94 | } 95 | 96 | bool is_digits(const std::string &str) 97 | { 98 | return std::all_of(str.begin(), str.end(), ::isdigit); 99 | } 100 | 101 | /* 102 | The equivalent of setlocale(LC_ALL, “C”) is called before any user code is run. 103 | If the user has an invalid environment setting then it is possible for the call 104 | to set locale to fail, so there are only two possible actions, the first is to 105 | throw a runtime exception and cause the program to quit (default behaviour), 106 | or the second is to modify the environment to something sensible (least 107 | surprising behaviour). 108 | 109 | The follow code produces the least surprising behaviour. It will use the user 110 | specified default locale if it is valid, and if not then it will modify the 111 | environment the process is running in to use a sensible default. This also means 112 | that users do not need to install language packs for their OS. 113 | */ 114 | void setDefaultOrCLocale() 115 | { 116 | #if __unix__ 117 | if (!setlocale(LC_ALL, "")) 118 | setenv("LC_ALL", "C", 1); 119 | #endif 120 | 121 | #if defined(_WIN32) 122 | // Change the code page from the default OEM code page (437) so that UTF-8 characters are 123 | // displayed correctly in the console. 124 | SetConsoleOutputCP(CP_UTF8); 125 | #endif 126 | } 127 | 128 | bool ExitHandler::s_shouldExit = false; 129 | 130 | bool isTrue(std::string const& _m) 131 | { 132 | return _m == "on" || _m == "yes" || _m == "true" || _m == "1"; 133 | } 134 | 135 | bool isFalse(std::string const& _m) 136 | { 137 | return _m == "off" || _m == "no" || _m == "false" || _m == "0"; 138 | } 139 | 140 | } // namespace dev 141 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # web3cpp 2 | 3 | Custom implementation of [Web3](https://web3js.readthedocs.io) in C++. 4 | 5 | This is ***NOT*** a 100% parity conversion of the web3js library, but rather a mix of web3js structure with some logic from the now deprecated [aleth](https://github.com/ethereum/aleth) library from Ethereum. 6 | 7 | See [Differences from web3js](#differences-from-web3js) for more details on how this project deviates from web3js. 8 | 9 | ## Compiling 10 | 11 | ### Dependencies 12 | 13 | * **CMake 3.19.0** or higher 14 | * **GCC** with support for **C++17** or higher 15 | * **Boost**, **libhidapi** and **OpenSSL** 16 | * (optional) **Doxygen** for generating the docs 17 | 18 | ### Instructions 19 | 20 | * Clone the project: `git clone https://github.com/avme/web3cpp` 21 | * Go to the project's root folder, create a "build" folder and change to it: `cd web3cpp && mkdir build && cd build` 22 | * Run `cmake ..` then `cmake --build . -- -j$(nproc)` inside the build folder 23 | * If you want documentation, go back to the project's root folder and run `doxygen Doxyfile` from there 24 | * Docs will be generated at a folder named `docs/html` 25 | 26 | ### CMake parameters 27 | 28 | For use with `cmake -D ..`: 29 | 30 | * `BUILD_STATIC` (default **ON**) - compiles the library as static 31 | * `BUILD_TESTS` (default **ON**) - compiles an extra program that runs some tests on the library 32 | 33 | ## Differences from web3js 34 | 35 | Due to architectural differences between JS and C++, most things were significantly changed. It's recommended to generate and read the docs from this project (see [Instructions](#instructions) instead of following other implementations. 36 | 37 | * `web3.utils` becomes `namespace Utils` 38 | * e.g. **web3.utils.sha3("Hello!%")** -> **Utils::sha3("Hello!%")** 39 | * `web3.eth.Contract` becomes `class Contract` 40 | * e.g. **var c = new web3.eth.Contract(...)** -> **Contract c(...)** 41 | * `web3.eth.abi` becomes `namespace Solidity` 42 | * e.g. **web3.eth.abi.encodeParameters(['uint256','string'], ['2345675643', 'Hello!%'])** -> **Solidity::packMulti({{{"t", "uint256"}, {"v", "2345675643"}}, {{"t", "string"}, {"v", "Hello!%"}}}, err)** 43 | * The "network" part of `web3.*.net` is technically replaced by `namespace Net` (which does HTTP requests) and `namespace RPC` (which builds the data that is sent through the requests) 44 | * They're meant to be used together (e.g. **Net::HTTPRequest(provider, Net::RequestTypes::POST, RPC::eth_getBlockNumber().dump())**) 45 | * The "node" part of `web3.*.net` is replaced by `class Provider` 46 | * Parts of `web3.eth.accounts` and `web3.eth.personal` are joined in a custom `Wallet` class 47 | * `web3.eth` becomes `class Eth` and almost all of its member variables were moved to `Provider` and/or `Contract::Options` 48 | * You still access `Provider`, `Wallet` and `Eth` from inside the Web3 class 49 | * e.g. **web3->getProvider()->getChainId()**, **web3->wallet.getAccounts()**, **web3->eth.getGasPrice()** 50 | * JavaScript's `BN.js` object is replaced by a simple unsigned 256-bit integer (aleth's `dev::u256`), which is aliased to `BigNumber` 51 | * JSON objects are handled using [nlohmann::json](https://github.com/nlohmann/json) 52 | 53 | ### Missing modules and functionalities 54 | 55 | Some particular things are not (and probably won't be) implemented as we either don't have a need for them (at least for now) or other parts of the library are already doing their job. 56 | 57 | * [web3.bzz (Swarm Protocol)](https://web3js.readthedocs.io/en/v1.7.4/web3-bzz.html) 58 | * [web3.shh (Whisper Protocol)](https://web3js.readthedocs.io/en/v1.7.4/web3-shh.html) 59 | * [web3.eth.ens (Ethereum Name Service)](https://web3js.readthedocs.io/en/v1.7.4/web3-eth-ens.html) 60 | * [web3.eth.Iban (IBAN/BBAN support)](https://web3js.readthedocs.io/en/v1.7.4/web3-eth-iban.html) 61 | * [web3.eth.subscribe](https://web3js.readthedocs.io/en/v1.7.4/web3-eth-subscribe.html) 62 | * This one will probably be implemented inside `Contract` but it's not set in stone 63 | * Bloom filters on [web3.utils](https://web3js.readthedocs.io/en/v1.7.4/web3-utils.html#bloom-filters) 64 | * [BatchRequest](https://web3js.readthedocs.io/en/v1.7.4/web3.html#batchrequest) 65 | * [PromiEvent](https://web3js.readthedocs.io/en/v1.7.4/callbacks-promises-events.html) 66 | * [Access lists](https://web3js.readthedocs.io/en/v1.7.4/web3-eth.html#createaccesslist) 67 | * [Extending modules](https://web3js.readthedocs.io/en/v1.7.4/web3.html#extend) 68 | * Other individual functions across some modules ("if it's not in the docs, we're not missing it") 69 | 70 | -------------------------------------------------------------------------------- /cmake/certifyPatch.patch: -------------------------------------------------------------------------------- 1 | diff --git a/CMakeLists.txt b/CMakeLists.txt 2 | index 7cceb2c..630f262 100644 3 | --- a/CMakeLists.txt 4 | +++ b/CMakeLists.txt 5 | @@ -59,13 +59,13 @@ write_basic_package_version_file( 6 | COMPATIBILITY AnyNewerVersion) 7 | 8 | install(FILES 9 | - "netutilsConfig.cmake" 10 | + "certifyConfig.cmake" 11 | "${CMAKE_BINARY_DIR}/certifyConfigVersion.cmake" 12 | DESTINATION lib/cmake/certify) 13 | 14 | install(DIRECTORY ${CMAKE_SOURCE_DIR}/include/ 15 | DESTINATION include 16 | - FILES_MATCHING PATTERN "*.hpp") 17 | + FILES_MATCHING PATTERN "*.hpp" PATTERN "*.ipp") 18 | 19 | install(TARGETS core 20 | EXPORT certifyTargets 21 | diff --git a/certifyConfig.cmake b/certifyConfig.cmake 22 | index 272dd90..87313e8 100644 23 | --- a/certifyConfig.cmake 24 | +++ b/certifyConfig.cmake 25 | @@ -1,6 +1,7 @@ 26 | include(CMakeFindDependencyMacro) 27 | 28 | -find_dependency(Boost COMPONENTS system) 29 | +find_dependency(Boost COMPONENTS system filesystem date_time) 30 | +find_dependency(OpenSSL) 31 | find_dependency(Threads) 32 | 33 | -include("${CMAKE_CURRENT_LIST_DIR}/certify-Targets.cmake") 34 | +include("${CMAKE_CURRENT_LIST_DIR}/certifyTargets.cmake") 35 | diff --git a/include/boost/certify/crlset_parser.hpp b/include/boost/certify/crlset_parser.hpp 36 | index 7174944..29ab461 100644 37 | --- a/include/boost/certify/crlset_parser.hpp 38 | +++ b/include/boost/certify/crlset_parser.hpp 39 | @@ -4,6 +4,7 @@ 40 | #include 41 | #include 42 | #include 43 | +#include 44 | 45 | namespace boost 46 | { 47 | diff --git a/include/boost/certify/detail/keystore_windows.ipp b/include/boost/certify/detail/keystore_windows.ipp 48 | index efcc697..625ef00 100644 49 | --- a/include/boost/certify/detail/keystore_windows.ipp 50 | +++ b/include/boost/certify/detail/keystore_windows.ipp 51 | @@ -6,6 +6,7 @@ 52 | 53 | #include 54 | #include 55 | +#include 56 | 57 | namespace boost 58 | { 59 | diff --git a/include/boost/certify/detail/spki_blacklist.hpp b/include/boost/certify/detail/spki_blacklist.hpp 60 | index 7833d80..2f456e9 100644 61 | --- a/include/boost/certify/detail/spki_blacklist.hpp 62 | +++ b/include/boost/certify/detail/spki_blacklist.hpp 63 | @@ -2,6 +2,7 @@ 64 | #define BOOST_CERTIFY_DETAIL_SPKI_BLACKLIST_HPP 65 | 66 | #include 67 | +#include 68 | 69 | namespace boost 70 | { 71 | diff --git a/include/boost/certify/detail/spki_digest.hpp b/include/boost/certify/detail/spki_digest.hpp 72 | index d9e4ba9..5f937c2 100644 73 | --- a/include/boost/certify/detail/spki_digest.hpp 74 | +++ b/include/boost/certify/detail/spki_digest.hpp 75 | @@ -5,6 +5,7 @@ 76 | #include 77 | #include 78 | #include 79 | +#include 80 | 81 | namespace boost 82 | { 83 | diff --git a/include/boost/certify/impl/crlset_parser.ipp b/include/boost/certify/impl/crlset_parser.ipp 84 | index d41fb7f..853894e 100644 85 | --- a/include/boost/certify/impl/crlset_parser.ipp 86 | +++ b/include/boost/certify/impl/crlset_parser.ipp 87 | @@ -2,6 +2,7 @@ 88 | #define BOOST_CERTIFY_IMPL_CRLSET_PARSER_IPP 89 | 90 | #include 91 | +#include 92 | 93 | namespace boost 94 | { 95 | diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt 96 | index c1cda26..03be79c 100644 97 | --- a/tests/CMakeLists.txt 98 | +++ b/tests/CMakeLists.txt 99 | @@ -11,5 +11,9 @@ function (certify_verify_add_test test_file) 100 | COMMAND ${target_name}) 101 | endfunction(certify_verify_add_test) 102 | 103 | +certify_verify_add_test(extensions.cpp) 104 | certify_verify_add_test(https_verification_success.cpp) 105 | certify_verify_add_test(https_verification_fail.cpp) 106 | +certify_verify_add_test(crl_set_parser.cpp) 107 | +certify_verify_add_test(detail_spki_digest.cpp) 108 | +certify_verify_add_test(status_cache.cpp) 109 | \ No newline at end of file 110 | diff --git a/tests/crl_set_parser.cpp b/tests/crl_set_parser.cpp 111 | index 4e5b221..8f29a27 100644 112 | --- a/tests/crl_set_parser.cpp 113 | +++ b/tests/crl_set_parser.cpp 114 | @@ -5,6 +5,7 @@ 115 | #include 116 | #include 117 | #include 118 | +#include 119 | 120 | const std::uint8_t array[46] = { 121 | 0x02, 0x00, 0x7b, 0x7d, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 122 | -------------------------------------------------------------------------------- /include/web3cpp/devcore/TrieCommon.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #pragma once 6 | 7 | #include "Common.h" 8 | #include "RLP.h" 9 | 10 | namespace dev 11 | { 12 | extern const h256 EmptyTrie; 13 | 14 | inline byte nibble(bytesConstRef _data, unsigned _i) 15 | { 16 | return (_i & 1) ? (_data[_i / 2] & 15) : (_data[_i / 2] >> 4); 17 | } 18 | 19 | /// Interprets @a _first and @a _second as vectors of nibbles and returns the length of the longest common 20 | /// prefix of _first[_beginFirst..._endFirst] and _second[_beginSecond..._endSecond]. 21 | inline unsigned sharedNibbles(bytesConstRef _first, unsigned _beginFirst, unsigned _endFirst, bytesConstRef _second, unsigned _beginSecond, unsigned _endSecond) 22 | { 23 | unsigned ret = 0; 24 | while (_beginFirst < _endFirst && _beginSecond < _endSecond && nibble(_first, _beginFirst) == nibble(_second, _beginSecond)) 25 | { 26 | ++_beginFirst; 27 | ++_beginSecond; 28 | ++ret; 29 | } 30 | return ret; 31 | } 32 | 33 | /** 34 | * Nibble-based view on a bytesConstRef. 35 | */ 36 | struct NibbleSlice 37 | { 38 | bytesConstRef data; 39 | unsigned offset; 40 | 41 | NibbleSlice(bytesConstRef _data = bytesConstRef(), unsigned _offset = 0): data(_data), offset(_offset) {} 42 | byte operator[](unsigned _index) const { return nibble(data, offset + _index); } 43 | unsigned size() const { return data.size() * 2 - offset; } 44 | bool empty() const { return !size(); } 45 | NibbleSlice mid(unsigned _index) const { return NibbleSlice(data, offset + _index); } 46 | void clear() { data.reset(); offset = 0; } 47 | 48 | /// @returns true iff _k is a prefix of this. 49 | bool contains(NibbleSlice _k) const { return shared(_k) == _k.size(); } 50 | /// @returns the number of shared nibbles at the beginning of this and _k. 51 | unsigned shared(NibbleSlice _k) const { return sharedNibbles(data, offset, offset + size(), _k.data, _k.offset, _k.offset + _k.size()); } 52 | /** 53 | * @brief Determine if we, a full key, are situated prior to a particular key-prefix. 54 | * @param _k The prefix. 55 | * @return true if we are strictly prior to the prefix. 56 | */ 57 | bool isEarlierThan(NibbleSlice _k) const 58 | { 59 | unsigned i = 0; 60 | for (; i < _k.size() && i < size(); ++i) 61 | if (operator[](i) < _k[i]) // Byte is lower - we're earlier.. 62 | return true; 63 | else if (operator[](i) > _k[i]) // Byte is higher - we're not earlier. 64 | return false; 65 | if (i >= _k.size()) // Ran past the end of the prefix - we're == for the entire prefix - we're not earlier. 66 | return false; 67 | return true; // Ran out before the prefix had finished - we're earlier. 68 | } 69 | bool operator==(NibbleSlice _k) const { return _k.size() == size() && shared(_k) == _k.size(); } 70 | bool operator!=(NibbleSlice _s) const { return !operator==(_s); } 71 | }; 72 | 73 | inline std::ostream& operator<<(std::ostream& _out, NibbleSlice const& _m) 74 | { 75 | for (unsigned i = 0; i < _m.size(); ++i) 76 | _out << std::hex << (int)_m[i] << std::dec; 77 | return _out; 78 | } 79 | 80 | inline bool isLeaf(RLP const& _twoItem) 81 | { 82 | assert(_twoItem.isList() && _twoItem.itemCount() == 2); 83 | auto pl = _twoItem[0].payload(); 84 | return (pl[0] & 0x20) != 0; 85 | } 86 | 87 | inline NibbleSlice keyOf(bytesConstRef _hpe) 88 | { 89 | if (!_hpe.size()) 90 | return NibbleSlice(_hpe, 0); 91 | if (_hpe[0] & 0x10) 92 | return NibbleSlice(_hpe, 1); 93 | else 94 | return NibbleSlice(_hpe, 2); 95 | } 96 | 97 | inline NibbleSlice keyOf(RLP const& _twoItem) 98 | { 99 | return keyOf(_twoItem[0].payload()); 100 | } 101 | 102 | byte uniqueInUse(RLP const& _orig, byte except); 103 | std::string hexPrefixEncode(bytes const& _hexVector, bool _leaf = false, int _begin = 0, int _end = -1); 104 | std::string hexPrefixEncode(bytesConstRef _data, bool _leaf, int _beginNibble, int _endNibble, unsigned _offset); 105 | std::string hexPrefixEncode(bytesConstRef _d1, unsigned _o1, bytesConstRef _d2, unsigned _o2, bool _leaf); 106 | 107 | inline std::string hexPrefixEncode(NibbleSlice _s, bool _leaf, int _begin = 0, int _end = -1) 108 | { 109 | return hexPrefixEncode(_s.data, _leaf, _begin, _end, _s.offset); 110 | } 111 | 112 | inline std::string hexPrefixEncode(NibbleSlice _s1, NibbleSlice _s2, bool _leaf) 113 | { 114 | return hexPrefixEncode(_s1.data, _s1.offset, _s2.data, _s2.offset, _leaf); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /cmake/FindCryptoPP.cmake: -------------------------------------------------------------------------------- 1 | # Module for locating the Crypto++ encryption library. 2 | # 3 | # Customizable variables: 4 | # CRYPTOPP_ROOT_DIR 5 | # This variable points to the CryptoPP root directory. On Windows the 6 | # library location typically will have to be provided explicitly using the 7 | # -D command-line option. The directory should include the include/cryptopp, 8 | # lib and/or bin sub-directories. 9 | # 10 | # Read-only variables: 11 | # CRYPTOPP_FOUND 12 | # Indicates whether the library has been found. 13 | # 14 | # CRYPTOPP_INCLUDE_DIRS 15 | # Points to the CryptoPP include directory. 16 | # 17 | # CRYPTOPP_LIBRARIES 18 | # Points to the CryptoPP libraries that should be passed to 19 | # target_link_libararies. 20 | # 21 | # 22 | # Copyright (c) 2012 Sergiu Dotenco 23 | # 24 | # Permission is hereby granted, free of charge, to any person obtaining a copy 25 | # of this software and associated documentation files (the "Software"), to deal 26 | # in the Software without restriction, including without limitation the rights 27 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 28 | # copies of the Software, and to permit persons to whom the Software is 29 | # furnished to do so, subject to the following conditions: 30 | # 31 | # The above copyright notice and this permission notice shall be included in all 32 | # copies or substantial portions of the Software. 33 | # 34 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 35 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 36 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 37 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 38 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 39 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 40 | # SOFTWARE. 41 | 42 | INCLUDE (FindPackageHandleStandardArgs) 43 | 44 | FIND_PATH (CRYPTOPP_ROOT_DIR 45 | NAMES cryptopp/cryptlib.h include/cryptopp/cryptlib.h 46 | PATHS ENV CRYPTOPPROOT 47 | DOC "CryptoPP root directory") 48 | 49 | # Re-use the previous path: 50 | FIND_PATH (CRYPTOPP_INCLUDE_DIR 51 | NAMES cryptopp/cryptlib.h 52 | HINTS ${CRYPTOPP_ROOT_DIR} 53 | PATH_SUFFIXES include 54 | DOC "CryptoPP include directory") 55 | 56 | FIND_LIBRARY (CRYPTOPP_LIBRARY_DEBUG 57 | NAMES libcryptlibd.a libcryptoppd.a 58 | #NAMES libcryptoppd.a 59 | HINTS ${CRYPTOPP_ROOT_DIR} 60 | PATH_SUFFIXES lib 61 | DOC "CryptoPP debug library") 62 | 63 | FIND_LIBRARY (CRYPTOPP_LIBRARY_RELEASE 64 | NAMES libcryptlib.a libcryptopp.a 65 | #NAMES libcryptopp.a 66 | HINTS ${CRYPTOPP_ROOT_DIR} 67 | PATH_SUFFIXES lib 68 | DOC "CryptoPP release library") 69 | 70 | IF (CRYPTOPP_LIBRARY_DEBUG AND CRYPTOPP_LIBRARY_RELEASE) 71 | SET (CRYPTOPP_LIBRARY 72 | optimized ${CRYPTOPP_LIBRARY_RELEASE} 73 | debug ${CRYPTOPP_LIBRARY_DEBUG} CACHE STRING "CryptoPP library") 74 | ELSEIF (CRYPTOPP_LIBRARY_RELEASE) 75 | SET (CRYPTOPP_LIBRARY ${CRYPTOPP_LIBRARY_RELEASE} CACHE STRING 76 | "CryptoPP library") 77 | ENDIF (CRYPTOPP_LIBRARY_DEBUG AND CRYPTOPP_LIBRARY_RELEASE) 78 | 79 | IF (CRYPTOPP_INCLUDE_DIR) 80 | SET (_CRYPTOPP_VERSION_HEADER ${CRYPTOPP_INCLUDE_DIR}/cryptopp/config_ver.h) 81 | 82 | IF (EXISTS ${_CRYPTOPP_VERSION_HEADER}) 83 | FILE (STRINGS ${_CRYPTOPP_VERSION_HEADER} _CRYPTOPP_VERSION_TMP REGEX 84 | "^#define CRYPTOPP_VERSION[ \t]+[0-9]+$") 85 | 86 | STRING (REGEX REPLACE 87 | "^#define CRYPTOPP_VERSION[ \t]+([0-9]+)" "\\1" _CRYPTOPP_VERSION_TMP 88 | "${_CRYPTOPP_VERSION_TMP}") 89 | 90 | STRING (REGEX REPLACE "([0-9]+)[0-9][0-9]" "\\1" CRYPTOPP_VERSION_MAJOR 91 | "${_CRYPTOPP_VERSION_TMP}") 92 | STRING (REGEX REPLACE "[0-9]([0-9])[0-9]" "\\1" CRYPTOPP_VERSION_MINOR 93 | "${_CRYPTOPP_VERSION_TMP}") 94 | STRING (REGEX REPLACE "[0-9][0-9]([0-9])" "\\1" CRYPTOPP_VERSION_PATCH 95 | "${_CRYPTOPP_VERSION_TMP}") 96 | 97 | SET (CRYPTOPP_VERSION_COUNT 3) 98 | SET (CRYPTOPP_VERSION 99 | ${CRYPTOPP_VERSION_MAJOR}.${CRYPTOPP_VERSION_MINOR}.${CRYPTOPP_VERSION_PATCH}) 100 | ENDIF (EXISTS ${_CRYPTOPP_VERSION_HEADER}) 101 | ENDIF (CRYPTOPP_INCLUDE_DIR) 102 | 103 | SET (CRYPTOPP_INCLUDE_DIRS ${CRYPTOPP_INCLUDE_DIR}) 104 | SET (CRYPTOPP_LIBRARIES ${CRYPTOPP_LIBRARY}) 105 | 106 | MARK_AS_ADVANCED (CRYPTOPP_INCLUDE_DIR CRYPTOPP_LIBRARY CRYPTOPP_LIBRARY_DEBUG 107 | CRYPTOPP_LIBRARY_RELEASE) 108 | 109 | FIND_PACKAGE_HANDLE_STANDARD_ARGS (CryptoPP REQUIRED_VARS CRYPTOPP_LIBRARY 110 | CRYPTOPP_INCLUDE_DIR CRYPTOPP_ROOT_DIR VERSION_VAR CRYPTOPP_VERSION) -------------------------------------------------------------------------------- /cmake/bip3x_strings_fix.patch: -------------------------------------------------------------------------------- 1 | diff --git a/src/minter/Bip39Mnemonic.cpp b/src/minter/Bip39Mnemonic.cpp 2 | index e181631..76ca60b 100644 3 | --- a/src/minter/Bip39Mnemonic.cpp 4 | +++ b/src/minter/Bip39Mnemonic.cpp 5 | @@ -13,6 +13,48 @@ 6 | 7 | #include 8 | 9 | +std::string glue_1(const std::string& glue, const std::vector& strings) { 10 | + std::string out; 11 | + 12 | + size_t size = strings.size(); 13 | + size_t i = 0; 14 | + for (auto& s : strings) { 15 | + if (i == 0 || i == size) { 16 | + out.append(s); 17 | + } else { 18 | + out.append(glue).append(s); 19 | + } 20 | + 21 | + i++; 22 | + } 23 | + 24 | + return out; 25 | +} 26 | + 27 | +std::vector split_1(const std::string& source, const std::string& delimiter) { 28 | + if (delimiter.empty()) { 29 | + return std::vector(0); 30 | + } 31 | + 32 | + std::string src = source; 33 | + 34 | + std::vector result; 35 | + size_t current = 0; 36 | + while (current != src.npos) { 37 | + current = src.find(delimiter); 38 | + if (current != src.npos && src.substr(current, delimiter.length()) == delimiter) { 39 | + result.push_back(src.substr(0, current)); 40 | + src = src.substr(current + (delimiter.length()), src.npos); 41 | + } 42 | + } 43 | + if (src.length() > 0) { 44 | + result.push_back(src); 45 | + } 46 | + 47 | + return result; 48 | +} 49 | + 50 | + 51 | std::vector bip3x::Bip39Mnemonic::getLanguages() { 52 | int sz = bip39_get_languages_size(); 53 | if (sz <= 0) { 54 | @@ -72,7 +114,7 @@ bip3x::Bip39Mnemonic::MnemonicResult bip3x::Bip39Mnemonic::encodeBytes(const uin 55 | return result; 56 | } 57 | 58 | - result.words = toolbox::strings::split(output[0], " "); 59 | + result.words = split_1(output[0], " "); 60 | result.len = result.words.size(); 61 | result.raw = std::string(output[0]); 62 | 63 | diff --git a/src/minter/HDKeyEncoder.cpp b/src/minter/HDKeyEncoder.cpp 64 | index a17bed4..b448cd1 100644 65 | --- a/src/minter/HDKeyEncoder.cpp 66 | +++ b/src/minter/HDKeyEncoder.cpp 67 | @@ -13,6 +13,47 @@ 68 | #include 69 | #include 70 | 71 | +std::string glue_2(const std::string& glue, const std::vector& strings) { 72 | + std::string out; 73 | + 74 | + size_t size = strings.size(); 75 | + size_t i = 0; 76 | + for (auto& s : strings) { 77 | + if (i == 0 || i == size) { 78 | + out.append(s); 79 | + } else { 80 | + out.append(glue).append(s); 81 | + } 82 | + 83 | + i++; 84 | + } 85 | + 86 | + return out; 87 | +} 88 | + 89 | +std::vector split_2(const std::string& source, const std::string& delimiter) { 90 | + if (delimiter.empty()) { 91 | + return std::vector(0); 92 | + } 93 | + 94 | + std::string src = source; 95 | + 96 | + std::vector result; 97 | + size_t current = 0; 98 | + while (current != src.npos) { 99 | + current = src.find(delimiter); 100 | + if (current != src.npos && src.substr(current, delimiter.length()) == delimiter) { 101 | + result.push_back(src.substr(0, current)); 102 | + src = src.substr(current + (delimiter.length()), src.npos); 103 | + } 104 | + } 105 | + if (src.length() > 0) { 106 | + result.push_back(src); 107 | + } 108 | + 109 | + return result; 110 | +} 111 | + 112 | bip3x::bytes_64 bip3x::HDKeyEncoder::makeBip39Seed(const std::string& mnemonicWords) { 113 | size_t n; 114 | bytes_64 out; 115 | @@ -20,7 +61,7 @@ bip3x::bytes_64 bip3x::HDKeyEncoder::makeBip39Seed(const std::string& mnemonicWo 116 | return out; 117 | } 118 | bip3x::bytes_64 bip3x::HDKeyEncoder::makeBip39Seed(const std::vector& mnemonicWords) { 119 | - return makeBip39Seed(toolbox::strings::glue(" ", mnemonicWords)); 120 | + return makeBip39Seed(glue_2(" ", mnemonicWords)); 121 | } 122 | 123 | bip3x::HDKey bip3x::HDKeyEncoder::makeBip32RootKey(const char* mnemonic, bip3x::BTCNetwork net) { 124 | @@ -115,7 +156,7 @@ void bip3x::HDKeyEncoder::derive(bip3x::HDKey& key, uint32_t index) { 125 | } 126 | 127 | void bip3x::HDKeyEncoder::derivePath(HDKey& key, const std::string& path, bool priv) { 128 | - std::vector pathBits = toolbox::strings::split(path, "/"); 129 | + std::vector pathBits = split_2(path, "/"); 130 | for (const auto& bit : pathBits) { 131 | if (bit == "m" || bit == "'") { 132 | continue; 133 | -------------------------------------------------------------------------------- /tests/ArrayTest.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "inputs": [ 4 | { 5 | "internalType": "bytes", 6 | "name": "item", 7 | "type": "bytes" 8 | }, 9 | { 10 | "internalType": "bytes", 11 | "name": "item2", 12 | "type": "bytes" 13 | } 14 | ], 15 | "name": "addMultipleToByteList", 16 | "outputs": [], 17 | "stateMutability": "nonpayable", 18 | "type": "function" 19 | }, 20 | { 21 | "inputs": [ 22 | { 23 | "internalType": "string", 24 | "name": "item", 25 | "type": "string" 26 | }, 27 | { 28 | "internalType": "string", 29 | "name": "item2", 30 | "type": "string" 31 | } 32 | ], 33 | "name": "addMultipleToStringList", 34 | "outputs": [], 35 | "stateMutability": "nonpayable", 36 | "type": "function" 37 | }, 38 | { 39 | "inputs": [ 40 | { 41 | "internalType": "address", 42 | "name": "item", 43 | "type": "address" 44 | } 45 | ], 46 | "name": "addToAddressList", 47 | "outputs": [], 48 | "stateMutability": "nonpayable", 49 | "type": "function" 50 | }, 51 | { 52 | "inputs": [ 53 | { 54 | "internalType": "address[]", 55 | "name": "list", 56 | "type": "address[]" 57 | } 58 | ], 59 | "name": "addToAddressListArr", 60 | "outputs": [], 61 | "stateMutability": "nonpayable", 62 | "type": "function" 63 | }, 64 | { 65 | "inputs": [ 66 | { 67 | "internalType": "bytes", 68 | "name": "item", 69 | "type": "bytes" 70 | } 71 | ], 72 | "name": "addToByteList", 73 | "outputs": [], 74 | "stateMutability": "nonpayable", 75 | "type": "function" 76 | }, 77 | { 78 | "inputs": [ 79 | { 80 | "internalType": "bytes[]", 81 | "name": "list", 82 | "type": "bytes[]" 83 | } 84 | ], 85 | "name": "addToByteListArr", 86 | "outputs": [], 87 | "stateMutability": "nonpayable", 88 | "type": "function" 89 | }, 90 | { 91 | "inputs": [ 92 | { 93 | "internalType": "string", 94 | "name": "item", 95 | "type": "string" 96 | } 97 | ], 98 | "name": "addToStringList", 99 | "outputs": [], 100 | "stateMutability": "nonpayable", 101 | "type": "function" 102 | }, 103 | { 104 | "inputs": [ 105 | { 106 | "internalType": "string[]", 107 | "name": "list", 108 | "type": "string[]" 109 | } 110 | ], 111 | "name": "addToStringListArr", 112 | "outputs": [], 113 | "stateMutability": "nonpayable", 114 | "type": "function" 115 | }, 116 | { 117 | "inputs": [ 118 | { 119 | "internalType": "uint256", 120 | "name": "value", 121 | "type": "uint256" 122 | }, 123 | { 124 | "internalType": "string[]", 125 | "name": "list", 126 | "type": "string[]" 127 | } 128 | ], 129 | "name": "addToStringListArrWithValue", 130 | "outputs": [], 131 | "stateMutability": "nonpayable", 132 | "type": "function" 133 | }, 134 | { 135 | "inputs": [ 136 | { 137 | "internalType": "uint256", 138 | "name": "item1", 139 | "type": "uint256" 140 | }, 141 | { 142 | "internalType": "address", 143 | "name": "item2", 144 | "type": "address" 145 | }, 146 | { 147 | "internalType": "bool", 148 | "name": "item3", 149 | "type": "bool" 150 | }, 151 | { 152 | "internalType": "bytes", 153 | "name": "item4", 154 | "type": "bytes" 155 | }, 156 | { 157 | "internalType": "string", 158 | "name": "item5", 159 | "type": "string" 160 | }, 161 | { 162 | "internalType": "string[]", 163 | "name": "item6", 164 | "type": "string[]" 165 | }, 166 | { 167 | "internalType": "address[]", 168 | "name": "item7", 169 | "type": "address[]" 170 | }, 171 | { 172 | "internalType": "bytes[]", 173 | "name": "item8", 174 | "type": "bytes[]" 175 | } 176 | ], 177 | "name": "testAlmostAll", 178 | "outputs": [], 179 | "stateMutability": "nonpayable", 180 | "type": "function" 181 | }, 182 | { 183 | "inputs": [ 184 | { 185 | "internalType": "bytes[]", 186 | "name": "list1", 187 | "type": "bytes[]" 188 | }, 189 | { 190 | "internalType": "bytes[]", 191 | "name": "list2", 192 | "type": "bytes[]" 193 | } 194 | ], 195 | "name": "testMultipleByteArray", 196 | "outputs": [], 197 | "stateMutability": "nonpayable", 198 | "type": "function" 199 | }, 200 | { 201 | "inputs": [ 202 | { 203 | "internalType": "uint256[]", 204 | "name": "array1", 205 | "type": "uint256[]" 206 | }, 207 | { 208 | "internalType": "uint256[]", 209 | "name": "array2", 210 | "type": "uint256[]" 211 | } 212 | ], 213 | "name": "testMultipleUint256Array", 214 | "outputs": [], 215 | "stateMutability": "nonpayable", 216 | "type": "function" 217 | } 218 | ] -------------------------------------------------------------------------------- /include/web3cpp/devcore/Guards.h: -------------------------------------------------------------------------------- 1 | // Aleth: Ethereum C++ client, tools and libraries. 2 | // Copyright 2014-2019 Aleth Authors. 3 | // Licensed under the GNU General Public License, Version 3. 4 | 5 | #pragma once 6 | 7 | #include 8 | #include 9 | #include 10 | #pragma warning(push) 11 | #pragma GCC diagnostic push 12 | #pragma GCC diagnostic ignored "-Wunused-parameter" 13 | #include 14 | #pragma warning(pop) 15 | #pragma GCC diagnostic pop 16 | 17 | namespace dev 18 | { 19 | 20 | using Mutex = std::mutex; 21 | using RecursiveMutex = std::recursive_mutex; 22 | using SharedMutex = boost::shared_mutex; 23 | 24 | using Guard = std::lock_guard; 25 | using UniqueGuard = std::unique_lock; 26 | using RecursiveGuard = std::lock_guard; 27 | using ReadGuard = boost::shared_lock; 28 | using UpgradableGuard = boost::upgrade_lock; 29 | using UpgradeGuard = boost::upgrade_to_unique_lock; 30 | using WriteGuard = boost::unique_lock; 31 | 32 | template 33 | struct GenericGuardBool: GuardType 34 | { 35 | GenericGuardBool(MutexType& _m): GuardType(_m) {} 36 | bool b = true; 37 | }; 38 | template 39 | struct GenericUnguardBool 40 | { 41 | GenericUnguardBool(MutexType& _m): m(_m) { m.unlock(); } 42 | ~GenericUnguardBool() { m.lock(); } 43 | bool b = true; 44 | MutexType& m; 45 | }; 46 | template 47 | struct GenericUnguardSharedBool 48 | { 49 | GenericUnguardSharedBool(MutexType& _m): m(_m) { m.unlock_shared(); } 50 | ~GenericUnguardSharedBool() { m.lock_shared(); } 51 | bool b = true; 52 | MutexType& m; 53 | }; 54 | 55 | template 56 | class Notified 57 | { 58 | public: 59 | Notified() {} 60 | Notified(N const& _v): m_value(_v) {} 61 | Notified(Notified const&) = delete; 62 | Notified& operator=(N const& _v) { UniqueGuard l(m_mutex); m_value = _v; m_cv.notify_all(); return *this; } 63 | 64 | operator N() const { UniqueGuard l(m_mutex); return m_value; } 65 | 66 | void wait() const { N old; { UniqueGuard l(m_mutex); old = m_value; } waitNot(old); } 67 | void wait(N const& _v) const { UniqueGuard l(m_mutex); m_cv.wait(l, [&](){return m_value == _v;}); } 68 | void waitNot(N const& _v) const { UniqueGuard l(m_mutex); m_cv.wait(l, [&](){return m_value != _v;}); } 69 | template void wait(F const& _f) const { UniqueGuard l(m_mutex); m_cv.wait(l, _f); } 70 | 71 | template void wait(std::chrono::duration _d) const { N old; { UniqueGuard l(m_mutex); old = m_value; } waitNot(_d, old); } 72 | template void wait(std::chrono::duration _d, N const& _v) const { UniqueGuard l(m_mutex); m_cv.wait_for(l, _d, [&](){return m_value == _v;}); } 73 | template void waitNot(std::chrono::duration _d, N const& _v) const { UniqueGuard l(m_mutex); m_cv.wait_for(l, _d, [&](){return m_value != _v;}); } 74 | template void wait(std::chrono::duration _d, F const& _f) const { UniqueGuard l(m_mutex); m_cv.wait_for(l, _d, _f); } 75 | 76 | private: 77 | mutable Mutex m_mutex; 78 | mutable std::condition_variable m_cv; 79 | N m_value; 80 | }; 81 | 82 | /** @brief Simple block guard. 83 | * The expression/block following is guarded though the given mutex. 84 | * Usage: 85 | * @code 86 | * Mutex m; 87 | * unsigned d; 88 | * ... 89 | * ETH_(m) d = 1; 90 | * ... 91 | * ETH_(m) { for (auto d = 10; d > 0; --d) foo(d); d = 0; } 92 | * @endcode 93 | * 94 | * There are several variants of this basic mechanism for different Mutex types and Guards. 95 | * 96 | * There is also the UNGUARD variant which allows an unguarded expression/block to exist within a 97 | * guarded expression. eg: 98 | * 99 | * @code 100 | * Mutex m; 101 | * int d; 102 | * ... 103 | * ETH_GUARDED(m) 104 | * { 105 | * for (auto d = 50; d > 25; --d) 106 | * foo(d); 107 | * ETH_UNGUARDED(m) 108 | * bar(); 109 | * for (; d > 0; --d) 110 | * foo(d); 111 | * } 112 | * @endcode 113 | */ 114 | 115 | #define DEV_GUARDED(MUTEX) \ 116 | for (GenericGuardBool __eth_l(MUTEX); __eth_l.b; __eth_l.b = false) 117 | #define DEV_READ_GUARDED(MUTEX) \ 118 | for (GenericGuardBool __eth_l(MUTEX); __eth_l.b; __eth_l.b = false) 119 | #define DEV_WRITE_GUARDED(MUTEX) \ 120 | for (GenericGuardBool __eth_l(MUTEX); __eth_l.b; __eth_l.b = false) 121 | #define DEV_RECURSIVE_GUARDED(MUTEX) \ 122 | for (GenericGuardBool __eth_l(MUTEX); __eth_l.b; __eth_l.b = false) 123 | #define DEV_UNGUARDED(MUTEX) \ 124 | for (GenericUnguardBool __eth_l(MUTEX); __eth_l.b; __eth_l.b = false) 125 | #define DEV_READ_UNGUARDED(MUTEX) \ 126 | for (GenericUnguardSharedBool __eth_l(MUTEX); __eth_l.b; __eth_l.b = false) 127 | #define DEV_WRITE_UNGUARDED(MUTEX) \ 128 | for (GenericUnguardBool __eth_l(MUTEX); __eth_l.b; __eth_l.b = false) 129 | 130 | } 131 | -------------------------------------------------------------------------------- /cmake/WindowsLibraries.cmake: -------------------------------------------------------------------------------- 1 | # TODO: revise library order, it's very messy 2 | SET(QT_LIBS "") 3 | LIST(APPEND QT_LIBS "-limm32 -ldwmapi -lwinmm -lversion -lwtsapi32 -lmincore -luserenv -lnetui1 -lnetapi32 -ldxgi -ld3d11 -lsetupapi -fstack-protector") 4 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/plugins/imageformats/libqgif.a") 5 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5Network.a") 6 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5Gui.a") 7 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5Qml.a") 8 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5QmlWorkerScript.a") 9 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/plugins/platforms/libqdirect2d.a") 10 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/qml/QtQuick.2/libqtquick2plugin.a") 11 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/qml/QtQuick/Window.2/libwindowplugin.a") 12 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5QmlModels.a") 13 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5Quick.a") 14 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libqtlibpng.a") 15 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libqtharfbuzz.a") 16 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libz.a") 17 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5Widgets.a") 18 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5WindowsUIAutomationSupport.a") 19 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/plugins/platforms/libqwindows.a") 20 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libqtpcre2.a") 21 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5Core.a") 22 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5EdidSupport.a") 23 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5EventDispatcherSupport.a") 24 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5ThemeSupport.a") 25 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5FontDatabaseSupport.a") 26 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/plugins/platforms/libqdirect2d.a") 27 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/plugins/platforms/libqminimal.a") 28 | # I don't know why this works the way it does, it just *does*, let's roll with it 29 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5Network.a") 30 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5Gui.a") 31 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/qml/QtQuick/Controls.2/libqtquickcontrols2plugin.a") 32 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5QuickControls2.a") 33 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/qml/QtQuick/Templates.2/libqtquicktemplates2plugin.a") 34 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5QuickTemplates2.a") 35 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/qml/Qt/labs/platform/libqtlabsplatformplugin.a") 36 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5Widgets.a") 37 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/qml/QtCharts/libqtchartsqml2.a") 38 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5Charts.a") 39 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/plugins/imageformats/libqsvg.a") 40 | LIST(APPEND QT_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libQt5Svg.a") 41 | 42 | SET(BOOST_LIBS "") 43 | LIST(APPEND BOOST_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libboost_filesystem-mt-s-x64.a") 44 | LIST(APPEND BOOST_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libboost_program_options-mt-s-x64.a") 45 | LIST(APPEND BOOST_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libboost_system-mt-s-x64.a") 46 | LIST(APPEND BOOST_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libboost_thread-mt-s-x64.a") 47 | LIST(APPEND BOOST_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libboost_chrono-mt-s-x64.a") 48 | LIST(APPEND BOOST_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libboost_nowide-mt-s-x64.a") 49 | LIST(APPEND BOOST_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libprotobuf.a") 50 | LIST(APPEND BOOST_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libusb-1.0.a") 51 | LIST(APPEND BOOST_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libhidapi.a") 52 | LIST(APPEND BOOST_LIBS "-static -luxtheme -lsetupapi") 53 | 54 | SET(OPENSSL_LIBS "") 55 | LIST(APPEND OPENSSL_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libcrypto.a") 56 | LIST(APPEND OPENSSL_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libssl.a") 57 | 58 | SET(QRENCODE_LIBS "") 59 | LIST(APPEND QRENCODE_LIBS "${CMAKE_SOURCE_DIR}/depends/${DEPENDS_PREFIX}/lib/libqrencode.a") 60 | -------------------------------------------------------------------------------- /cmake/web3cpp_install.patch: -------------------------------------------------------------------------------- 1 | diff --git a/CMakeLists.txt b/CMakeLists.txt 2 | index e9208ae..a94221a 100644 3 | --- a/CMakeLists.txt 4 | +++ b/CMakeLists.txt 5 | @@ -135,7 +135,7 @@ target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/i 6 | 7 | # Link project to dependencies and external libraries 8 | target_link_libraries(${PROJECT_NAME} PUBLIC 9 | - ${Boost_LIBRARIES} ssl crypto nlohmann_json::nlohmann_json cryptopp scrypt 10 | + ${Boost_LIBRARIES} ssl crypto nlohmann_json::nlohmann_json libcryptopp scrypt 11 | Secp256k1 bip39 toolbox ${ETHASH_BYPRODUCTS} Ethash LevelDB snappy 12 | ) 13 | 14 | @@ -155,3 +155,12 @@ set_target_properties(${PROJECT_NAME} PROPERTIES PUBLIC_HEADER "include/web3cpp/ 15 | set_target_properties(${PROJECT_NAME} PROPERTIES LINKER_LANGUAGE CXX) 16 | set_target_properties(${PROJECT_NAME} PROPERTIES LANGUAGE CXX) 17 | 18 | +install(TARGETS web3cpp 19 | + EXPORT web3cppTargets 20 | + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} 21 | + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} 22 | + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} 23 | +) 24 | +install(DIRECTORY include/ DESTINATION include) 25 | + 26 | + 27 | diff --git a/cmake/ProjectCryptoPP.cmake b/cmake/ProjectCryptoPP.cmake 28 | index 2b8a7bf..0fefa21 100644 29 | --- a/cmake/ProjectCryptoPP.cmake 30 | +++ b/cmake/ProjectCryptoPP.cmake 31 | @@ -27,9 +27,9 @@ ExternalProject_Add( 32 | BUILD_BYPRODUCTS "${CRYPTOPP_LIBRARY}" 33 | ) 34 | 35 | -add_library(cryptopp STATIC IMPORTED) 36 | +add_library(libcryptopp STATIC IMPORTED) 37 | file(MAKE_DIRECTORY "${CRYPTOPP_INCLUDE_DIR}") # Must exist. 38 | -set_property(TARGET cryptopp PROPERTY IMPORTED_CONFIGURATIONS Release) 39 | -set_property(TARGET cryptopp PROPERTY IMPORTED_LOCATION_RELEASE "${CRYPTOPP_LIBRARY}") 40 | -set_property(TARGET cryptopp PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${CRYPTOPP_INCLUDE_DIR}") 41 | +set_property(TARGET libcryptopp PROPERTY IMPORTED_CONFIGURATIONS Release) 42 | +set_property(TARGET libcryptopp PROPERTY IMPORTED_LOCATION_RELEASE "${CRYPTOPP_LIBRARY}") 43 | +set_property(TARGET libcryptopp PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${CRYPTOPP_INCLUDE_DIR}") 44 | 45 | diff --git a/include/web3cpp/Account.h b/include/web3cpp/Account.h 46 | index b4dfb69..47a701b 100644 47 | --- a/include/web3cpp/Account.h 48 | +++ b/include/web3cpp/Account.h 49 | @@ -50,7 +50,7 @@ class Account { 50 | ); 51 | 52 | /// Copy constructor. 53 | - Account(Account& other) noexcept : 54 | + Account(const Account& other) noexcept : 55 | _address(other._address), 56 | _name(other._name), 57 | _derivationPath(other._derivationPath), 58 | diff --git a/include/web3cpp/DB.h b/include/web3cpp/DB.h 59 | index c2fbac9..adfb178 100644 60 | --- a/include/web3cpp/DB.h 61 | +++ b/include/web3cpp/DB.h 62 | @@ -53,7 +53,7 @@ class Database { 63 | } 64 | 65 | /// Copy constructor. 66 | - Database(Database& other) noexcept : 67 | + Database(const Database& other) noexcept : 68 | name(other.name), path(other.path), db(other.db), 69 | dbOpts(other.dbOpts), dbStatus(other.dbStatus), tmpValue(other.tmpValue) 70 | {} 71 | diff --git a/include/web3cpp/Wallet.h b/include/web3cpp/Wallet.h 72 | index 9fd598b..5ca2fdd 100644 73 | --- a/include/web3cpp/Wallet.h 74 | +++ b/include/web3cpp/Wallet.h 75 | @@ -259,6 +259,15 @@ class Wallet { 76 | */ 77 | std::vector getAccounts(); 78 | 79 | + /** 80 | + * Get the account seed phrase 81 | + * @param password the Wallet's password. 82 | + * @param &err Error object. 83 | + * @return The wallet seed phrase. 84 | + */ 85 | + 86 | + std::string getSeedPhrase(std::string password, Error &err); 87 | + 88 | /** 89 | * Get the details for a specific account. 90 | * @param address The address of the account. Will be converted to lowercase. 91 | diff --git a/src/Wallet.cpp b/src/Wallet.cpp 92 | index af802ff..23de2dc 100644 93 | --- a/src/Wallet.cpp 94 | +++ b/src/Wallet.cpp 95 | @@ -348,3 +348,17 @@ json Wallet::getAccountRawDetails(std::string address) { 96 | return ret; 97 | } 98 | 99 | +std::string Wallet::getSeedPhrase(std::string password, Error &err) { 100 | + std::string seedPhrase; 101 | + Error readErr, decErr; 102 | + boost::filesystem::path tmpPath = seedPhraseFile(); 103 | + json seedJson = Utils::readJSONFile(tmpPath, readErr); 104 | + if (readErr.getCode() != 0) { 105 | + err.setCode(readErr.getCode()); 106 | + return ""; 107 | + } 108 | + seedPhrase = Cipher::decrypt(seedJson.dump(), password, decErr); 109 | + if (decErr.getCode() != 0) { err.setCode(decErr.getCode()); return ""; } 110 | + return seedPhrase; 111 | +} 112 | + 113 | diff --git a/src/devcrypto/CryptoPP.cpp b/src/devcrypto/CryptoPP.cpp 114 | index 42f1588..cb5613e 100644 115 | --- a/src/devcrypto/CryptoPP.cpp 116 | +++ b/src/devcrypto/CryptoPP.cpp 117 | @@ -10,7 +10,7 @@ 118 | #include 119 | #include 120 | 121 | -static_assert(CRYPTOPP_VERSION == 820, "Wrong Crypto++ version"); 122 | +static_assert(CRYPTOPP_VERSION >= 820, "Wrong Crypto++ version"); 123 | 124 | using namespace dev; 125 | using namespace dev::crypto; 126 | --------------------------------------------------------------------------------