Browse Source

Merge remote-tracking branch 'chfast/ethminer-remove-code'

cl-refactor
Paweł Bylica 8 years ago
parent
commit
7dc32ce961
No known key found for this signature in database GPG Key ID: 7A0C037434FE77EF
  1. 1
      BuildInfo.h.in
  2. 161
      CMakeLists.txt
  3. 42
      cmake/EthCompilerSettings.cmake
  4. 100
      cmake/EthDependencies.cmake
  5. 33
      cmake/FindCpuid.cmake
  6. 108
      cmake/FindCryptoPP.cmake
  7. 34
      cmake/FindGmp.cmake
  8. 49
      cmake/FindLevelDB.cmake
  9. 54
      cmake/FindMHD.cmake
  10. 49
      cmake/FindMiniupnpc.cmake
  11. 34
      cmake/FindReadline.cmake
  12. 322
      cmake/FindWindowsSDK.cmake
  13. 69
      cmake/Findv8.cmake
  14. 6
      cmake/scripts/buildinfo.cmake
  15. 1
      ethminer/CMakeLists.txt
  16. 96
      ethminer/MinerAux.h
  17. 28
      ethminer/PhoneHome.h
  18. 5
      ethminer/main.cpp
  19. 3
      ethminer/phonehome.json
  20. 1
      libdevcore/Assertions.h
  21. 146
      libdevcore/Base64.cpp
  22. 62
      libdevcore/Base64.h
  23. 21
      libdevcore/CMakeLists.txt
  24. 26
      libdevcore/Common.cpp
  25. 150
      libdevcore/Common.h
  26. 32
      libdevcore/CommonData.cpp
  27. 224
      libdevcore/CommonData.h
  28. 182
      libdevcore/CommonIO.cpp
  29. 270
      libdevcore/CommonIO.h
  30. 1
      libdevcore/CommonJS.h
  31. 52
      libdevcore/Diff.h
  32. 73
      libdevcore/FileSystem.cpp
  33. 35
      libdevcore/FileSystem.h
  34. 10
      libdevcore/Guards.h
  35. 440
      libdevcore/Hash.cpp
  36. 38
      libdevcore/Hash.h
  37. 8
      libdevcore/Log.cpp
  38. 22
      libdevcore/Log.h
  39. 183
      libdevcore/MemoryDB.cpp
  40. 99
      libdevcore/MemoryDB.h
  41. 22
      libdevcore/RangeMask.cpp
  42. 294
      libdevcore/RangeMask.h
  43. 1
      libdevcore/SHA3.cpp
  44. 25
      libdevcore/SHA3.h
  45. 251
      libdevcore/StructuredLogger.cpp
  46. 111
      libdevcore/StructuredLogger.h
  47. 66
      libdevcore/TransientDirectory.cpp
  48. 47
      libdevcore/TransientDirectory.h
  49. 127
      libdevcore/TrieCommon.cpp
  50. 133
      libdevcore/TrieCommon.h
  51. 30
      libdevcore/TrieDB.cpp
  52. 1224
      libdevcore/TrieDB.h
  53. 195
      libdevcore/TrieHash.cpp
  54. 46
      libdevcore/TrieHash.h
  55. 46
      libdevcore/UndefMacros.h
  56. 21
      libdevcore/Worker.cpp
  57. 60
      libdevcore/concurrent_queue.h
  58. 30
      libdevcore/db.h
  59. 121
      libdevcore/debugbreak.h
  60. 360
      libdevcore/picosha2.h
  61. 13054
      libethash-cl/CL/cl.hpp
  62. 2
      libethash-cl/CMakeLists.txt
  63. 17
      libethash-cl/ethash_cl_miner.h
  64. 12
      libethash/CMakeLists.txt
  65. 97
      libethcore/BlockInfo.cpp
  66. 21
      libethcore/BlockInfo.h
  67. 27
      libethcore/CMakeLists.txt
  68. 143
      libethcore/Common.cpp
  69. 175
      libethcore/Common.h
  70. 196
      libethcore/Ethash.cpp
  71. 32
      libethcore/Ethash.h
  72. 1
      libethcore/EthashAux.cpp
  73. 55
      libethcore/EthashCPUMiner.cpp
  74. 2
      libethcore/EthashCUDAMiner.cpp
  75. 2
      libethcore/EthashCUDAMiner.h
  76. 2
      libethcore/EthashGPUMiner.cpp
  77. 2
      libethcore/EthashGPUMiner.h
  78. 27
      libethcore/EthashSealEngine.cpp
  79. 12
      libethcore/EthashSealEngine.h
  80. 6
      libethcore/Miner.h
  81. 75
      libethcore/Params.cpp
  82. 43
      libethcore/Params.h
  83. 26
      libethcore/Sealer.cpp
  84. 77
      libethcore/Sealer.h
  85. 4
      libstratum/CMakeLists.txt
  86. 1
      libstratum/EthStratumClient.cpp
  87. 1
      libstratum/EthStratumClientV2.cpp

1
BuildInfo.h.in

@ -5,4 +5,3 @@
#define ETH_CLEAN_REPO @ETH_CLEAN_REPO@
#define ETH_BUILD_TYPE @ETH_BUILD_TYPE@
#define ETH_BUILD_PLATFORM @ETH_BUILD_PLATFORM@
#define ETH_FATDB @ETH_FATDB@

161
CMakeLists.txt

@ -1,17 +1,10 @@
# cmake global
cmake_minimum_required(VERSION 2.8.12)
cmake_minimum_required(VERSION 3.0)
set(PROJECT_VERSION "0.9.41")
set(GENOIL_VERSION "1.1.7")
if (${CMAKE_VERSION} VERSION_GREATER 3.0)
cmake_policy(SET CMP0042 OLD) # fix MACOSX_RPATH
cmake_policy(SET CMP0048 NEW) # allow VERSION argument in project()
project(ethereum VERSION ${PROJECT_VERSION})
else()
project(ethereum)
endif()
set(CMAKE_AUTOMOC ON)
cmake_policy(SET CMP0042 OLD) # fix MACOSX_RPATH
cmake_policy(SET CMP0048 NEW) # allow VERSION argument in project()
project(ethereum VERSION 0.9.41)
# link_directories interprate relative paths with respect to CMAKE_CURRENT_SOURCE_DIR
cmake_policy(SET CMP0015 NEW)
@ -21,10 +14,7 @@ cmake_policy(SET CMP0015 NEW)
cmake_policy(SET CMP0020 NEW)
# 3.1 and above
if ((${CMAKE_MAJOR_VERSION} GREATER 2) AND (${CMAKE_MINOR_VERSION} GREATER 0))
# implicitly dereference variables (deprecated in 3.1)
cmake_policy(SET CMP0054 NEW)
endif()
cmake_policy(SET CMP0054 NEW)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
@ -36,65 +26,17 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
#defaults:
set(D_CMAKE_BUILD_TYPE "Release")
set(D_GUI ON)
set(D_ETHASHCL ON)
set(D_ETHASHCUDA OFF)
set(D_JSONRPC ON)
set(D_VMTRACE OFF)
set(D_PARANOID OFF)
set(D_PROFILING OFF)
set(D_OLYMPIC OFF)
set(D_MINER ON)
set(D_ETHSTRATUM OFF)
if (BUNDLE STREQUAL "minimal")
set(D_GUI OFF)
elseif (BUNDLE STREQUAL "full")
set(D_GUI ON)
elseif (BUNDLE STREQUAL "cli")
set(D_GUI OFF)
elseif (BUNDLE STREQUAL "core")
set(D_GUI ON)
elseif (BUNDLE STREQUAL "user")
set(D_GUI ON)
elseif (BUNDLE STREQUAL "wallet")
set(D_GUI OFF)
set(D_MINER OFF)
set(D_ETHASHCL OFF)
set(D_JSONRPC OFF)
elseif (BUNDLE STREQUAL "miner")
set(D_GUI OFF)
set(D_MINER ON)
set(D_ETHASHCL ON)
set(D_JSONRPC ON)
set(D_ETHSTRATUM ON)
elseif (BUNDLE STREQUAL "cudaminer")
set(D_GUI OFF)
set(D_MINER ON)
set(D_ETHASHCL ON)
set(D_ETHASHCUDA ON)
set(D_JSONRPC ON)
set(D_ETHSTRATUM ON)
elseif (BUNDLE STREQUAL "release") # release builds
set(D_GUI ON)
set(D_ETHASHCL ON)
set(D_JSONRPC ON)
set(D_CMAKE_BUILD_TYPE "Release")
endif ()
if ("${CMAKE_BUILD_TYPE}" STREQUAL "")
set(CMAKE_BUILD_TYPE ${D_CMAKE_BUILD_TYPE})
endif ()
# propagates CMake configuration options to the compiler
function(configureProject)
if (PARANOID)
add_definitions(-DETH_PARANOIA)
endif ()
if (VMTRACE)
add_definitions(-DETH_VMTRACE)
endif ()
if (ETHASHCL)
add_definitions(-DETH_ETHASHCL)
@ -107,30 +49,6 @@ function(configureProject)
if (ETHSTRATUM)
add_definitions(-DETH_STRATUM)
endif()
if (FATDB)
add_definitions(-DETH_FATDB)
endif()
if (GUI)
add_definitions(-DETH_GUI)
endif()
if (CPUID_FOUND)
add_definitions(-DETH_CPUID)
endif()
if (CURL_FOUND)
add_definitions(-DETH_CURL)
endif()
if (OLYMPIC)
add_definitions(-DETH_OLYMPIC)
else()
add_definitions(-DETH_FRONTIER)
endif()
add_definitions(-DETH_TRUE)
endfunction()
set(CPPETHEREUM 1)
@ -154,10 +72,6 @@ function(createBuildInfo)
set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/int")
if (PARANOID)
set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/PARA")
endif ()
#cmake build type may be not specified when using msvc
if (CMAKE_BUILD_TYPE)
set(_cmake_build_type ${CMAKE_BUILD_TYPE})
@ -172,7 +86,7 @@ function(createBuildInfo)
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
COMMAND ${CMAKE_COMMAND} -DETH_SOURCE_DIR="${CMAKE_SOURCE_DIR}" -DETH_DST_DIR="${CMAKE_BINARY_DIR}"
-DETH_BUILD_TYPE="${_cmake_build_type}" -DETH_BUILD_PLATFORM="${ETH_BUILD_PLATFORM}"
-DPROJECT_VERSION="${PROJECT_VERSION}" -DGENOIL_VERSION="${GENOIL_VERSION}" -DETH_FATDB="${FATDB}"
-DPROJECT_VERSION="${PROJECT_VERSION}" -DGENOIL_VERSION="${GENOIL_VERSION}"
-P "${ETH_SCRIPTS_DIR}/buildinfo.cmake"
)
include_directories(${CMAKE_CURRENT_BINARY_DIR})
@ -185,28 +99,6 @@ endfunction()
######################################################################################################
# Clear invalid option
if ("${CMAKE_BUILD_TYPE}" STREQUAL "Release")
if (PARANOID)
message("Paranoia requires debug - disabling for release build.")
set(PARANOID OFF)
endif ()
if (VMTRACE)
message("VM Tracing requires debug - disabling for release build.")
set (VMTRACE OFF)
endif ()
endif ()
# Force chromium.
set (ETH_HAVE_WEBENGINE 1)
# Backwards compatibility
if (HEADLESS)
message("*** WARNING: -DHEADLESS=1 option is DEPRECATED! Use -DBUNDLE=minimal or -DGUI=0")
set(GUI OFF)
endif ()
macro(eth_format_option O)
if (${${O}})
set(${O} ON)
@ -218,21 +110,11 @@ macro(eth_format_option O)
endmacro()
# Normalise build options
eth_format_option(PARANOID)
eth_format_option(VMTRACE)
eth_format_option(JSONRPC)
eth_format_option(MINER)
eth_format_option(PROFILING)
eth_format_option(GUI)
eth_format_option(ETHASHCL)
eth_format_option(ETHASHCUDA)
eth_format_option(OLYMPIC)
eth_format_option(ETHSTRATUM)
if (GUI)
set(JSONRPC ON)
endif()
# Default CMAKE_BUILD_TYPE accordingly.
set(CMAKE_BUILD_TYPE CACHE STRING ${D_CMAKE_BUILD_TYPE})
@ -251,19 +133,11 @@ message("-----------------------------------------------------------------------
message("-- CMake Version ${CMAKE_VERSION}")
message("-- CMAKE_BUILD_TYPE Build type ${CMAKE_BUILD_TYPE}")
message("-- TARGET_PLATFORM Target platform ${TARGET_PLATFORM}")
message("-- BUNDLE Build bundle ${BUNDLE}")
message("--------------------------------------------------------------- features")
message("-- Chromium support ${ETH_HAVE_WEBENGINE}")
message("-- Hardware identification support ${CPUID_FOUND}")
message("-- HTTP Request support ${CURL_FOUND}")
message("-- VMTRACE VM execution tracing ${VMTRACE}")
message("-- PROFILING Profiling support ${PROFILING}")
message("-- FATDB Full database exploring ${FATDB}")
message("-- JSONRPC JSON-RPC support ${JSONRPC}")
message("-- OLYMPIC Default to the Olympic network ${OLYMPIC}")
message("------------------------------------------------------------- components")
message("-- MINER Build miner ${MINER}")
message("-- GUI Build GUI components ${GUI}")
message("-- ETHASHCL Build OpenCL components ${ETHASHCL}")
message("-- ETHASHCUDA Build CUDA components ${ETHASHCUDA}")
message("-- ETHSTRATUM Build Stratum components ${ETHSTRATUM}")
@ -283,23 +157,18 @@ include(EthExecutableHelper)
message("creating build info...")
createBuildInfo()
set(DB_INCLUDE_DIRS ${LEVELDB_INCLUDE_DIRS})
set(DB_LIBRARIES ${LEVELDB_LIBRARIES})
add_subdirectory(libdevcore)
if (MINER)
add_subdirectory(libethash)
if (ETHASHCL)
add_subdirectory(libethash-cl)
endif ()
if (ETHASHCUDA)
add_subdirectory(libethash-cuda)
endif ()
if(ETHSTRATUM)
add_subdirectory(libstratum)
endif()
add_subdirectory(libethash)
if (ETHASHCL)
add_subdirectory(libethash-cl)
endif ()
if (ETHASHCUDA)
add_subdirectory(libethash-cuda)
endif ()
if(ETHSTRATUM)
add_subdirectory(libstratum)
endif()
add_subdirectory(libethcore)
add_subdirectory(ethminer)

42
cmake/EthCompilerSettings.cmake

@ -3,7 +3,7 @@
# C++11 check and activation
if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU")
set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -Wno-error=parentheses -pedantic -DSHAREDLIB -fPIC ${CMAKE_CXX_FLAGS}")
set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -Wno-error=parentheses -pedantic${CMAKE_CXX_FLAGS}")
set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DETH_DEBUG")
set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG -DETH_RELEASE")
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG -DETH_RELEASE")
@ -17,7 +17,7 @@ if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU")
elseif ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -DSHAREDLIB -fPIC")
set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra")
set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DETH_DEBUG")
set(CMAKE_CXX_FLAGS_DEBUGSAN "-O1 -g -fsanitize=address,integer,undefined -fsanitize-blacklist=${CMAKE_SOURCE_DIR}/sanitizer-blacklist.txt -fno-omit-frame-pointer -DETH_DEBUG")
set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG -DETH_RELEASE")
@ -51,45 +51,7 @@ elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
# warning LNK4099: pdb was not found with lib
# stack size 16MB
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /ignore:4099,4075 /STACK:16777216")
# windows likes static
if (NOT ETH_STATIC)
message("Forcing static linkage for MSVC.")
set(ETH_STATIC 1)
endif ()
else ()
message(WARNING "Your compiler is not tested, if you run into any issues, we'd welcome any patches.")
endif ()
if (PROFILING AND (("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") OR ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")))
set(CMAKE_CXX_FLAGS "-g ${CMAKE_CXX_FLAGS}")
set(CMAKE_C_FLAGS "-g ${CMAKE_C_FLAGS}")
add_definitions(-DETH_PROFILING_GPERF)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -lprofiler")
# set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} -lprofiler")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lprofiler")
endif ()
if (PROFILING AND (("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU")))
set(CMAKE_CXX_FLAGS "-g --coverage ${CMAKE_CXX_FLAGS}")
set(CMAKE_C_FLAGS "-g --coverage ${CMAKE_C_FLAGS}")
set(CMAKE_SHARED_LINKER_FLAGS "--coverage ${CMAKE_SHARED_LINKER_FLAGS} -lprofiler")
set(CMAKE_EXE_LINKER_FLAGS "--coverage ${CMAKE_EXE_LINKER_FLAGS} -lprofiler")
endif ()
if (("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") OR ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang"))
option(USE_LD_GOLD "Use GNU gold linker" ON)
if (USE_LD_GOLD)
execute_process(COMMAND ${CMAKE_C_COMPILER} -fuse-ld=gold -Wl,--version ERROR_QUIET OUTPUT_VARIABLE LD_VERSION)
if ("${LD_VERSION}" MATCHES "GNU gold")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fuse-ld=gold")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fuse-ld=gold")
endif ()
endif ()
endif ()
if(ETH_STATIC)
set(BUILD_SHARED_LIBS OFF)
else()
set(BUILD_SHARED_LIBS ON)
endif(ETH_STATIC)

100
cmake/EthDependencies.cmake

@ -41,60 +41,14 @@ message(STATUS "ctest path: ${CTEST_COMMAND}")
# Dependencies must have a version number, to ensure reproducible build. The version provided here is the one that is in the extdep repository. If you use system libraries, version numbers may be different.
find_package (CryptoPP 5.6.2 REQUIRED)
message(" - CryptoPP header: ${CRYPTOPP_INCLUDE_DIRS}")
message(" - CryptoPP lib : ${CRYPTOPP_LIBRARIES}")
find_package (LevelDB REQUIRED)
message(" - LevelDB header: ${LEVELDB_INCLUDE_DIRS}")
message(" - LevelDB lib: ${LEVELDB_LIBRARIES}")
# TODO the Jsoncpp package does not yet check for correct version number
find_package (Jsoncpp 0.60 REQUIRED)
message(" - Jsoncpp header: ${JSONCPP_INCLUDE_DIRS}")
message(" - Jsoncpp lib : ${JSONCPP_LIBRARIES}")
# TODO get rid of -DETH_JSONRPC
# TODO add EXACT once we commit ourselves to cmake 3.x
if (JSONRPC)
find_package (json_rpc_cpp 0.4 REQUIRED)
message (" - json-rpc-cpp header: ${JSON_RPC_CPP_INCLUDE_DIRS}")
message (" - json-rpc-cpp lib : ${JSON_RPC_CPP_LIBRARIES}")
add_definitions(-DETH_JSONRPC)
find_package(MHD)
message(" - microhttpd header: ${MHD_INCLUDE_DIRS}")
message(" - microhttpd lib : ${MHD_LIBRARIES}")
message(" - microhttpd dll : ${MHD_DLLS}")
endif() #JSONRPC
# TODO readline package does not yet check for correct version number
# TODO make readline package dependent on cmake options
# TODO get rid of -DETH_READLINE
find_package (Readline 6.3.8)
if (READLINE_FOUND)
message (" - readline header: ${READLINE_INCLUDE_DIRS}")
message (" - readline lib : ${READLINE_LIBRARIES}")
add_definitions(-DETH_READLINE)
endif ()
# TODO miniupnpc package does not yet check for correct version number
# TODO make miniupnpc package dependent on cmake options
# TODO get rid of -DMINIUPNPC
find_package (Miniupnpc 1.8.2013)
if (MINIUPNPC_FOUND)
message (" - miniupnpc header: ${MINIUPNPC_INCLUDE_DIRS}")
message (" - miniupnpc lib : ${MINIUPNPC_LIBRARIES}")
add_definitions(-DETH_MINIUPNPC)
endif()
# TODO gmp package does not yet check for correct version number
# TODO it is also not required in msvc build
find_package (Gmp 6.0.0)
if (GMP_FOUND)
message(" - gmp header: ${GMP_INCLUDE_DIRS}")
message(" - gmp lib : ${GMP_LIBRARIES}")
endif()
find_package (json_rpc_cpp 0.4 REQUIRED)
message (" - json-rpc-cpp header: ${JSON_RPC_CPP_INCLUDE_DIRS}")
message (" - json-rpc-cpp lib : ${JSON_RPC_CPP_LIBRARIES}")
# curl is only requried for tests
# TODO specify min curl version, on windows we are currently using 7.29
@ -102,13 +56,6 @@ find_package (CURL)
message(" - curl header: ${CURL_INCLUDE_DIRS}")
message(" - curl lib : ${CURL_LIBRARIES}")
# cpuid required for eth
find_package (Cpuid)
if (CPUID_FOUND)
message(" - cpuid header: ${CPUID_INCLUDE_DIRS}")
message(" - cpuid lib : ${CPUID_LIBRARIES}")
endif()
find_package (OpenCL)
if (OpenCL_FOUND)
message(" - opencl header: ${OpenCL_INCLUDE_DIRS}")
@ -125,47 +72,6 @@ endif()
find_program(ETH_JSON_RPC_STUB jsonrpcstub)
message(" - jsonrpcstub location : ${ETH_JSON_RPC_STUB}")
# do not compile GUI
if (GUI)
# we need json rpc to build alethzero
if (NOT JSON_RPC_CPP_FOUND)
message (FATAL_ERROR "JSONRPC is required for GUI client")
endif()
# find all of the Qt packages
# remember to use 'Qt' instead of 'QT', cause unix is case sensitive
# TODO make headless client optional
set (ETH_QT_VERSION 5.4)
find_package (Qt5Core ${ETH_QT_VERSION} REQUIRED)
find_package (Qt5Gui ${ETH_QT_VERSION} REQUIRED)
find_package (Qt5Quick ${ETH_QT_VERSION} REQUIRED)
find_package (Qt5Qml ${ETH_QT_VERSION} REQUIRED)
find_package (Qt5Network ${ETH_QT_VERSION} REQUIRED)
find_package (Qt5Widgets ${ETH_QT_VERSION} REQUIRED)
find_package (Qt5WebEngine ${ETH_QT_VERSION} REQUIRED)
find_package (Qt5WebEngineWidgets ${ETH_QT_VERSION} REQUIRED)
# we need to find path to macdeployqt on mac
if (APPLE)
set (MACDEPLOYQT_APP ${Qt5Core_DIR}/../../../bin/macdeployqt)
message(" - macdeployqt path: ${MACDEPLOYQT_APP}")
endif()
# we need to find path to windeployqt on windows
if (WIN32)
set (WINDEPLOYQT_APP ${Qt5Core_DIR}/../../../bin/windeployqt)
message(" - windeployqt path: ${WINDEPLOYQT_APP}")
endif()
if (APPLE)
find_program(ETH_APP_DMG appdmg)
message(" - appdmg location : ${ETH_APP_DMG}")
endif()
endif() #GUI
# use multithreaded boost libraries, with -mt suffix
set(Boost_USE_MULTITHREADED ON)

33
cmake/FindCpuid.cmake

@ -1,33 +0,0 @@
# Find libcpuid
#
# Find the libcpuid includes and library
#
# if you nee to add a custom library search path, do it via via CMAKE_PREFIX_PATH
#
# This module defines
# CPUID_INCLUDE_DIRS, where to find header, etc.
# CPUID_LIBRARIES, the libraries needed to use cpuid.
# CPUID_FOUND, If false, do not try to use cpuid.
# only look in default directories
find_path(
CPUID_INCLUDE_DIR
NAMES libcpuid/libcpuid.h
DOC "libcpuid include dir"
)
find_library(
CPUID_LIBRARY
NAMES cpuid
DOC "libcpuid library"
)
set(CPUID_INCLUDE_DIRS ${CPUID_INCLUDE_DIR})
set(CPUID_LIBRARIES ${CPUID_LIBRARY})
# handle the QUIETLY and REQUIRED arguments and set CPUID_FOUND to TRUE
# if all listed variables are TRUE, hide their existence from configuration view
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(cpuid DEFAULT_MSG CPUID_INCLUDE_DIR CPUID_LIBRARY)
mark_as_advanced (CPUID_INCLUDE_DIR CPUID_LIBRARY)

108
cmake/FindCryptoPP.cmake

@ -1,108 +0,0 @@
# Module for locating the Crypto++ encryption library.
#
# Customizable variables:
# CRYPTOPP_ROOT_DIR
# This variable points to the CryptoPP root directory. On Windows the
# library location typically will have to be provided explicitly using the
# -D command-line option. The directory should include the include/cryptopp,
# lib and/or bin sub-directories.
#
# Read-only variables:
# CRYPTOPP_FOUND
# Indicates whether the library has been found.
#
# CRYPTOPP_INCLUDE_DIRS
# Points to the CryptoPP include directory.
#
# CRYPTOPP_LIBRARIES
# Points to the CryptoPP libraries that should be passed to
# target_link_libararies.
#
#
# Copyright (c) 2012 Sergiu Dotenco
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
INCLUDE (FindPackageHandleStandardArgs)
FIND_PATH (CRYPTOPP_ROOT_DIR
NAMES cryptopp/cryptlib.h include/cryptopp/cryptlib.h
PATHS ENV CRYPTOPPROOT
DOC "CryptoPP root directory")
# Re-use the previous path:
FIND_PATH (CRYPTOPP_INCLUDE_DIR
NAMES cryptopp/cryptlib.h
HINTS ${CRYPTOPP_ROOT_DIR}
PATH_SUFFIXES include
DOC "CryptoPP include directory")
FIND_LIBRARY (CRYPTOPP_LIBRARY_DEBUG
NAMES cryptlibd cryptoppd
HINTS ${CRYPTOPP_ROOT_DIR}
PATH_SUFFIXES lib
DOC "CryptoPP debug library")
FIND_LIBRARY (CRYPTOPP_LIBRARY_RELEASE
NAMES cryptlib cryptopp
HINTS ${CRYPTOPP_ROOT_DIR}
PATH_SUFFIXES lib
DOC "CryptoPP release library")
IF (CRYPTOPP_LIBRARY_DEBUG AND CRYPTOPP_LIBRARY_RELEASE)
SET (CRYPTOPP_LIBRARY
optimized ${CRYPTOPP_LIBRARY_RELEASE}
debug ${CRYPTOPP_LIBRARY_DEBUG} CACHE DOC "CryptoPP library")
ELSEIF (CRYPTOPP_LIBRARY_RELEASE)
SET (CRYPTOPP_LIBRARY ${CRYPTOPP_LIBRARY_RELEASE} CACHE DOC
"CryptoPP library")
ENDIF (CRYPTOPP_LIBRARY_DEBUG AND CRYPTOPP_LIBRARY_RELEASE)
IF (CRYPTOPP_INCLUDE_DIR)
SET (_CRYPTOPP_VERSION_HEADER ${CRYPTOPP_INCLUDE_DIR}/cryptopp/config.h)
IF (EXISTS ${_CRYPTOPP_VERSION_HEADER})
FILE (STRINGS ${_CRYPTOPP_VERSION_HEADER} _CRYPTOPP_VERSION_TMP REGEX
"^#define CRYPTOPP_VERSION[ \t]+[0-9]+$")
STRING (REGEX REPLACE
"^#define CRYPTOPP_VERSION[ \t]+([0-9]+)" "\\1" _CRYPTOPP_VERSION_TMP
${_CRYPTOPP_VERSION_TMP})
STRING (REGEX REPLACE "([0-9]+)[0-9][0-9]" "\\1" CRYPTOPP_VERSION_MAJOR
${_CRYPTOPP_VERSION_TMP})
STRING (REGEX REPLACE "[0-9]([0-9])[0-9]" "\\1" CRYPTOPP_VERSION_MINOR
${_CRYPTOPP_VERSION_TMP})
STRING (REGEX REPLACE "[0-9][0-9]([0-9])" "\\1" CRYPTOPP_VERSION_PATCH
${_CRYPTOPP_VERSION_TMP})
SET (CRYPTOPP_VERSION_COUNT 3)
SET (CRYPTOPP_VERSION
${CRYPTOPP_VERSION_MAJOR}.${CRYPTOPP_VERSION_MINOR}.${CRYPTOPP_VERSION_PATCH})
ENDIF (EXISTS ${_CRYPTOPP_VERSION_HEADER})
ENDIF (CRYPTOPP_INCLUDE_DIR)
SET (CRYPTOPP_INCLUDE_DIRS ${CRYPTOPP_INCLUDE_DIR})
SET (CRYPTOPP_LIBRARIES ${CRYPTOPP_LIBRARY})
MARK_AS_ADVANCED (CRYPTOPP_INCLUDE_DIR CRYPTOPP_LIBRARY CRYPTOPP_LIBRARY_DEBUG
CRYPTOPP_LIBRARY_RELEASE)
FIND_PACKAGE_HANDLE_STANDARD_ARGS (CryptoPP REQUIRED_VARS
CRYPTOPP_INCLUDE_DIR CRYPTOPP_LIBRARY VERSION_VAR CRYPTOPP_VERSION)

34
cmake/FindGmp.cmake

@ -1,34 +0,0 @@
# Find gmp
#
# Find the gmp includes and library
#
# if you nee to add a custom library search path, do it via via CMAKE_PREFIX_PATH
#
# This module defines
# GMP_INCLUDE_DIRS, where to find header, etc.
# GMP_LIBRARIES, the libraries needed to use gmp.
# GMP_FOUND, If false, do not try to use gmp.
# only look in default directories
find_path(
GMP_INCLUDE_DIR
NAMES gmp.h
DOC "gmp include dir"
)
find_library(
GMP_LIBRARY
NAMES gmp
DOC "gmp library"
)
set(GMP_INCLUDE_DIRS ${GMP_INCLUDE_DIR})
set(GMP_LIBRARIES ${GMP_LIBRARY})
# handle the QUIETLY and REQUIRED arguments and set GMP_FOUND to TRUE
# if all listed variables are TRUE, hide their existence from configuration view
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(gmp DEFAULT_MSG
GMP_INCLUDE_DIR GMP_LIBRARY)
mark_as_advanced (GMP_INCLUDE_DIR GMP_LIBRARY)

49
cmake/FindLevelDB.cmake

@ -1,49 +0,0 @@
# Find leveldb
#
# Find the leveldb includes and library
#
# if you nee to add a custom library search path, do it via via CMAKE_PREFIX_PATH
#
# This module defines
# LEVELDB_INCLUDE_DIRS, where to find header, etc.
# LEVELDB_LIBRARIES, the libraries needed to use leveldb.
# LEVELDB_FOUND, If false, do not try to use leveldb.
# only look in default directories
find_path(
LEVELDB_INCLUDE_DIR
NAMES leveldb/db.h
DOC "leveldb include dir"
)
find_library(
LEVELDB_LIBRARY
NAMES leveldb
DOC "leveldb library"
)
set(LEVELDB_INCLUDE_DIRS ${LEVELDB_INCLUDE_DIR})
set(LEVELDB_LIBRARIES ${LEVELDB_LIBRARY})
# debug library on windows
# same naming convention as in qt (appending debug library with d)
# boost is using the same "hack" as us with "optimized" and "debug"
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
find_library(
LEVELDB_LIBRARY_DEBUG
NAMES leveldbd
DOC "leveldb debug library"
)
set(LEVELDB_LIBRARIES optimized ${LEVELDB_LIBRARIES} debug ${LEVELDB_LIBRARY_DEBUG})
endif()
# handle the QUIETLY and REQUIRED arguments and set LEVELDB_FOUND to TRUE
# if all listed variables are TRUE, hide their existence from configuration view
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(leveldb DEFAULT_MSG
LEVELDB_INCLUDE_DIR LEVELDB_LIBRARY)
mark_as_advanced (LEVELDB_INCLUDE_DIR LEVELDB_LIBRARY)

54
cmake/FindMHD.cmake

@ -1,54 +0,0 @@
# Find microhttpd
#
# Find the microhttpd includes and library
#
# if you need to add a custom library search path, do it via via CMAKE_PREFIX_PATH
#
# This module defines
# MHD_INCLUDE_DIRS, where to find header, etc.
# MHD_LIBRARIES, the libraries needed to use jsoncpp.
# MHD_FOUND, If false, do not try to use jsoncpp.
find_path(
MHD_INCLUDE_DIR
NAMES microhttpd.h
DOC "microhttpd include dir"
)
find_library(
MHD_LIBRARY
NAMES microhttpd microhttpd-10 libmicrohttpd libmicrohttpd-dll
DOC "microhttpd library"
)
set(MHD_INCLUDE_DIRS ${MHD_INCLUDE_DIR})
set(MHD_LIBRARIES ${MHD_LIBRARY})
# debug library on windows
# same naming convention as in QT (appending debug library with d)
# boost is using the same "hack" as us with "optimized" and "debug"
# official MHD project actually uses _d suffix
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
find_library(
MHD_LIBRARY_DEBUG
NAMES microhttpd_d microhttpd-10_d libmicrohttpd_d libmicrohttpd-dll_d
DOC "mhd debug library"
)
set(MHD_LIBRARIES optimized ${MHD_LIBRARIES} debug ${MHD_LIBRARY_DEBUG})
# prepare dlls
string(REPLACE ".lib" ".dll" MHD_DLL ${MHD_LIBRARY})
string(REPLACE "/lib/" "/bin/" MHD_DLL ${MHD_DLL})
string(REPLACE ".lib" ".dll" MHD_DLL_DEBUG ${MHD_LIBRARY_DEBUG})
string(REPLACE "/lib/" "/bin/" MHD_DLL_DEBUG ${MHD_DLL_DEBUG})
set(MHD_DLLS optimized ${MHD_DLL} debug ${MHD_DLL_DEBUG})
endif()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(mhd DEFAULT_MSG
MHD_INCLUDE_DIR MHD_LIBRARY)
mark_as_advanced(MHD_INCLUDE_DIR MHD_LIBRARY)

49
cmake/FindMiniupnpc.cmake

@ -1,49 +0,0 @@
# Find miniupnpc
#
# Find the miniupnpc includes and library
#
# if you nee to add a custom library search path, do it via via CMAKE_PREFIX_PATH
#
# This module defines
# MINIUPNPC_INCLUDE_DIRS, where to find header, etc.
# MINIUPNPC_LIBRARIES, the libraries needed to use gmp.
# MINIUPNPC_FOUND, If false, do not try to use gmp.
# only look in default directories
find_path(
MINIUPNPC_INCLUDE_DIR
NAMES miniupnpc/miniupnpc.h
DOC "miniupnpc include dir"
)
find_library(
MINIUPNPC_LIBRARY
NAMES miniupnpc
DOC "miniupnpc library"
)
set(MINIUPNPC_INCLUDE_DIRS ${MINIUPNPC_INCLUDE_DIR})
set(MINIUPNPC_LIBRARIES ${MINIUPNPC_LIBRARY})
# debug library on windows
# same naming convention as in QT (appending debug library with d)
# boost is using the same "hack" as us with "optimized" and "debug"
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
find_library(
MINIUPNPC_LIBRARY_DEBUG
NAMES miniupnpcd
DOC "miniupnpc debug library"
)
set(MINIUPNPC_LIBRARIES "iphlpapi" optimized ${MINIUPNPC_LIBRARIES} debug ${MINIUPNPC_LIBRARY_DEBUG})
endif()
# handle the QUIETLY and REQUIRED arguments and set MINIUPNPC_FOUND to TRUE
# if all listed variables are TRUE, hide their existence from configuration view
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(miniupnpc DEFAULT_MSG
MINIUPNPC_INCLUDE_DIR MINIUPNPC_LIBRARY)
mark_as_advanced (MINIUPNPC_INCLUDE_DIR MINIUPNPC_LIBRARY)

34
cmake/FindReadline.cmake

@ -1,34 +0,0 @@
# Find readline
#
# Find the readline includes and library
#
# if you nee to add a custom library search path, do it via via CMAKE_PREFIX_PATH
#
# This module defines
# READLINE_INCLUDE_DIRS, where to find header, etc.
# READLINE_LIBRARIES, the libraries needed to use readline.
# READLINE_FOUND, If false, do not try to use readline.
# only look in default directories
find_path(
READLINE_INCLUDE_DIR
NAMES readline/readline.h
DOC "readling include dir"
)
find_library(
READLINE_LIBRARY
NAMES readline
DOC "readline library"
)
set(READLINE_INCLUDE_DIRS ${READLINE_INCLUDE_DIR})
set(READLINE_LIBRARIES ${READLINE_LIBRARY})
# handle the QUIETLY and REQUIRED arguments and set READLINE_FOUND to TRUE
# if all listed variables are TRUE, hide their existence from configuration view
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(readline DEFAULT_MSG
READLINE_INCLUDE_DIR READLINE_LIBRARY)
mark_as_advanced (READLINE_INCLUDE_DIR READLINE_LIBRARY)

322
cmake/FindWindowsSDK.cmake

@ -1,322 +0,0 @@
# - Find the Windows SDK aka Platform SDK
#
# Relevant Wikipedia article: http://en.wikipedia.org/wiki/Microsoft_Windows_SDK
#
# Variables:
# WINDOWSSDK_FOUND - if any version of the windows or platform SDK was found that is usable with the current version of visual studio
# WINDOWSSDK_LATEST_DIR
# WINDOWSSDK_LATEST_NAME
# WINDOWSSDK_FOUND_PREFERENCE - if we found an entry indicating a "preferred" SDK listed for this visual studio version
# WINDOWSSDK_PREFERRED_DIR
# WINDOWSSDK_PREFERRED_NAME
#
# WINDOWSSDK_DIRS - contains no duplicates, ordered most recent first.
# WINDOWSSDK_PREFERRED_FIRST_DIRS - contains no duplicates, ordered with preferred first, followed by the rest in descending recency
#
# Functions:
# windowssdk_name_lookup(<directory> <output variable>) - Find the name corresponding with the SDK directory you pass in, or
# NOTFOUND if not recognized. Your directory must be one of WINDOWSSDK_DIRS for this to work.
#
# get_windowssdk_from_component(<file or dir> <output variable>) - Given a library or include dir,
# find the Windows SDK root dir corresponding to it, or NOTFOUND if unrecognized.
#
# get_windowssdk_library_dirs(<directory> <output variable>) - Find the architecture-appropriate
# library directories corresponding to the SDK directory you pass in (or NOTFOUND if none)
#
# get_windowssdk_include_dirs(<directory> <output variable>) - Find the
# include directories corresponding to the SDK directory you pass in (or NOTFOUND if none)
#
# Requires these CMake modules:
# FindPackageHandleStandardArgs (known included with CMake >=2.6.2)
#
# Original Author:
# 2012 Ryan Pavlik <rpavlik@iastate.edu> <abiryan@ryand.net>
# http://academic.cleardefinition.com
# Iowa State University HCI Graduate Program/VRAC
#
# Copyright Iowa State University 2012.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
set(_preferred_sdk_dirs)
set(_win_sdk_dirs)
set(_win_sdk_versanddirs)
if(MSVC_VERSION GREATER 1310) # Newer than VS .NET/VS Toolkit 2003
# Environment variable for SDK dir
if(EXISTS "$ENV{WindowsSDKDir}" AND (NOT "$ENV{WindowsSDKDir}" STREQUAL ""))
message(STATUS "Got $ENV{WindowsSDKDir} - Windows/Platform SDK directories: ${_win_sdk_dirs}")
list(APPEND _preferred_sdk_dirs "$ENV{WindowsSDKDir}")
endif()
if(MSVC_VERSION LESS 1600)
# Per-user current Windows SDK for VS2005/2008
get_filename_component(_sdkdir
"[HKEY_CURRENT_USER\\Software\\Microsoft\\Microsoft SDKs\\Windows;CurrentInstallFolder]"
ABSOLUTE)
if(EXISTS "${_sdkdir}")
list(APPEND _preferred_sdk_dirs "${_sdkdir}")
endif()
# System-wide current Windows SDK for VS2005/2008
get_filename_component(_sdkdir
"[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows;CurrentInstallFolder]"
ABSOLUTE)
if(EXISTS "${_sdkdir}")
list(APPEND _preferred_sdk_dirs "${_sdkdir}")
endif()
endif()
if(MSVC_VERSION LESS 1700)
# VC 10 and older has broad target support
set(_winsdk_vistaonly)
else()
# VC 11 by default targets Vista and later only, so we can add a few more SDKs that (might?) only work on vista+
if("${CMAKE_VS_PLATFORM_TOOLSET}" MATCHES "_xp")
# This is the XP-compatible v110 toolset
elseif("${CMAKE_VS_PLATFORM_TOOLSET}" STREQUAL "v100")
# This is the VS2010 toolset
else()
if(NOT WINDOWSSDK_FOUND AND NOT WindowsSDK_FIND_QUIETLY)
message(STATUS "FindWindowsSDK: Detected Visual Studio 2012 or newer, not using the _xp toolset variant: including SDK versions that drop XP support in search!")
endif()
# These versions have no XP (and possibly Vista pre-SP1) support
set(_winsdk_vistaonly)
if(NOT MSVC_VERSION LESS 1800)
list(APPEND _winsdk_vistaonly
# Windows Software Development Kit (SDK) for Windows 8.1
# http://msdn.microsoft.com/en-gb/windows/desktop/bg162891
v8.1)
endif()
list(APPEND _winsdk_vistaonly
# Included in Visual Studio 2012
v8.0A
# Microsoft Windows SDK for Windows 8 and .NET Framework 4.5
# This is the first version to also include the DirectX SDK
# http://msdn.microsoft.com/en-US/windows/desktop/hh852363.aspx
v8.0
# Microsoft Windows SDK for Windows 7 and .NET Framework 4
# http://www.microsoft.com/downloads/en/details.aspx?FamilyID=6b6c21d2-2006-4afa-9702-529fa782d63b
v7.1
)
endif()
endif()
foreach(_winsdkver
${_winsdk_vistaonly}
# Included in Visual Studio 2013
# Includes the v120_xp toolset
v8.1A
# Included with VS 2012 Update 1 or later
# Introduces v110_xp toolset
v7.1A
# Included with VS 2010
v7.0A
# Windows SDK for Windows 7 and .NET Framework 3.5 SP1
# Works with VC9
#http://www.microsoft.com/en-us/download/details.aspx?id=18950
v7.0
# Two versions call themselves "v6.1":
# Older:
# Windows Vista Update & .NET 3.0 SDK
# http://www.microsoft.com/en-us/download/details.aspx?id=14477
# Newer:
# Windows Server 2008 & .NET 3.5 SDK
# may have broken VS9SP1? they recommend v7.0 instead, or a KB...
# http://www.microsoft.com/en-us/download/details.aspx?id=24826
v6.1
# Included in VS 2008
v6.0A
# Microsoft Windows Software Development Kit for Windows Vista and .NET Framework 3.0 Runtime Components
# http://blogs.msdn.com/b/stanley/archive/2006/11/08/microsoft-windows-software-development-kit-for-windows-vista-and-net-framework-3-0-runtime-components.aspx
v6.0)
get_filename_component(_sdkdir
"[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\${_winsdkver};InstallationFolder]"
ABSOLUTE)
if(EXISTS "${_sdkdir}")
list(APPEND _win_sdk_dirs "${_sdkdir}")
list(APPEND
_win_sdk_versanddirs
"Windows SDK ${_winsdkver}"
"${_sdkdir}")
endif()
endforeach()
endif()
if(MSVC_VERSION GREATER 1200)
foreach(_platformsdkinfo
"D2FF9F89-8AA2-4373-8A31-C838BF4DBBE1_Microsoft Platform SDK for Windows Server 2003 R2"
"8F9E5EF3-A9A5-491B-A889-C58EFFECE8B3_Microsoft Platform SDK for Windows Server 2003 SP1")
string(SUBSTRING "${_platformsdkinfo}" 0 36 _platformsdkguid)
string(SUBSTRING "${_platformsdkinfo}" 37 -1 _platformsdkname)
foreach(HIVE HKEY_LOCAL_MACHINE HKEY_CURRENT_USER)
get_filename_component(_sdkdir
"[${HIVE}\\SOFTWARE\\Microsoft\\MicrosoftSDK\\InstalledSDKs\\${_platformsdkguid};Install Dir]"
ABSOLUTE)
if(EXISTS "${_sdkdir}")
list(APPEND _win_sdk_dirs "${_sdkdir}")
list(APPEND _win_sdk_versanddirs "${_platformsdkname}" "${_sdkdir}")
endif()
endforeach()
endforeach()
endif()
set(_win_sdk_versanddirs
"${_win_sdk_versanddirs}"
CACHE
INTERNAL
"mapping between windows sdk version locations and names"
FORCE)
function(windowssdk_name_lookup _dir _outvar)
list(FIND _win_sdk_versanddirs "${_dir}" _diridx)
math(EXPR _nameidx "${_diridx} - 1")
if(${_nameidx} GREATER -1)
list(GET _win_sdk_versanddirs ${_nameidx} _sdkname)
else()
set(_sdkname "NOTFOUND")
endif()
set(${_outvar} "${_sdkname}" PARENT_SCOPE)
endfunction()
if(_win_sdk_dirs)
# Remove duplicates
list(REMOVE_DUPLICATES _win_sdk_dirs)
list(GET _win_sdk_dirs 0 WINDOWSSDK_LATEST_DIR)
windowssdk_name_lookup("${WINDOWSSDK_LATEST_DIR}"
WINDOWSSDK_LATEST_NAME)
set(WINDOWSSDK_DIRS ${_win_sdk_dirs})
endif()
if(_preferred_sdk_dirs)
list(GET _preferred_sdk_dirs 0 WINDOWSSDK_PREFERRED_DIR)
windowssdk_name_lookup("${WINDOWSSDK_LATEST_DIR}"
WINDOWSSDK_PREFERRED_NAME)
set(WINDOWSSDK_PREFERRED_FIRST_DIRS
${_preferred_sdk_dirs}
${_win_sdk_dirs})
list(REMOVE_DUPLICATES WINDOWSSDK_PREFERRED_FIRST_DIRS)
set(WINDOWSSDK_FOUND_PREFERENCE ON)
# In case a preferred dir was found that isn't found otherwise
#set(WINDOWSSDK_DIRS ${WINDOWSSDK_DIRS} ${WINDOWSSDK_PREFERRED_FIRST_DIRS})
#list(REMOVE_DUPLICATES WINDOWSSDK_DIRS)
else()
set(WINDOWSSDK_PREFERRED_DIR "${WINDOWSSDK_LATEST_DIR}")
set(WINDOWSSDK_PREFERRED_NAME "${WINDOWSSDK_LATEST_NAME}")
set(WINDOWSSDK_PREFERRED_FIRST_DIRS ${WINDOWSSDK_DIRS})
set(WINDOWSSDK_FOUND_PREFERENCE OFF)
endif()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(WindowsSDK
"No compatible version of the Windows SDK or Platform SDK found."
WINDOWSSDK_DIRS)
if(WINDOWSSDK_FOUND)
if(NOT _winsdk_remembered_dirs STREQUAL WINDOWSSDK_DIRS)
set(_winsdk_remembered_dirs
"${WINDOWSSDK_DIRS}"
CACHE
INTERNAL
""
FORCE)
if(NOT WindowsSDK_FIND_QUIETLY)
foreach(_sdkdir ${WINDOWSSDK_DIRS})
windowssdk_name_lookup("${_sdkdir}" _sdkname)
message(STATUS " - Found ${_sdkname} at ${_sdkdir}")
endforeach()
endif()
endif()
# Internal: Architecture-appropriate library directory names.
if("${CMAKE_VS_PLATFORM_NAME}" STREQUAL "ARM")
set(_winsdk_archbare /arm) # what the architecture used to be called in oldest SDKs
set(_winsdk_arch arm) # what the architecture used to be called
set(_winsdk_arch8 arm) # what the WDK for Win8+ calls this architecture
else()
if(CMAKE_SIZEOF_VOID_P MATCHES "8")
set(_winsdk_archbare /x64) # what the architecture used to be called in oldest SDKs
set(_winsdk_arch amd64) # what the architecture used to be called
set(_winsdk_arch8 x64) # what the WDK for Win8+ calls this architecture
else()
set(_winsdk_archbare ) # what the architecture used to be called in oldest SDKs
set(_winsdk_arch i386) # what the architecture used to be called
set(_winsdk_arch8 x86) # what the WDK for Win8+ calls this architecture
endif()
endif()
function(get_windowssdk_from_component _component _var)
get_filename_component(_component "${_component}" ABSOLUTE)
file(TO_CMAKE_PATH "${_component}" _component)
foreach(_sdkdir ${WINDOWSSDK_DIRS})
get_filename_component(_sdkdir "${_sdkdir}" ABSOLUTE)
string(LENGTH "${_sdkdir}" _sdklen)
file(RELATIVE_PATH _rel "${_sdkdir}" "${_component}")
# If we don't have any "parent directory" items...
if(NOT "${_rel}" MATCHES "[.][.]")
set(${_var} "${_sdkdir}" PARENT_SCOPE)
return()
endif()
endforeach()
# Fail.
set(${_var} "NOTFOUND" PARENT_SCOPE)
endfunction()
function(get_windowssdk_library_dirs _winsdk_dir _var)
set(_result)
foreach(_suffix
"lib${_winsdk_archbare}" # SDKs like 7.1A
"lib/w2k/${_winsdk_arch}" # Win2k min requirement
"lib/wxp/${_winsdk_arch}" # WinXP min requirement
"lib/wnet/${_winsdk_arch}" # Win Server 2003 min requirement
"lib/wlh/${_winsdk_arch}" # Win Vista ("Long Horn") min requirement
"lib/wlh/um/${_winsdk_arch8}" # Win Vista ("Long Horn") min requirement
"lib/win7/${_winsdk_arch}" # Win 7 min requirement
"lib/win7/um/${_winsdk_arch8}" # Win 7 min requirement
"lib/win8/um/${_winsdk_arch8}" # Win 8 min requirement
"lib/win8/km/${_winsdk_arch8}" # Win 8 min requirement
"lib/winv6.3/km/${_winsdk_arch8}" # Win 8.1 min requirement
"lib/winv6.3/um/${_winsdk_arch8}" # Win 8.1 min requirement
)
# Check to see if a library actually exists here.
file(GLOB _libs "${_winsdk_dir}/${_suffix}/*.lib")
if(_libs)
list(APPEND _result "${_winsdk_dir}/${_suffix}")
endif()
endforeach()
if(NOT _result)
set(_result NOTFOUND)
endif()
set(${_var} ${_result} PARENT_SCOPE)
endfunction()
function(get_windowssdk_include_dirs _winsdk_dir _var)
set(_result)
foreach(_suffix
"Include"
"Include/shared"
"Include/um"
"Include/winrt"
"Include/km"
"Include/wdf"
)
# Check to see if a header file actually exists here.
file(GLOB _headers "${_winsdk_dir}/${_suffix}/*.h")
if(_headers)
list(APPEND _result "${_winsdk_dir}/${_suffix}")
endif()
endforeach()
if(NOT _result)
set(_result NOTFOUND)
endif()
set(${_var} ${_result} PARENT_SCOPE)
endfunction()
endif()

69
cmake/Findv8.cmake

@ -1,69 +0,0 @@
# Find v8
#
# Find the v8 includes and library
#
# if you nee to add a custom library search path, do it via via CMAKE_PREFIX_PATH
#
# This module defines
# V8_INCLUDE_DIRS, where to find header, etc.
# V8_LIBRARIES, the libraries needed to use v8.
# V8_FOUND, If false, do not try to use v8.
# only look in default directories
find_path(
V8_INCLUDE_DIR
NAMES v8.h
DOC "v8 include dir"
)
find_library(
V8_LIBRARY
NAMES v8
DOC "v8 library"
)
set(V8_INCLUDE_DIRS ${V8_INCLUDE_DIR})
set(V8_LIBRARIES ${V8_LIBRARY})
# debug library on windows
# same naming convention as in qt (appending debug library with d)
# boost is using the same "hack" as us with "optimized" and "debug"
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
find_library(
V8_LIBRARY
NAMES v8_base
DOC "v8 base library"
)
find_library(
V8_NO_SNAPSHOT_LIBRARY
NAMES v8_nosnapshot
DOC "v8 nosnapshot library"
)
set(V8_LIBRARIES ${V8_LIBRARY} ${V8_NO_SNAPSHOT_LIBRARY})
find_library(
V8_LIBRARY_DEBUG
NAMES v8_based
DOC "v8 base library"
)
find_library(
V8_NO_SNAPSHOT_LIBRARY_DEBUG
NAMES v8_nosnapshotd
DOC "v8 nosnapshot library"
)
set(V8_LIBRARIES "ws2_32" "winmm" optimized ${V8_LIBRARIES} debug ${V8_LIBRARY_DEBUG} ${V8_NO_SNAPSHOT_LIBRARY_DEBUG})
endif()
# handle the QUIETLY and REQUIRED arguments and set V8_FOUND to TRUE
# if all listed variables are TRUE, hide their existence from configuration view
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(v8 DEFAULT_MSG
V8_INCLUDE_DIR V8_LIBRARY)
mark_as_advanced (V8_INCLUDE_DIR V8_LIBRARY)

6
cmake/scripts/buildinfo.cmake

@ -9,12 +9,6 @@
# example usage:
# cmake -DETH_SOURCE_DIR=. -DETH_DST_DIR=build -DETH_BUILD_TYPE=Debug -DETH_BUILD_PLATFORM=mac -P scripts/buildinfo.cmake
if (ETH_FATDB)
set(ETH_FATDB 1)
else()
set(ETH_FATDB 0)
endif()
if (NOT ETH_BUILD_TYPE)
set(ETH_BUILD_TYPE "unknown")
endif()

1
ethminer/CMakeLists.txt

@ -42,7 +42,6 @@ target_link_libraries(${EXECUTABLE} ethstratum)
endif()
if (DEFINED WIN32 AND NOT DEFINED CMAKE_COMPILER_IS_MINGW)
eth_copy_dlls("${EXECUTABLE}" MHD_DLLS)
eth_copy_dlls("${EXECUTABLE}" OpenCL_DLLS)
endif()

96
ethminer/MinerAux.h

@ -33,8 +33,6 @@
#include <boost/algorithm/string/trim_all.hpp>
#include <boost/optional.hpp>
#include <libdevcore/FileSystem.h>
#include <libdevcore/StructuredLogger.h>
#include <libethcore/Exceptions.h>
#include <libdevcore/SHA3.h>
#include <libdevcore/CommonJS.h>
@ -43,22 +41,17 @@
#include <libethcore/EthashGPUMiner.h>
#include <libethcore/EthashCPUMiner.h>
#include <libethcore/Farm.h>
#if ETH_ETHASHCL || !ETH_TRUE
#if ETH_ETHASHCL
#include <libethash-cl/ethash_cl_miner.h>
#endif
#if ETH_ETHASHCUDA || !ETH_TRUE
#if ETH_ETHASHCUDA
#include <libethash-cuda/ethash_cuda_miner.h>
#endif
#if ETH_JSONRPC || !ETH_TRUE
#include <jsonrpccpp/server/connectors/httpserver.h>
#include <jsonrpccpp/client/connectors/httpclient.h>
#endif
#include "BuildInfo.h"
#if ETH_JSONRPC || !ETH_TRUE
#include "PhoneHome.h"
#include "FarmClient.h"
#endif
#if ETH_STRATUM || !ETH_TRUE
#if ETH_STRATUM
#include <libstratum/EthStratumClient.h>
#include <libstratum/EthStratumClientV2.h>
#endif
@ -69,25 +62,6 @@ using namespace boost::algorithm;
#undef RETURN
bool isTrue(std::string const& _m)
{
return _m == "on" || _m == "yes" || _m == "true" || _m == "1";
}
bool isFalse(std::string const& _m)
{
return _m == "off" || _m == "no" || _m == "false" || _m == "0";
}
inline std::string credits()
{
std::ostringstream out;
out
<< "Ethereum (++) " << dev::Version << endl
<< " Code by Gav Wood et al, (c) 2013, 2014, 2015." << endl;
return out.str();
}
class BadArgument: public Exception {};
struct MiningChannel: public LogChannel
{
@ -163,7 +137,7 @@ public:
cerr << "Bad " << arg << " option: " << argv[i] << endl;
BOOST_THROW_EXCEPTION(BadArgument());
}
#if ETH_STRATUM || !ETH_TRUE
#if ETH_STRATUM
else if ((arg == "-S" || arg == "--stratum") && i + 1 < argc)
{
mode = OperationMode::Stratum;
@ -261,7 +235,7 @@ public:
}
#endif
#if ETH_ETHASHCL || !ETH_TRUE
#if ETH_ETHASHCL
else if (arg == "--opencl-platform" && i + 1 < argc)
try {
m_openclPlatform = stol(argv[++i]);
@ -286,7 +260,7 @@ public:
}
}
#endif
#if ETH_ETHASHCL || ETH_ETHASHCUDA || !ETH_TRUE
#if ETH_ETHASHCL || ETH_ETHASHCUDA
else if ((arg == "--cl-global-work" || arg == "--cuda-grid-size") && i + 1 < argc)
try {
m_globalWorkSizeMultiplier = stol(argv[++i]);
@ -310,11 +284,11 @@ public:
else if ((arg == "--cl-extragpu-mem" || arg == "--cuda-extragpu-mem") && i + 1 < argc)
m_extraGPUMemory = 1000000 * stol(argv[++i]);
#endif
#if ETH_ETHASHCL || !ETH_TRUE
#if ETH_ETHASHCL
else if (arg == "--allow-opencl-cpu")
m_clAllowCPU = true;
#endif
#if ETH_ETHASHCUDA || !ETH_TRUE
#if ETH_ETHASHCUDA
else if (arg == "--cuda-devices")
{
while (m_cudaDeviceCount < 16 && i + 1 < argc)
@ -482,11 +456,11 @@ public:
{
if (m_shouldListDevices)
{
#if ETH_ETHASHCL || !ETH_TRUE
#if ETH_ETHASHCL
if (m_minerType == MinerType::CL || m_minerType == MinerType::Mixed)
EthashGPUMiner::listDevices();
#endif
#if ETH_ETHASHCUDA || !ETH_TRUE
#if ETH_ETHASHCUDA
if (m_minerType == MinerType::CUDA || m_minerType == MinerType::Mixed)
EthashCUDAMiner::listDevices();
#endif
@ -502,7 +476,7 @@ public:
}
else if (m_minerType == MinerType::CL || m_minerType == MinerType::Mixed)
{
#if ETH_ETHASHCL || !ETH_TRUE
#if ETH_ETHASHCL
if (m_openclDeviceCount > 0)
{
EthashGPUMiner::setDevices(m_openclDevices, m_openclDeviceCount);
@ -529,7 +503,7 @@ public:
}
else if (m_minerType == MinerType::CUDA || m_minerType == MinerType::Mixed)
{
#if ETH_ETHASHCUDA || !ETH_TRUE
#if ETH_ETHASHCUDA
if (m_cudaDeviceCount > 0)
{
EthashCUDAMiner::setDevices(m_cudaDevices, m_cudaDeviceCount);
@ -554,12 +528,12 @@ public:
#endif
}
if (mode == OperationMode::Benchmark)
doBenchmark(m_minerType, m_phoneHome, m_benchmarkWarmup, m_benchmarkTrial, m_benchmarkTrials);
doBenchmark(m_minerType, m_benchmarkWarmup, m_benchmarkTrial, m_benchmarkTrials);
else if (mode == OperationMode::Farm)
doFarm(m_minerType, m_activeFarmURL, m_farmRecheckPeriod);
else if (mode == OperationMode::Simulation)
doSimulation(m_minerType);
#if ETH_STRATUM || !ETH_TRUE
#if ETH_STRATUM
else if (mode == OperationMode::Stratum)
doStratum();
#endif
@ -568,13 +542,11 @@ public:
static void streamHelp(ostream& _out)
{
_out
#if ETH_JSONRPC || !ETH_TRUE
<< "Work farming mode:" << endl
<< " -F,--farm <url> Put into mining farm mode with the work server at URL (default: http://127.0.0.1:8545)" << endl
<< " -FF,-FO, --farm-failover, --stratum-failover <url> Failover getwork/stratum URL (default: disabled)" << endl
<< " --farm-retries <n> Number of retries until switch to failover (default: 3)" << endl
#endif
#if ETH_STRATUM || !ETH_TRUE
#if ETH_STRATUM
<< " -S, --stratum <host:port> Put into stratum mode with the stratum server at host:port" << endl
<< " -FS, --failover-stratum <host:port> Failover stratum server at host:port" << endl
<< " -O, --userpass <username.workername:password> Stratum login credentials" << endl
@ -587,7 +559,7 @@ public:
<< " 2: EthereumStratum/1.0.0: nicehash" << endl
<< " -SE, --stratum-email <s> Email address used in eth-proxy (optional)" << endl
#endif
#if ETH_JSONRPC || ETH_STRATUM || !ETH_TRUE
#if ETH_STRATUM
<< " --farm-recheck <n> Leave n ms between checks for changed work (default: 500). When using stratum, use a high value (i.e. 2000) to get more stable hashrate output" << endl
#endif
<< endl
@ -612,12 +584,12 @@ public:
<< " parallel - load DAG on all GPUs at the same time (default)" << endl
<< " sequential - load DAG on GPUs one after another. Use this when the miner crashes during DAG generation" << endl
<< " single <n> - generate DAG on device n, then copy to other devices" << endl
#if ETH_ETHASHCL || !ETH_TRUE
#if ETH_ETHASHCL
<< " --cl-extragpu-mem Set the memory (in MB) you believe your GPU requires for stuff other than mining. default: 0" << endl
<< " --cl-local-work Set the OpenCL local work size. Default is " << toString(ethash_cl_miner::c_defaultLocalWorkSize) << endl
<< " --cl-global-work Set the OpenCL global work size as a multiple of the local work size. Default is " << toString(ethash_cl_miner::c_defaultGlobalWorkSizeMultiplier) << " * " << toString(ethash_cl_miner::c_defaultLocalWorkSize) << endl
#endif
#if ETH_ETHASHCUDA || !ETH_TRUE
#if ETH_ETHASHCUDA
<< " --cuda-extragpu-mem Set the memory (in MB) you believe your GPU requires for stuff other than mining. Windows rendering e.t.c.." << endl
<< " --cuda-block-size Set the CUDA block work size. Default is " << toString(ethash_cuda_miner::c_defaultBlockSize) << endl
<< " --cuda-grid-size Set the CUDA grid size. Default is " << toString(ethash_cuda_miner::c_defaultGridSize) << endl
@ -645,7 +617,7 @@ private:
void doBenchmark(MinerType _m, bool _phoneHome, unsigned _warmupDuration = 15, unsigned _trialDuration = 3, unsigned _trials = 5)
void doBenchmark(MinerType _m, unsigned _warmupDuration = 15, unsigned _trialDuration = 3, unsigned _trials = 5)
{
Ethash::BlockHeader genesis;
genesis.setNumber(m_benchmarkBlock);
@ -709,23 +681,6 @@ private:
cout << "min/mean/max: " << results.begin()->second.rate() << "/" << (mean / _trials) << "/" << results.rbegin()->second.rate() << " H/s" << endl;
cout << "inner mean: " << innerMean << " H/s" << endl;
(void)_phoneHome;
#if ETH_JSONRPC || !ETH_TRUE
if (_phoneHome)
{
cout << "Phoning home to find world ranking..." << endl;
jsonrpc::HttpClient client("http://gav.ethdev.com:3000");
PhoneHome rpc(client);
try
{
unsigned ranking = rpc.report_benchmark(platformInfo, innerMean);
cout << "Ranked: " << ranking << " of all benchmarks." << endl;
}
catch (...)
{
}
}
#endif
exit(0);
}
@ -828,7 +783,6 @@ private:
(void)_m;
(void)_remote;
(void)_recheckPeriod;
#if ETH_JSONRPC || !ETH_TRUE
jsonrpc::HttpClient client(m_farmURL);
:: FarmClient rpc(client);
jsonrpc::HttpClient failoverClient(m_farmFailOverURL);
@ -966,11 +920,10 @@ private:
}
}
#endif
exit(0);
}
#if ETH_STRATUM || !ETH_TRUE
#if ETH_STRATUM
void doStratum()
{
map<string, GenericFarm<EthashProofOfWork>::SealerDescriptor> sealers;
@ -1077,15 +1030,15 @@ private:
unsigned m_miningThreads = UINT_MAX;
bool m_shouldListDevices = false;
bool m_clAllowCPU = false;
#if ETH_ETHASHCL || !ETH_TRUE
#if ETH_ETHASHCL
unsigned m_openclDeviceCount = 0;
unsigned m_openclDevices[16];
#if !ETH_ETHASHCUDA || !ETH_TRUE
#if !ETH_ETHASHCUDA
unsigned m_globalWorkSizeMultiplier = ethash_cl_miner::c_defaultGlobalWorkSizeMultiplier;
unsigned m_localWorkSize = ethash_cl_miner::c_defaultLocalWorkSize;
#endif
#endif
#if ETH_ETHASHCUDA || !ETH_TRUE
#if ETH_ETHASHCUDA
unsigned m_globalWorkSizeMultiplier = ethash_cuda_miner::c_defaultGridSize;
unsigned m_localWorkSize = ethash_cuda_miner::c_defaultBlockSize;
unsigned m_cudaDeviceCount = 0;
@ -1098,7 +1051,6 @@ private:
unsigned m_dagLoadMode = 0; // parallel
unsigned m_dagCreateDevice = 0;
/// Benchmarking params
bool m_phoneHome = false;
unsigned m_benchmarkWarmup = 15;
unsigned m_benchmarkTrial = 3;
unsigned m_benchmarkTrials = 5;
@ -1116,7 +1068,7 @@ private:
bool m_farmRecheckSet = false;
int m_worktimeout = 180;
#if ETH_STRATUM || !ETH_TRUE
#if ETH_STRATUM
int m_stratumClientVersion = 1;
int m_stratumProtocol = STRATUM_PROTOCOL_STRATUM;
string m_user;

28
ethminer/PhoneHome.h

@ -1,28 +0,0 @@
/**
* This file is generated by jsonrpcstub, DO NOT CHANGE IT MANUALLY!
*/
#ifndef JSONRPC_CPP_STUB_PHONEHOME_H_
#define JSONRPC_CPP_STUB_PHONEHOME_H_
#include <jsonrpccpp/client.h>
class PhoneHome : public jsonrpc::Client
{
public:
PhoneHome(jsonrpc::IClientConnector &conn, jsonrpc::clientVersion_t type = jsonrpc::JSONRPC_CLIENT_V2) : jsonrpc::Client(conn, type) {}
int report_benchmark(const std::string& param1, int param2) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p.append(param1);
p.append(param2);
Json::Value result = this->CallMethod("report_benchmark",p);
if (result.isInt())
return result.asInt();
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
};
#endif //JSONRPC_CPP_STUB_PHONEHOME_H_

5
ethminer/main.cpp

@ -29,13 +29,8 @@
#endif
#include <thread>
#include <chrono>
#include <fstream>
#include <iostream>
#include <signal.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim_all.hpp>
#include <libdevcore/FileSystem.h>
#include "MinerAux.h"
using namespace std;
using namespace dev;

3
ethminer/phonehome.json

@ -1,3 +0,0 @@
[
{ "name": "report_benchmark", "params": [ "", 0 ], "order": [], "returns": 0 }
]

1
libdevcore/Assertions.h

@ -25,7 +25,6 @@
#pragma once
#include "Exceptions.h"
#include "debugbreak.h"
namespace dev
{

146
libdevcore/Base64.cpp

@ -1,146 +0,0 @@
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
/// Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
/// Originally by René Nyffenegger, modified by some other guy and then devified by Gav Wood.
#include "Base64.h"
using namespace std;
using namespace dev;
static inline bool is_base64(byte c)
{
return (isalnum(c) || (c == '+') || (c == '/'));
}
static inline byte find_base64_char_index(byte c)
{
if ('A' <= c && c <= 'Z') return c - 'A';
else if ('a' <= c && c <= 'z') return c - 'a' + 1 + find_base64_char_index('Z');
else if ('0' <= c && c <= '9') return c - '0' + 1 + find_base64_char_index('z');
else if (c == '+') return 1 + find_base64_char_index('9');
else if (c == '/') return 1 + find_base64_char_index('+');
else return 1 + find_base64_char_index('/');
}
string dev::toBase64(bytesConstRef _in)
{
static const char base64_chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
string ret;
int i = 0;
int j = 0;
byte char_array_3[3];
byte char_array_4[4];
auto buf = _in.data();
auto bufLen = _in.size();
while (bufLen--)
{
char_array_3[i++] = *(buf++);
if (i == 3)
{
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (i = 0; i < 4; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for (j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; j < i + 1; j++)
ret += base64_chars[char_array_4[j]];
while (i++ < 3)
ret += '=';
}
return ret;
}
bytes dev::fromBase64(string const& encoded_string)
{
auto in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
byte char_array_3[3];
byte char_array_4[4];
bytes ret;
while (in_len-- && encoded_string[in_] != '=' && is_base64(encoded_string[in_]))
{
char_array_4[i++] = encoded_string[in_]; in_++;
if (i == 4)
{
for (i = 0; i < 4; i++)
char_array_4[i] = find_base64_char_index(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret.push_back(char_array_3[i]);
i = 0;
}
}
if (i)
{
for (j = i; j < 4; j++)
char_array_4[j] = 0;
for (j = 0; j < 4; j++)
char_array_4[j] = find_base64_char_index(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; j < i - 1; j++)
ret.push_back(char_array_3[j]);
}
return ret;
}

62
libdevcore/Base64.h

@ -1,62 +0,0 @@
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
/// Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
/// Originally by René Nyffenegger.
/// DEVified by Gav Wood.
#pragma once
#include <string>
#include "Common.h"
#include "FixedHash.h"
namespace dev
{
std::string toBase64(bytesConstRef _in);
bytes fromBase64(std::string const& _in);
template <size_t N> inline std::string toBase36(FixedHash<N> const& _h)
{
static char const* c_alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
typename FixedHash<N>::Arith a = _h;
std::string ret;
for (; a > 0; a /= 36)
{
unsigned r = (unsigned)(a - a / 36 * 36); // boost's % is broken
ret = c_alphabet[r] + ret;
}
return ret;
}
template <size_t N> inline FixedHash<N> fromBase36(std::string const& _h)
{
typename FixedHash<N>::Arith ret = 0;
for (char c: _h)
ret = ret * 36 + (c < 'A' ? c - '0' : (c - 'A' + 10));
return ret;
}
}

21
libdevcore/CMakeLists.txt

@ -1,29 +1,22 @@
cmake_policy(SET CMP0015 NEW)
set(CMAKE_AUTOMOC OFF)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB")
aux_source_directory(. SRC_LIST)
aux_source_directory(. SOURCES)
include_directories(BEFORE ${JSONCPP_INCLUDE_DIRS})
include_directories(BEFORE ..)
include_directories(${Boost_INCLUDE_DIRS})
include_directories(${DB_INCLUDE_DIRS})
set(EXECUTABLE devcore)
file(GLOB HEADERS "*.h")
add_library(${EXECUTABLE} ${SRC_LIST} ${HEADERS})
add_library(devcore ${SOURCES} ${HEADERS})
target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${Boost_RANDOM_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARIES})
if (JSONRPC)
target_link_libraries(${EXECUTABLE} ${JSONCPP_LIBRARIES})
endif()
target_link_libraries(${EXECUTABLE} ${DB_LIBRARIES})
target_link_libraries(devcore ${Boost_THREAD_LIBRARIES})
target_link_libraries(devcore ${Boost_RANDOM_LIBRARIES})
target_link_libraries(devcore ${Boost_FILESYSTEM_LIBRARIES})
target_link_libraries(devcore ${Boost_SYSTEM_LIBRARIES})
target_link_libraries(devcore ${JSONCPP_LIBRARIES})
# transitive dependencies for windows executables
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")

26
libdevcore/Common.cpp

@ -33,30 +33,4 @@ char const* Version = ETH_PROJECT_VERSION;
const u256 UndefinedU256 = ~(u256)0;
void InvariantChecker::checkInvariants(HasInvariants const* _this, char const* _fn, char const* _file, int _line, bool _pre)
{
if (!_this->invariants())
{
cwarn << (_pre ? "Pre" : "Post") << "invariant failed in" << _fn << "at" << _file << ":" << _line;
::boost::exception_detail::throw_exception_(FailedInvariant(), _fn, _file, _line);
}
}
struct TimerChannel: public LogChannel { static const char* name(); static const int verbosity = 0; };
#ifdef _WIN32
const char* TimerChannel::name() { return EthRed " ! "; }
#else
const char* TimerChannel::name() { return EthRed ""; }
#endif
TimerHelper::~TimerHelper()
{
auto e = std::chrono::high_resolution_clock::now() - m_t;
if (!m_ms || e > chrono::milliseconds(m_ms))
{
clog(TimerChannel) << m_id << chrono::duration_cast<chrono::milliseconds>(e).count() << "ms";
}
}
}

150
libdevcore/Common.h

@ -149,161 +149,23 @@ using u256HashMap = std::unordered_map<u256, u256>;
// String types.
using strings = std::vector<std::string>;
// Fixed-length string types.
using string32 = std::array<char, 32>;
static const string32 ZeroString32 = {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }};
// Null/Invalid values for convenience.
static const u256 Invalid256 = ~(u256)0;
static const bytes NullBytes;
static const std::map<u256, u256> EmptyMapU256U256;
/// Interprets @a _u as a two's complement signed number and returns the resulting s256.
inline s256 u2s(u256 _u)
{
static const bigint c_end = bigint(1) << 256;
if (boost::multiprecision::bit_test(_u, 255))
return s256(-(c_end - _u));
else
return s256(_u);
}
/// @returns the two's complement signed representation of the signed number _u.
inline u256 s2u(s256 _u)
{
static const bigint c_end = bigint(1) << 256;
if (_u >= 0)
return u256(_u);
else
return u256(c_end + _u);
}
/// @returns the smallest n >= 0 such that (1 << n) >= _x
inline unsigned int toLog2(u256 _x)
/// Converts arbitrary value to string representation using std::stringstream.
template <class _T>
std::string toString(_T const& _t)
{
unsigned ret;
for (ret = 0; _x >>= 1; ++ret) {}
return ret;
std::ostringstream o;
o << _t;
return o.str();
}
/// @returns the absolute distance between _a and _b.
template <class N>
inline N diff(N const& _a, N const& _b)
{
return std::max(_a, _b) - std::min(_a, _b);
}
/// RAII utility class whose destructor calls a given function.
class ScopeGuard
{
public:
ScopeGuard(std::function<void(void)> _f): m_f(_f) {}
~ScopeGuard() { m_f(); }
private:
std::function<void(void)> m_f;
};
/// Inheritable for classes that have invariants.
class HasInvariants
{
public:
/// Reimplement to specify the invariants.
virtual bool invariants() const = 0;
};
/// RAII checker for invariant assertions.
class InvariantChecker
{
public:
InvariantChecker(HasInvariants* _this, char const* _fn, char const* _file, int _line): m_this(_this), m_function(_fn), m_file(_file), m_line(_line) { checkInvariants(_this, _fn , _file, _line, true); }
~InvariantChecker() { checkInvariants(m_this, m_function, m_file, m_line, false); }
/// Check invariants are met, throw if not.
static void checkInvariants(HasInvariants const* _this, char const* _fn, char const* _file, int line, bool _pre);
private:
HasInvariants const* m_this;
char const* m_function;
char const* m_file;
int m_line;
};
/// Scope guard for invariant check in a class derived from HasInvariants.
#if ETH_DEBUG
#define DEV_INVARIANT_CHECK ::dev::InvariantChecker __dev_invariantCheck(this, BOOST_CURRENT_FUNCTION, __FILE__, __LINE__)
#define DEV_INVARIANT_CHECK_HERE ::dev::InvariantChecker::checkInvariants(this, BOOST_CURRENT_FUNCTION, __FILE__, __LINE__, true)
#else
#define DEV_INVARIANT_CHECK (void)0;
#define DEV_INVARIANT_CHECK_HERE (void)0;
#endif
/// Simple scope-based timer helper.
class TimerHelper
{
public:
TimerHelper(std::string const& _id, unsigned _msReportWhenGreater = 0): m_t(std::chrono::high_resolution_clock::now()), m_id(_id), m_ms(_msReportWhenGreater) {}
~TimerHelper();
private:
std::chrono::high_resolution_clock::time_point m_t;
std::string m_id;
unsigned m_ms;
};
class Timer
{
public:
Timer() { restart(); }
std::chrono::high_resolution_clock::duration duration() const { return std::chrono::high_resolution_clock::now() - m_t; }
double elapsed() const { return std::chrono::duration_cast<std::chrono::microseconds>(duration()).count() / 1000000.0; }
void restart() { m_t = std::chrono::high_resolution_clock::now(); }
private:
std::chrono::high_resolution_clock::time_point m_t;
};
#define DEV_TIMED(S) for (::std::pair<::dev::TimerHelper, bool> __eth_t(S, true); __eth_t.second; __eth_t.second = false)
#define DEV_TIMED_SCOPE(S) ::dev::TimerHelper __eth_t(S)
#if WIN32
#define DEV_TIMED_FUNCTION DEV_TIMED_SCOPE(__FUNCSIG__)
#else
#define DEV_TIMED_FUNCTION DEV_TIMED_SCOPE(__PRETTY_FUNCTION__)
#endif
#define DEV_TIMED_ABOVE(S, MS) for (::std::pair<::dev::TimerHelper, bool> __eth_t(::dev::TimerHelper(S, MS), true); __eth_t.second; __eth_t.second = false)
#define DEV_TIMED_SCOPE_ABOVE(S, MS) ::dev::TimerHelper __eth_t(S, MS)
#if WIN32
#define DEV_TIMED_FUNCTION_ABOVE(MS) DEV_TIMED_SCOPE_ABOVE(__FUNCSIG__, MS)
#else
#define DEV_TIMED_FUNCTION_ABOVE(MS) DEV_TIMED_SCOPE_ABOVE(__PRETTY_FUNCTION__, MS)
#endif
#ifdef _MSC_VER
// TODO.
#define DEV_UNUSED
#else
#define DEV_UNUSED __attribute__((unused))
#endif
enum class WithExisting: int
{
Trust = 0,
Verify,
Rescue,
Kill
};
}
namespace std
{
inline dev::WithExisting max(dev::WithExisting _a, dev::WithExisting _b)
{
return static_cast<dev::WithExisting>(max(static_cast<int>(_a), static_cast<int>(_b)));
}
template <> struct hash<dev::u256>
{
size_t operator()(dev::u256 const& _a) const

32
libdevcore/CommonData.cpp

@ -21,7 +21,6 @@
#include "CommonData.h"
#include <random>
#include <boost/random/uniform_int_distribution.hpp>
#include "Exceptions.h"
#include "Log.h"
@ -56,17 +55,6 @@ std::string dev::escaped(std::string const& _s, bool _all)
return ret;
}
std::string dev::randomWord()
{
static std::mt19937_64 s_eng(0);
std::string ret(boost::random::uniform_int_distribution<int>(1, 5)(s_eng), ' ');
char const n[] = "qwertyuiop";//asdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
boost::random::uniform_int_distribution<int> d(0, sizeof(n) - 2);
for (char& c: ret)
c = n[d(s_eng)];
return ret;
}
int dev::fromHex(char _i, WhenError _throw)
{
if (_i >= '0' && _i <= '9')
@ -110,23 +98,3 @@ bytes dev::fromHex(std::string const& _s, WhenError _throw)
}
return ret;
}
bytes dev::asNibbles(bytesConstRef const& _s)
{
std::vector<uint8_t> ret;
ret.reserve(_s.size() * 2);
for (auto i: _s)
{
ret.push_back(i / 16);
ret.push_back(i % 16);
}
return ret;
}
std::string dev::toString(string32 const& _s)
{
std::string ret;
for (unsigned i = 0; i < 32 && _s[i]; ++i)
ret.push_back(_s[i]);
return ret;
}

224
libdevcore/CommonData.h

@ -76,23 +76,12 @@ inline std::string asString(bytes const& _b)
return std::string((char const*)_b.data(), (char const*)(_b.data() + _b.size()));
}
/// Converts byte array ref to a string containing the same (binary) data. Unless
/// the byte array happens to contain ASCII data, this won't be printable.
inline std::string asString(bytesConstRef _b)
{
return std::string((char const*)_b.data(), (char const*)(_b.data() + _b.size()));
}
/// Converts a string to a byte array containing the string's (byte) data.
inline bytes asBytes(std::string const& _b)
{
return bytes((byte const*)_b.data(), (byte const*)(_b.data() + _b.size()));
}
/// Converts a string into the big-endian base-16 stream of integers (NOT ASCII).
/// @example asNibbles("A")[0] == 4 && asNibbles("A")[1] == 1
bytes asNibbles(bytesConstRef const& _s);
// Big-endian to/from host endian conversion functions.
@ -125,8 +114,6 @@ inline T fromBigEndian(_In const& _bytes)
}
/// Convenience functions for toBigEndian
inline std::string toBigEndianString(u256 _val) { std::string ret(32, '\0'); toBigEndian(_val, ret); return ret; }
inline std::string toBigEndianString(u160 _val) { std::string ret(20, '\0'); toBigEndian(_val, ret); return ret; }
inline bytes toBigEndian(u256 _val) { bytes ret(32); toBigEndian(_val, ret); return ret; }
inline bytes toBigEndian(u160 _val) { bytes ret(20); toBigEndian(_val, ret); return ret; }
@ -142,23 +129,6 @@ inline bytes toCompactBigEndian(T _val, unsigned _min = 0)
toBigEndian(_val, ret);
return ret;
}
inline bytes toCompactBigEndian(byte _val, unsigned _min = 0)
{
return (_min || _val) ? bytes{ _val } : bytes{};
}
/// Convenience function for toBigEndian.
/// @returns a string just big enough to represent @a _val.
template <class T>
inline std::string toCompactBigEndianString(T _val, unsigned _min = 0)
{
static_assert(std::is_same<bigint, T>::value || !std::numeric_limits<T>::is_signed, "only unsigned types or bigint supported"); //bigint does not carry sign bit on shift
int i = 0;
for (T v = _val; v; ++i, v >>= 8) {}
std::string ret(std::max<unsigned>(_min, i), '\0');
toBigEndian(_val, ret);
return ret;
}
/// Convenience function for conversion of a u256 to hex
inline std::string toHex(u256 val, HexPrefix prefix = HexPrefix::DontAdd)
@ -167,35 +137,12 @@ inline std::string toHex(u256 val, HexPrefix prefix = HexPrefix::DontAdd)
return (prefix == HexPrefix::Add) ? "0x" + str : str;
}
inline std::string toCompactHex(u256 val, HexPrefix prefix = HexPrefix::DontAdd, unsigned _min = 0)
{
std::string str = toHex(toCompactBigEndian(val, _min));
return (prefix == HexPrefix::Add) ? "0x" + str : str;
}
// Algorithms for string and string-like collections.
/// Escapes a string into the C-string representation.
/// @p _all if true will escape all characters, not just the unprintable ones.
std::string escaped(std::string const& _s, bool _all = true);
/// Determines the length of the common prefix of the two collections given.
/// @returns the number of elements both @a _t and @a _u share, in order, at the beginning.
/// @example commonPrefix("Hello world!", "Hello, world!") == 5
template <class T, class _U>
unsigned commonPrefix(T const& _t, _U const& _u)
{
unsigned s = std::min<unsigned>(_t.size(), _u.size());
for (unsigned i = 0;; ++i)
if (i == s || _t[i] != _u[i])
return i;
return s;
}
/// Creates a random, printable, word.
std::string randomWord();
// General datatype convenience functions.
/// Determine bytes required to encode the given integer value. @returns 0 if @a _i is zero.
@ -208,175 +155,4 @@ inline unsigned bytesRequired(T _i)
return i;
}
/// Trims a given number of elements from the front of a collection.
/// Only works for POD element types.
template <class T>
void trimFront(T& _t, unsigned _elements)
{
static_assert(std::is_pod<typename T::value_type>::value, "");
memmove(_t.data(), _t.data() + _elements, (_t.size() - _elements) * sizeof(_t[0]));
_t.resize(_t.size() - _elements);
}
/// Pushes an element on to the front of a collection.
/// Only works for POD element types.
template <class T, class _U>
void pushFront(T& _t, _U _e)
{
static_assert(std::is_pod<typename T::value_type>::value, "");
_t.push_back(_e);
memmove(_t.data() + 1, _t.data(), (_t.size() - 1) * sizeof(_e));
_t[0] = _e;
}
/// Concatenate two vectors of elements of POD types.
template <class T>
inline std::vector<T>& operator+=(std::vector<typename std::enable_if<std::is_pod<T>::value, T>::type>& _a, std::vector<T> const& _b)
{
auto s = _a.size();
_a.resize(_a.size() + _b.size());
memcpy(_a.data() + s, _b.data(), _b.size() * sizeof(T));
return _a;
}
/// Concatenate two vectors of elements.
template <class T>
inline std::vector<T>& operator+=(std::vector<typename std::enable_if<!std::is_pod<T>::value, T>::type>& _a, std::vector<T> const& _b)
{
_a.reserve(_a.size() + _b.size());
for (auto& i: _b)
_a.push_back(i);
return _a;
}
/// Insert the contents of a container into a set
template <class T, class U> std::set<T>& operator+=(std::set<T>& _a, U const& _b)
{
for (auto const& i: _b)
_a.insert(i);
return _a;
}
/// Insert the contents of a container into an unordered_set
template <class T, class U> std::unordered_set<T>& operator+=(std::unordered_set<T>& _a, U const& _b)
{
for (auto const& i: _b)
_a.insert(i);
return _a;
}
/// Concatenate the contents of a container onto a vector
template <class T, class U> std::vector<T>& operator+=(std::vector<T>& _a, U const& _b)
{
for (auto const& i: _b)
_a.push_back(i);
return _a;
}
/// Insert the contents of a container into a set
template <class T, class U> std::set<T> operator+(std::set<T> _a, U const& _b)
{
return _a += _b;
}
/// Insert the contents of a container into an unordered_set
template <class T, class U> std::unordered_set<T> operator+(std::unordered_set<T> _a, U const& _b)
{
return _a += _b;
}
/// Concatenate the contents of a container onto a vector
template <class T, class U> std::vector<T> operator+(std::vector<T> _a, U const& _b)
{
return _a += _b;
}
/// Concatenate two vectors of elements.
template <class T>
inline std::vector<T> operator+(std::vector<T> const& _a, std::vector<T> const& _b)
{
std::vector<T> ret(_a);
return ret += _b;
}
/// Merge two sets of elements.
template <class T>
inline std::set<T>& operator+=(std::set<T>& _a, std::set<T> const& _b)
{
for (auto& i: _b)
_a.insert(i);
return _a;
}
/// Merge two sets of elements.
template <class T>
inline std::set<T> operator+(std::set<T> const& _a, std::set<T> const& _b)
{
std::set<T> ret(_a);
return ret += _b;
}
template <class A, class B>
std::unordered_map<A, B>& operator+=(std::unordered_map<A, B>& _x, std::unordered_map<A, B> const& _y)
{
for (auto const& i: _y)
_x.insert(i);
return _x;
}
template <class A, class B>
std::unordered_map<A, B> operator+(std::unordered_map<A, B> const& _x, std::unordered_map<A, B> const& _y)
{
std::unordered_map<A, B> ret(_x);
return ret += _y;
}
/// Make normal string from fixed-length string.
std::string toString(string32 const& _s);
template<class T, class U>
std::vector<T> keysOf(std::map<T, U> const& _m)
{
std::vector<T> ret;
for (auto const& i: _m)
ret.push_back(i.first);
return ret;
}
template<class T, class U>
std::vector<T> keysOf(std::unordered_map<T, U> const& _m)
{
std::vector<T> ret;
for (auto const& i: _m)
ret.push_back(i.first);
return ret;
}
template<class T, class U>
std::vector<U> valuesOf(std::map<T, U> const& _m)
{
std::vector<U> ret;
ret.reserve(_m.size());
for (auto const& i: _m)
ret.push_back(i.second);
return ret;
}
template<class T, class U>
std::vector<U> valuesOf(std::unordered_map<T, U> const& _m)
{
std::vector<U> ret;
ret.reserve(_m.size());
for (auto const& i: _m)
ret.push_back(i.second);
return ret;
}
template <class T, class V>
bool contains(T const& _t, V const& _v)
{
return std::end(_t) != std::find(std::begin(_t), std::end(_t), _v);
}
}

182
libdevcore/CommonIO.cpp

@ -1,182 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file CommonIO.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "CommonIO.h"
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <stdio.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <termios.h>
#endif
#include <boost/filesystem.hpp>
#include "Exceptions.h"
using namespace std;
using namespace dev;
string dev::memDump(bytes const& _bytes, unsigned _width, bool _html)
{
stringstream ret;
if (_html)
ret << "<pre style=\"font-family: Monospace,Lucida Console,Courier,Courier New,sans-serif; font-size: small\">";
for (unsigned i = 0; i < _bytes.size(); i += _width)
{
ret << hex << setw(4) << setfill('0') << i << " ";
for (unsigned j = i; j < i + _width; ++j)
if (j < _bytes.size())
if (_bytes[j] >= 32 && _bytes[j] < 127)
if ((char)_bytes[j] == '<' && _html)
ret << "&lt;";
else if ((char)_bytes[j] == '&' && _html)
ret << "&amp;";
else
ret << (char)_bytes[j];
else
ret << '?';
else
ret << ' ';
ret << " ";
for (unsigned j = i; j < i + _width && j < _bytes.size(); ++j)
ret << setfill('0') << setw(2) << hex << (unsigned)_bytes[j] << " ";
ret << "\n";
}
if (_html)
ret << "</pre>";
return ret.str();
}
template <typename _T>
inline _T contentsGeneric(std::string const& _file)
{
_T ret;
size_t const c_elementSize = sizeof(typename _T::value_type);
std::ifstream is(_file, std::ifstream::binary);
if (!is)
return ret;
// get length of file:
is.seekg(0, is.end);
streamoff length = is.tellg();
if (length == 0)
return ret; // do not read empty file (MSVC does not like it)
is.seekg(0, is.beg);
ret.resize((length + c_elementSize - 1) / c_elementSize);
is.read(const_cast<char*>(reinterpret_cast<char const*>(ret.data())), length);
return ret;
}
bytes dev::contents(string const& _file)
{
return contentsGeneric<bytes>(_file);
}
bytesSec dev::contentsSec(string const& _file)
{
bytes b = contentsGeneric<bytes>(_file);
bytesSec ret(b);
bytesRef(&b).cleanse();
return ret;
}
string dev::contentsString(string const& _file)
{
return contentsGeneric<string>(_file);
}
void dev::writeFile(std::string const& _file, bytesConstRef _data, bool _writeDeleteRename)
{
namespace fs = boost::filesystem;
if (_writeDeleteRename)
{
fs::path tempPath = fs::unique_path(_file + "-%%%%%%");
writeFile(tempPath.string(), _data, false);
// will delete _file if it exists
fs::rename(tempPath, _file);
}
else
{
// create directory if not existent
fs::path p(_file);
if (!fs::exists(p.parent_path()))
{
fs::create_directories(p.parent_path());
DEV_IGNORE_EXCEPTIONS(fs::permissions(p.parent_path(), fs::owner_all));
}
ofstream s(_file, ios::trunc | ios::binary);
s.write(reinterpret_cast<char const*>(_data.data()), _data.size());
if (!s)
BOOST_THROW_EXCEPTION(FileError() << errinfo_comment("Could not write to file: " + _file));
DEV_IGNORE_EXCEPTIONS(fs::permissions(_file, fs::owner_read|fs::owner_write));
}
}
std::string dev::getPassword(std::string const& _prompt)
{
#if WIN32
cout << _prompt << flush;
// Get current Console input flags
HANDLE hStdin;
DWORD fdwSaveOldMode;
if ((hStdin = GetStdHandle(STD_INPUT_HANDLE)) == INVALID_HANDLE_VALUE)
BOOST_THROW_EXCEPTION(ExternalFunctionFailure("GetStdHandle"));
if (!GetConsoleMode(hStdin, &fdwSaveOldMode))
BOOST_THROW_EXCEPTION(ExternalFunctionFailure("GetConsoleMode"));
// Set console flags to no echo
if (!SetConsoleMode(hStdin, fdwSaveOldMode & (~ENABLE_ECHO_INPUT)))
BOOST_THROW_EXCEPTION(ExternalFunctionFailure("SetConsoleMode"));
// Read the string
std::string ret;
std::getline(cin, ret);
// Restore old input mode
if (!SetConsoleMode(hStdin, fdwSaveOldMode))
BOOST_THROW_EXCEPTION(ExternalFunctionFailure("SetConsoleMode"));
return ret;
#else
struct termios oflags;
struct termios nflags;
char password[256];
// disable echo in the terminal
tcgetattr(fileno(stdin), &oflags);
nflags = oflags;
nflags.c_lflag &= ~ECHO;
nflags.c_lflag |= ECHONL;
if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0)
BOOST_THROW_EXCEPTION(ExternalFunctionFailure("tcsetattr"));
printf("%s", _prompt.c_str());
if (!fgets(password, sizeof(password), stdin))
BOOST_THROW_EXCEPTION(ExternalFunctionFailure("fgets"));
password[strlen(password) - 1] = 0;
// restore terminal
if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0)
BOOST_THROW_EXCEPTION(ExternalFunctionFailure("tcsetattr"));
return password;
#endif
}

270
libdevcore/CommonIO.h

@ -1,270 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file CommonIO.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*
* File & stream I/O routines.
*/
#pragma once
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <list>
#include <memory>
#include <vector>
#include <array>
#include <sstream>
#include <string>
#include <iostream>
#include <chrono>
#include "Common.h"
#include "Base64.h"
namespace dev
{
/// Requests the user to enter a password on the console.
std::string getPassword(std::string const& _prompt);
/// Retrieve and returns the contents of the given file.
/// If the file doesn't exist or isn't readable, returns an empty container / bytes.
bytes contents(std::string const& _file);
/// Secure variation.
bytesSec contentsSec(std::string const& _file);
/// Retrieve and returns the contents of the given file as a std::string.
/// If the file doesn't exist or isn't readable, returns an empty container / bytes.
std::string contentsString(std::string const& _file);
/// Retrieve and returns the allocated contents of the given file; if @_dest is given, don't allocate, use it directly.
/// If the file doesn't exist or isn't readable, returns bytesRef(). Don't forget to delete [] the returned value's data when finished.
bytesRef contentsNew(std::string const& _file, bytesRef _dest = bytesRef());
/// Write the given binary data into the given file, replacing the file if it pre-exists.
/// Throws exception on error.
/// @param _writeDeleteRename useful not to lose any data: If set, first writes to another file in
/// the same directory and then moves that file.
void writeFile(std::string const& _file, bytesConstRef _data, bool _writeDeleteRename = false);
/// Write the given binary data into the given file, replacing the file if it pre-exists.
inline void writeFile(std::string const& _file, bytes const& _data, bool _writeDeleteRename = false) { writeFile(_file, bytesConstRef(&_data), _writeDeleteRename); }
inline void writeFile(std::string const& _file, std::string const& _data, bool _writeDeleteRename = false) { writeFile(_file, bytesConstRef(_data), _writeDeleteRename); }
/// Nicely renders the given bytes to a string, optionally as HTML.
/// @a _bytes: bytes array to be rendered as string. @a _width of a bytes line.
std::string memDump(bytes const& _bytes, unsigned _width = 8, bool _html = false);
// Stream I/O functions.
// Provides templated stream I/O for all STL collections so they can be shifted on to any iostream-like interface.
template <class S, class T> struct StreamOut { static S& bypass(S& _out, T const& _t) { _out << _t; return _out; } };
template <class S> struct StreamOut<S, uint8_t> { static S& bypass(S& _out, uint8_t const& _t) { _out << (int)_t; return _out; } };
template <class T> inline std::ostream& operator<<(std::ostream& _out, std::vector<T> const& _e);
template <class T, std::size_t Z> inline std::ostream& operator<<(std::ostream& _out, std::array<T, Z> const& _e);
template <class T, class U> inline std::ostream& operator<<(std::ostream& _out, std::pair<T, U> const& _e);
template <class T> inline std::ostream& operator<<(std::ostream& _out, std::list<T> const& _e);
template <class T1, class T2, class T3> inline std::ostream& operator<<(std::ostream& _out, std::tuple<T1, T2, T3> const& _e);
template <class T, class U> inline std::ostream& operator<<(std::ostream& _out, std::map<T, U> const& _e);
template <class T, class U> inline std::ostream& operator<<(std::ostream& _out, std::unordered_map<T, U> const& _e);
template <class T, class U> inline std::ostream& operator<<(std::ostream& _out, std::set<T, U> const& _e);
template <class T, class U> inline std::ostream& operator<<(std::ostream& _out, std::unordered_set<T, U> const& _e);
template <class T, class U> inline std::ostream& operator<<(std::ostream& _out, std::multimap<T, U> const& _e);
template <class _S, class _T> _S& operator<<(_S& _out, std::shared_ptr<_T> const& _p);
#ifdef _WIN32
template <class T> inline std::string toString(std::chrono::time_point<T> const& _e, std::string _format = "%Y-%m-%d %H:%M:%S")
#else
template <class T> inline std::string toString(std::chrono::time_point<T> const& _e, std::string _format = "%F %T")
#endif
{
unsigned long milliSecondsSinceEpoch = std::chrono::duration_cast<std::chrono::milliseconds>(_e.time_since_epoch()).count();
auto const durationSinceEpoch = std::chrono::milliseconds(milliSecondsSinceEpoch);
std::chrono::time_point<std::chrono::system_clock> const tpAfterDuration(durationSinceEpoch);
tm timeValue;
auto time = std::chrono::system_clock::to_time_t(tpAfterDuration);
#ifdef _WIN32
gmtime_s(&timeValue, &time);
#else
gmtime_r(&time, &timeValue);
#endif
unsigned const millisRemainder = milliSecondsSinceEpoch % 1000;
char buffer[1024];
if (strftime(buffer, sizeof(buffer), _format.c_str(), &timeValue))
return std::string(buffer) + "." + (millisRemainder < 1 ? "000" : millisRemainder < 10 ? "00" : millisRemainder < 100 ? "0" : "") + std::to_string(millisRemainder) + "Z";
return std::string();
}
template <class S, class T>
inline S& streamout(S& _out, std::vector<T> const& _e)
{
_out << "[";
if (!_e.empty())
{
StreamOut<S, T>::bypass(_out, _e.front());
for (auto i = ++_e.begin(); i != _e.end(); ++i)
StreamOut<S, T>::bypass(_out << ",", *i);
}
_out << "]";
return _out;
}
template <class T> inline std::ostream& operator<<(std::ostream& _out, std::vector<T> const& _e) { streamout(_out, _e); return _out; }
template <class S, class T, std::size_t Z>
inline S& streamout(S& _out, std::array<T, Z> const& _e)
{
_out << "[";
if (!_e.empty())
{
StreamOut<S, T>::bypass(_out, _e.front());
auto i = _e.begin();
for (++i; i != _e.end(); ++i)
StreamOut<S, T>::bypass(_out << ",", *i);
}
_out << "]";
return _out;
}
template <class T, std::size_t Z> inline std::ostream& operator<<(std::ostream& _out, std::array<T, Z> const& _e) { streamout(_out, _e); return _out; }
template <class S, class T>
inline S& streamout(S& _out, std::list<T> const& _e)
{
_out << "[";
if (!_e.empty())
{
_out << _e.front();
for (auto i = ++_e.begin(); i != _e.end(); ++i)
_out << "," << *i;
}
_out << "]";
return _out;
}
template <class T> inline std::ostream& operator<<(std::ostream& _out, std::list<T> const& _e) { streamout(_out, _e); return _out; }
template <class S, class T, class U>
inline S& streamout(S& _out, std::pair<T, U> const& _e)
{
_out << "(" << _e.first << "," << _e.second << ")";
return _out;
}
template <class T, class U> inline std::ostream& operator<<(std::ostream& _out, std::pair<T, U> const& _e) { streamout(_out, _e); return _out; }
template <class S, class T1, class T2, class T3>
inline S& streamout(S& _out, std::tuple<T1, T2, T3> const& _t)
{
_out << "(" << std::get<0>(_t) << "," << std::get<1>(_t) << "," << std::get<2>(_t) << ")";
return _out;
}
template <class T1, class T2, class T3> inline std::ostream& operator<<(std::ostream& _out, std::tuple<T1, T2, T3> const& _e) { streamout(_out, _e); return _out; }
template <class S, class T, class U>
S& streamout(S& _out, std::map<T, U> const& _v)
{
if (_v.empty())
return _out << "{}";
int i = 0;
for (auto p: _v)
_out << (!(i++) ? "{ " : "; ") << p.first << " => " << p.second;
return _out << " }";
}
template <class T, class U> inline std::ostream& operator<<(std::ostream& _out, std::map<T, U> const& _e) { streamout(_out, _e); return _out; }
template <class S, class T, class U>
S& streamout(S& _out, std::unordered_map<T, U> const& _v)
{
if (_v.empty())
return _out << "{}";
int i = 0;
for (auto p: _v)
_out << (!(i++) ? "{ " : "; ") << p.first << " => " << p.second;
return _out << " }";
}
template <class T, class U> inline std::ostream& operator<<(std::ostream& _out, std::unordered_map<T, U> const& _e) { streamout(_out, _e); return _out; }
template <class S, class T>
S& streamout(S& _out, std::set<T> const& _v)
{
if (_v.empty())
return _out << "{}";
int i = 0;
for (auto p: _v)
_out << (!(i++) ? "{ " : ", ") << p;
return _out << " }";
}
template <class T> inline std::ostream& operator<<(std::ostream& _out, std::set<T> const& _e) { streamout(_out, _e); return _out; }
template <class S, class T>
S& streamout(S& _out, std::unordered_set<T> const& _v)
{
if (_v.empty())
return _out << "{}";
int i = 0;
for (auto p: _v)
_out << (!(i++) ? "{ " : ", ") << p;
return _out << " }";
}
template <class T> inline std::ostream& operator<<(std::ostream& _out, std::unordered_set<T> const& _e) { streamout(_out, _e); return _out; }
template <class S, class T>
S& streamout(S& _out, std::multiset<T> const& _v)
{
if (_v.empty())
return _out << "{}";
int i = 0;
for (auto p: _v)
_out << (!(i++) ? "{ " : ", ") << p;
return _out << " }";
}
template <class T> inline std::ostream& operator<<(std::ostream& _out, std::multiset<T> const& _e) { streamout(_out, _e); return _out; }
template <class S, class T, class U>
S& streamout(S& _out, std::multimap<T, U> const& _v)
{
if (_v.empty())
return _out << "{}";
T l;
int i = 0;
for (auto p: _v)
if (!(i++))
_out << "{ " << (l = p.first) << " => " << p.second;
else if (l == p.first)
_out << ", " << p.second;
else
_out << "; " << (l = p.first) << " => " << p.second;
return _out << " }";
}
template <class T, class U> inline std::ostream& operator<<(std::ostream& _out, std::multimap<T, U> const& _e) { streamout(_out, _e); return _out; }
template <class _S, class _T> _S& operator<<(_S& _out, std::shared_ptr<_T> const& _p) { if (_p) _out << "@" << (*_p); else _out << "nullptr"; return _out; }
// Functions that use streaming stuff.
/// Converts arbitrary value to string representation using std::stringstream.
template <class _T>
std::string toString(_T const& _t)
{
std::ostringstream o;
o << _t;
return o.str();
}
}

1
libdevcore/CommonJS.h

@ -26,7 +26,6 @@
#include <string>
#include "FixedHash.h"
#include "CommonData.h"
#include "CommonIO.h"
namespace dev
{

52
libdevcore/Diff.h

@ -1,52 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Diff.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
namespace dev
{
enum class ExistDiff
{
Same,
New,
Dead
};
template <class T>
class Diff
{
public:
Diff() {}
Diff(T _from, T _to): m_from(_from), m_to(_to) {}
T const& from() const { return m_from; }
T const& to() const { return m_to; }
explicit operator bool() const { return m_from != m_to; }
private:
T m_from;
T m_to;
};
}

73
libdevcore/FileSystem.cpp

@ -1,73 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file FileSystem.cpp
* @authors
* Eric Lombrozo <elombrozo@gmail.com>
* Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "FileSystem.h"
#include "Common.h"
#include "Log.h"
#if defined(_WIN32)
#include <shlobj.h>
#else
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>
#include <unistd.h>
#endif
#include <boost/filesystem.hpp>
using namespace std;
using namespace dev;
std::string dev::getDataDir(std::string _prefix)
{
if (_prefix.empty())
_prefix = "ethereum";
#ifdef _WIN32
_prefix[0] = toupper(_prefix[0]);
char path[1024] = "";
if (SHGetSpecialFolderPathA(NULL, path, CSIDL_APPDATA, true))
return (boost::filesystem::path(path) / _prefix).string();
else
{
#ifndef _MSC_VER // todo?
cwarn << "getDataDir(): SHGetSpecialFolderPathA() failed.";
#endif
BOOST_THROW_EXCEPTION(std::runtime_error("getDataDir() - SHGetSpecialFolderPathA() failed."));
}
#else
boost::filesystem::path dataDirPath;
char const* homeDir = getenv("HOME");
if (!homeDir || strlen(homeDir) == 0)
{
struct passwd* pwd = getpwuid(getuid());
if (pwd)
homeDir = pwd->pw_dir;
}
if (!homeDir || strlen(homeDir) == 0)
dataDirPath = boost::filesystem::path("/");
else
dataDirPath = boost::filesystem::path(homeDir);
return (dataDirPath / ("." + _prefix)).string();
#endif
}

35
libdevcore/FileSystem.h

@ -1,35 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file FileSystem.h
* @authors
* Eric Lombrozo <elombrozo@gmail.com>
* Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
#include <string>
#include <libdevcore/CommonIO.h>
namespace dev
{
/// @returns the path for user data.
std::string getDataDir(std::string _prefix = "ethereum");
}

10
libdevcore/Guards.h

@ -145,15 +145,5 @@ private:
for (GenericGuardBool<Guard, Mutex> __eth_l(MUTEX); __eth_l.b; __eth_l.b = false)
#define DEV_READ_GUARDED(MUTEX) \
for (GenericGuardBool<ReadGuard, SharedMutex> __eth_l(MUTEX); __eth_l.b; __eth_l.b = false)
#define DEV_WRITE_GUARDED(MUTEX) \
for (GenericGuardBool<WriteGuard, SharedMutex> __eth_l(MUTEX); __eth_l.b; __eth_l.b = false)
#define DEV_RECURSIVE_GUARDED(MUTEX) \
for (GenericGuardBool<RecursiveGuard, RecursiveMutex> __eth_l(MUTEX); __eth_l.b; __eth_l.b = false)
#define DEV_UNGUARDED(MUTEX) \
for (GenericUnguardBool<Mutex> __eth_l(MUTEX); __eth_l.b; __eth_l.b = false)
#define DEV_READ_UNGUARDED(MUTEX) \
for (GenericUnguardSharedBool<SharedMutex> __eth_l(MUTEX); __eth_l.b; __eth_l.b = false)
#define DEV_WRITE_UNGUARDED(MUTEX) \
for (GenericUnguardBool<SharedMutex> __eth_l(MUTEX); __eth_l.b; __eth_l.b = false)
}

440
libdevcore/Hash.cpp

@ -1,440 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Hash.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "Hash.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "picosha2.h"
using namespace std;
using namespace dev;
namespace dev
{
h256 sha256(bytesConstRef _input)
{
h256 ret;
picosha2::hash256(_input.begin(), _input.end(), ret.data(), ret.data() + 32);
return ret;
}
namespace rmd160
{
/********************************************************************\
*
* FILE: rmd160.h
* FILE: rmd160.c
*
* CONTENTS: Header file for a sample C-implementation of the
* RIPEMD-160 hash-function.
* TARGET: any computer with an ANSI C compiler
*
* AUTHOR: Antoon Bosselaers, ESAT-COSIC
* DATE: 1 March 1996
* VERSION: 1.0
*
* Copyright (c) Katholieke Universiteit Leuven
* 1996, All Rights Reserved
*
\********************************************************************/
// Adapted into "header-only" format by Gav Wood.
/* macro definitions */
#define RMDsize 160
/* collect four bytes into one word: */
#define BYTES_TO_DWORD(strptr) \
(((uint32_t) *((strptr)+3) << 24) | \
((uint32_t) *((strptr)+2) << 16) | \
((uint32_t) *((strptr)+1) << 8) | \
((uint32_t) *(strptr)))
/* ROL(x, n) cyclically rotates x over n bits to the left */
/* x must be of an unsigned 32 bits type and 0 <= n < 32. */
#define ROL(x, n) (((x) << (n)) | ((x) >> (32-(n))))
/* the five basic functions F(), G() and H() */
#define F(x, y, z) ((x) ^ (y) ^ (z))
#define G(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define H(x, y, z) (((x) | ~(y)) ^ (z))
#define I(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define J(x, y, z) ((x) ^ ((y) | ~(z)))
/* the ten basic operations FF() through III() */
#define FF(a, b, c, d, e, x, s) {\
(a) += F((b), (c), (d)) + (x);\
(a) = ROL((a), (s)) + (e);\
(c) = ROL((c), 10);\
}
#define GG(a, b, c, d, e, x, s) {\
(a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
(a) = ROL((a), (s)) + (e);\
(c) = ROL((c), 10);\
}
#define HH(a, b, c, d, e, x, s) {\
(a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
(a) = ROL((a), (s)) + (e);\
(c) = ROL((c), 10);\
}
#define II(a, b, c, d, e, x, s) {\
(a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
(a) = ROL((a), (s)) + (e);\
(c) = ROL((c), 10);\
}
#define JJ(a, b, c, d, e, x, s) {\
(a) += J((b), (c), (d)) + (x) + 0xa953fd4eUL;\
(a) = ROL((a), (s)) + (e);\
(c) = ROL((c), 10);\
}
#define FFF(a, b, c, d, e, x, s) {\
(a) += F((b), (c), (d)) + (x);\
(a) = ROL((a), (s)) + (e);\
(c) = ROL((c), 10);\
}
#define GGG(a, b, c, d, e, x, s) {\
(a) += G((b), (c), (d)) + (x) + 0x7a6d76e9UL;\
(a) = ROL((a), (s)) + (e);\
(c) = ROL((c), 10);\
}
#define HHH(a, b, c, d, e, x, s) {\
(a) += H((b), (c), (d)) + (x) + 0x6d703ef3UL;\
(a) = ROL((a), (s)) + (e);\
(c) = ROL((c), 10);\
}
#define III(a, b, c, d, e, x, s) {\
(a) += I((b), (c), (d)) + (x) + 0x5c4dd124UL;\
(a) = ROL((a), (s)) + (e);\
(c) = ROL((c), 10);\
}
#define JJJ(a, b, c, d, e, x, s) {\
(a) += J((b), (c), (d)) + (x) + 0x50a28be6UL;\
(a) = ROL((a), (s)) + (e);\
(c) = ROL((c), 10);\
}
void MDinit(uint32_t *MDbuf)
{
MDbuf[0] = 0x67452301UL;
MDbuf[1] = 0xefcdab89UL;
MDbuf[2] = 0x98badcfeUL;
MDbuf[3] = 0x10325476UL;
MDbuf[4] = 0xc3d2e1f0UL;
return;
}
/********************************************************************/
void MDcompress(uint32_t *MDbuf, uint32_t *X)
{
uint32_t aa = MDbuf[0], bb = MDbuf[1], cc = MDbuf[2],
dd = MDbuf[3], ee = MDbuf[4];
uint32_t aaa = MDbuf[0], bbb = MDbuf[1], ccc = MDbuf[2],
ddd = MDbuf[3], eee = MDbuf[4];
/* round 1 */
FF(aa, bb, cc, dd, ee, X[ 0], 11);
FF(ee, aa, bb, cc, dd, X[ 1], 14);
FF(dd, ee, aa, bb, cc, X[ 2], 15);
FF(cc, dd, ee, aa, bb, X[ 3], 12);
FF(bb, cc, dd, ee, aa, X[ 4], 5);
FF(aa, bb, cc, dd, ee, X[ 5], 8);
FF(ee, aa, bb, cc, dd, X[ 6], 7);
FF(dd, ee, aa, bb, cc, X[ 7], 9);
FF(cc, dd, ee, aa, bb, X[ 8], 11);
FF(bb, cc, dd, ee, aa, X[ 9], 13);
FF(aa, bb, cc, dd, ee, X[10], 14);
FF(ee, aa, bb, cc, dd, X[11], 15);
FF(dd, ee, aa, bb, cc, X[12], 6);
FF(cc, dd, ee, aa, bb, X[13], 7);
FF(bb, cc, dd, ee, aa, X[14], 9);
FF(aa, bb, cc, dd, ee, X[15], 8);
/* round 2 */
GG(ee, aa, bb, cc, dd, X[ 7], 7);
GG(dd, ee, aa, bb, cc, X[ 4], 6);
GG(cc, dd, ee, aa, bb, X[13], 8);
GG(bb, cc, dd, ee, aa, X[ 1], 13);
GG(aa, bb, cc, dd, ee, X[10], 11);
GG(ee, aa, bb, cc, dd, X[ 6], 9);
GG(dd, ee, aa, bb, cc, X[15], 7);
GG(cc, dd, ee, aa, bb, X[ 3], 15);
GG(bb, cc, dd, ee, aa, X[12], 7);
GG(aa, bb, cc, dd, ee, X[ 0], 12);
GG(ee, aa, bb, cc, dd, X[ 9], 15);
GG(dd, ee, aa, bb, cc, X[ 5], 9);
GG(cc, dd, ee, aa, bb, X[ 2], 11);
GG(bb, cc, dd, ee, aa, X[14], 7);
GG(aa, bb, cc, dd, ee, X[11], 13);
GG(ee, aa, bb, cc, dd, X[ 8], 12);
/* round 3 */
HH(dd, ee, aa, bb, cc, X[ 3], 11);
HH(cc, dd, ee, aa, bb, X[10], 13);
HH(bb, cc, dd, ee, aa, X[14], 6);
HH(aa, bb, cc, dd, ee, X[ 4], 7);
HH(ee, aa, bb, cc, dd, X[ 9], 14);
HH(dd, ee, aa, bb, cc, X[15], 9);
HH(cc, dd, ee, aa, bb, X[ 8], 13);
HH(bb, cc, dd, ee, aa, X[ 1], 15);
HH(aa, bb, cc, dd, ee, X[ 2], 14);
HH(ee, aa, bb, cc, dd, X[ 7], 8);
HH(dd, ee, aa, bb, cc, X[ 0], 13);
HH(cc, dd, ee, aa, bb, X[ 6], 6);
HH(bb, cc, dd, ee, aa, X[13], 5);
HH(aa, bb, cc, dd, ee, X[11], 12);
HH(ee, aa, bb, cc, dd, X[ 5], 7);
HH(dd, ee, aa, bb, cc, X[12], 5);
/* round 4 */
II(cc, dd, ee, aa, bb, X[ 1], 11);
II(bb, cc, dd, ee, aa, X[ 9], 12);
II(aa, bb, cc, dd, ee, X[11], 14);
II(ee, aa, bb, cc, dd, X[10], 15);
II(dd, ee, aa, bb, cc, X[ 0], 14);
II(cc, dd, ee, aa, bb, X[ 8], 15);
II(bb, cc, dd, ee, aa, X[12], 9);
II(aa, bb, cc, dd, ee, X[ 4], 8);
II(ee, aa, bb, cc, dd, X[13], 9);
II(dd, ee, aa, bb, cc, X[ 3], 14);
II(cc, dd, ee, aa, bb, X[ 7], 5);
II(bb, cc, dd, ee, aa, X[15], 6);
II(aa, bb, cc, dd, ee, X[14], 8);
II(ee, aa, bb, cc, dd, X[ 5], 6);
II(dd, ee, aa, bb, cc, X[ 6], 5);
II(cc, dd, ee, aa, bb, X[ 2], 12);
/* round 5 */
JJ(bb, cc, dd, ee, aa, X[ 4], 9);
JJ(aa, bb, cc, dd, ee, X[ 0], 15);
JJ(ee, aa, bb, cc, dd, X[ 5], 5);
JJ(dd, ee, aa, bb, cc, X[ 9], 11);
JJ(cc, dd, ee, aa, bb, X[ 7], 6);
JJ(bb, cc, dd, ee, aa, X[12], 8);
JJ(aa, bb, cc, dd, ee, X[ 2], 13);
JJ(ee, aa, bb, cc, dd, X[10], 12);
JJ(dd, ee, aa, bb, cc, X[14], 5);
JJ(cc, dd, ee, aa, bb, X[ 1], 12);
JJ(bb, cc, dd, ee, aa, X[ 3], 13);
JJ(aa, bb, cc, dd, ee, X[ 8], 14);
JJ(ee, aa, bb, cc, dd, X[11], 11);
JJ(dd, ee, aa, bb, cc, X[ 6], 8);
JJ(cc, dd, ee, aa, bb, X[15], 5);
JJ(bb, cc, dd, ee, aa, X[13], 6);
/* parallel round 1 */
JJJ(aaa, bbb, ccc, ddd, eee, X[ 5], 8);
JJJ(eee, aaa, bbb, ccc, ddd, X[14], 9);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 7], 9);
JJJ(ccc, ddd, eee, aaa, bbb, X[ 0], 11);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 9], 13);
JJJ(aaa, bbb, ccc, ddd, eee, X[ 2], 15);
JJJ(eee, aaa, bbb, ccc, ddd, X[11], 15);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 4], 5);
JJJ(ccc, ddd, eee, aaa, bbb, X[13], 7);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 6], 7);
JJJ(aaa, bbb, ccc, ddd, eee, X[15], 8);
JJJ(eee, aaa, bbb, ccc, ddd, X[ 8], 11);
JJJ(ddd, eee, aaa, bbb, ccc, X[ 1], 14);
JJJ(ccc, ddd, eee, aaa, bbb, X[10], 14);
JJJ(bbb, ccc, ddd, eee, aaa, X[ 3], 12);
JJJ(aaa, bbb, ccc, ddd, eee, X[12], 6);
/* parallel round 2 */
III(eee, aaa, bbb, ccc, ddd, X[ 6], 9);
III(ddd, eee, aaa, bbb, ccc, X[11], 13);
III(ccc, ddd, eee, aaa, bbb, X[ 3], 15);
III(bbb, ccc, ddd, eee, aaa, X[ 7], 7);
III(aaa, bbb, ccc, ddd, eee, X[ 0], 12);
III(eee, aaa, bbb, ccc, ddd, X[13], 8);
III(ddd, eee, aaa, bbb, ccc, X[ 5], 9);
III(ccc, ddd, eee, aaa, bbb, X[10], 11);
III(bbb, ccc, ddd, eee, aaa, X[14], 7);
III(aaa, bbb, ccc, ddd, eee, X[15], 7);
III(eee, aaa, bbb, ccc, ddd, X[ 8], 12);
III(ddd, eee, aaa, bbb, ccc, X[12], 7);
III(ccc, ddd, eee, aaa, bbb, X[ 4], 6);
III(bbb, ccc, ddd, eee, aaa, X[ 9], 15);
III(aaa, bbb, ccc, ddd, eee, X[ 1], 13);
III(eee, aaa, bbb, ccc, ddd, X[ 2], 11);
/* parallel round 3 */
HHH(ddd, eee, aaa, bbb, ccc, X[15], 9);
HHH(ccc, ddd, eee, aaa, bbb, X[ 5], 7);
HHH(bbb, ccc, ddd, eee, aaa, X[ 1], 15);
HHH(aaa, bbb, ccc, ddd, eee, X[ 3], 11);
HHH(eee, aaa, bbb, ccc, ddd, X[ 7], 8);
HHH(ddd, eee, aaa, bbb, ccc, X[14], 6);
HHH(ccc, ddd, eee, aaa, bbb, X[ 6], 6);
HHH(bbb, ccc, ddd, eee, aaa, X[ 9], 14);
HHH(aaa, bbb, ccc, ddd, eee, X[11], 12);
HHH(eee, aaa, bbb, ccc, ddd, X[ 8], 13);
HHH(ddd, eee, aaa, bbb, ccc, X[12], 5);
HHH(ccc, ddd, eee, aaa, bbb, X[ 2], 14);
HHH(bbb, ccc, ddd, eee, aaa, X[10], 13);
HHH(aaa, bbb, ccc, ddd, eee, X[ 0], 13);
HHH(eee, aaa, bbb, ccc, ddd, X[ 4], 7);
HHH(ddd, eee, aaa, bbb, ccc, X[13], 5);
/* parallel round 4 */
GGG(ccc, ddd, eee, aaa, bbb, X[ 8], 15);
GGG(bbb, ccc, ddd, eee, aaa, X[ 6], 5);
GGG(aaa, bbb, ccc, ddd, eee, X[ 4], 8);
GGG(eee, aaa, bbb, ccc, ddd, X[ 1], 11);
GGG(ddd, eee, aaa, bbb, ccc, X[ 3], 14);
GGG(ccc, ddd, eee, aaa, bbb, X[11], 14);
GGG(bbb, ccc, ddd, eee, aaa, X[15], 6);
GGG(aaa, bbb, ccc, ddd, eee, X[ 0], 14);
GGG(eee, aaa, bbb, ccc, ddd, X[ 5], 6);
GGG(ddd, eee, aaa, bbb, ccc, X[12], 9);
GGG(ccc, ddd, eee, aaa, bbb, X[ 2], 12);
GGG(bbb, ccc, ddd, eee, aaa, X[13], 9);
GGG(aaa, bbb, ccc, ddd, eee, X[ 9], 12);
GGG(eee, aaa, bbb, ccc, ddd, X[ 7], 5);
GGG(ddd, eee, aaa, bbb, ccc, X[10], 15);
GGG(ccc, ddd, eee, aaa, bbb, X[14], 8);
/* parallel round 5 */
FFF(bbb, ccc, ddd, eee, aaa, X[12] , 8);
FFF(aaa, bbb, ccc, ddd, eee, X[15] , 5);
FFF(eee, aaa, bbb, ccc, ddd, X[10] , 12);
FFF(ddd, eee, aaa, bbb, ccc, X[ 4] , 9);
FFF(ccc, ddd, eee, aaa, bbb, X[ 1] , 12);
FFF(bbb, ccc, ddd, eee, aaa, X[ 5] , 5);
FFF(aaa, bbb, ccc, ddd, eee, X[ 8] , 14);
FFF(eee, aaa, bbb, ccc, ddd, X[ 7] , 6);
FFF(ddd, eee, aaa, bbb, ccc, X[ 6] , 8);
FFF(ccc, ddd, eee, aaa, bbb, X[ 2] , 13);
FFF(bbb, ccc, ddd, eee, aaa, X[13] , 6);
FFF(aaa, bbb, ccc, ddd, eee, X[14] , 5);
FFF(eee, aaa, bbb, ccc, ddd, X[ 0] , 15);
FFF(ddd, eee, aaa, bbb, ccc, X[ 3] , 13);
FFF(ccc, ddd, eee, aaa, bbb, X[ 9] , 11);
FFF(bbb, ccc, ddd, eee, aaa, X[11] , 11);
/* combine results */
ddd += cc + MDbuf[1]; /* final result for MDbuf[0] */
MDbuf[1] = MDbuf[2] + dd + eee;
MDbuf[2] = MDbuf[3] + ee + aaa;
MDbuf[3] = MDbuf[4] + aa + bbb;
MDbuf[4] = MDbuf[0] + bb + ccc;
MDbuf[0] = ddd;
return;
}
void MDfinish(uint32_t *MDbuf, byte const *strptr, uint32_t lswlen, uint32_t mswlen)
{
unsigned int i; /* counter */
uint32_t X[16]; /* message words */
memset(X, 0, 16*sizeof(uint32_t));
/* put bytes from strptr into X */
for (i=0; i<(lswlen&63); i++) {
/* byte i goes into word X[i div 4] at pos. 8*(i mod 4) */
X[i>>2] ^= (uint32_t) *strptr++ << (8 * (i&3));
}
/* append the bit m_n == 1 */
X[(lswlen>>2)&15] ^= (uint32_t)1 << (8*(lswlen&3) + 7);
if ((lswlen & 63) > 55) {
/* length goes to next block */
MDcompress(MDbuf, X);
memset(X, 0, 16*sizeof(uint32_t));
}
/* append length in bits*/
X[14] = lswlen << 3;
X[15] = (lswlen >> 29) | (mswlen << 3);
MDcompress(MDbuf, X);
return;
}
#undef ROL
#undef F
#undef G
#undef H
#undef I
#undef J
#undef FF
#undef GG
#undef HH
#undef II
#undef JJ
#undef FFF
#undef GGG
#undef HHH
#undef III
#undef JJJ
}
/*
* @returns RMD(_input)
*/
h160 ripemd160(bytesConstRef _input)
{
h160 hashcode;
uint32_t buffer[RMDsize / 32]; // contains (A, B, C, D(, E))
uint32_t current[16]; // current 16-word chunk
// initialize
rmd160::MDinit(buffer);
byte const* message = _input.data();
uint32_t remaining = _input.size(); // # of bytes not yet processed
// process message in 16x 4-byte chunks
for (; remaining >= 64; remaining -= 64)
{
for (unsigned i = 0; i < 16; i++)
{
current[i] = BYTES_TO_DWORD(message);
message += 4;
}
rmd160::MDcompress(buffer, current);
}
// length mod 64 bytes left
// finish:
rmd160::MDfinish(buffer, message, _input.size(), 0);
for (unsigned i = 0; i < RMDsize / 8; i += 4)
{
hashcode[i] = buffer[i >> 2]; // implicit cast to byte
hashcode[i + 1] = (buffer[i >> 2] >> 8); //extracts the 8 least
hashcode[i + 2] = (buffer[i >> 2] >> 16); // significant bits.
hashcode[i + 3] = (buffer[i >> 2] >> 24);
}
return hashcode;
}
#undef BYTES_TO_DWORD
#undef RMDsize
}

38
libdevcore/Hash.h

@ -1,38 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Hash.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*
* The FixedHash fixed-size "hash" container type.
*/
#pragma once
#include <string>
#include <libdevcore/FixedHash.h>
#include <libdevcore/vector_ref.h>
#include "SHA3.h"
namespace dev
{
h256 sha256(bytesConstRef _input);
h160 ripemd160(bytesConstRef _input);
}

8
libdevcore/Log.cpp

@ -43,14 +43,6 @@ mutex x_logOverride;
/// or equal to the currently output verbosity (g_logVerbosity).
static map<type_info const*, bool> s_logOverride;
bool dev::isChannelVisible(std::type_info const* _ch, bool _default)
{
Guard l(x_logOverride);
if (s_logOverride.count(_ch))
return s_logOverride[_ch];
return _default;
}
LogOverrideAux::LogOverrideAux(std::type_info const* _ch, bool _value):
m_ch(_ch)
{

22
libdevcore/Log.h

@ -33,7 +33,6 @@
#pragma GCC diagnostic pop
#include "vector_ref.h"
#include "Common.h"
#include "CommonIO.h"
#include "CommonData.h"
#include "FixedHash.h"
#include "Terminal.h"
@ -71,27 +70,6 @@ private:
int m_old;
};
template <class Channel>
class LogOverride: LogOverrideAux
{
public:
LogOverride(bool _value): LogOverrideAux(&typeid(Channel), _value) {}
};
bool isChannelVisible(std::type_info const* _ch, bool _default);
template <class Channel> bool isChannelVisible() { return isChannelVisible(&typeid(Channel), Channel::verbosity <= g_logVerbosity); }
/// Temporary changes system's verbosity for specific function. Restores the old verbosity when function returns.
/// Not thread-safe, use with caution!
struct VerbosityHolder
{
VerbosityHolder(int _temporaryValue): oldLogVerbosity(g_logVerbosity) { g_logVerbosity = _temporaryValue; }
~VerbosityHolder() { g_logVerbosity = oldLogVerbosity; }
int oldLogVerbosity;
};
#define ETH_THREAD_CONTEXT(name) for (std::pair<dev::ThreadContext, bool> __eth_thread_context(name, true); p.second; p.second = false)
class ThreadContext
{
public:

183
libdevcore/MemoryDB.cpp

@ -1,183 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file MemoryDB.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include <libdevcore/Common.h>
#include "MemoryDB.h"
using namespace std;
using namespace dev;
namespace dev
{
const char* DBChannel::name() { return "TDB"; }
const char* DBWarn::name() { return "TDB"; }
std::unordered_map<h256, std::string> MemoryDB::get() const
{
#if DEV_GUARDED_DB
ReadGuard l(x_this);
#endif
std::unordered_map<h256, std::string> ret;
for (auto const& i: m_main)
if (!m_enforceRefs || i.second.second > 0)
ret.insert(make_pair(i.first, i.second.first));
return ret;
}
MemoryDB& MemoryDB::operator=(MemoryDB const& _c)
{
if (this == &_c)
return *this;
#if DEV_GUARDED_DB
ReadGuard l(_c.x_this);
WriteGuard l2(x_this);
#endif
m_main = _c.m_main;
m_aux = _c.m_aux;
return *this;
}
std::string MemoryDB::lookup(h256 const& _h) const
{
#if DEV_GUARDED_DB
ReadGuard l(x_this);
#endif
auto it = m_main.find(_h);
if (it != m_main.end())
{
if (!m_enforceRefs || it->second.second > 0)
return it->second.first;
else
cwarn << "Lookup required for value with refcount == 0. This is probably a critical trie issue" << _h;
}
return std::string();
}
bool MemoryDB::exists(h256 const& _h) const
{
#if DEV_GUARDED_DB
ReadGuard l(x_this);
#endif
auto it = m_main.find(_h);
if (it != m_main.end() && (!m_enforceRefs || it->second.second > 0))
return true;
return false;
}
void MemoryDB::insert(h256 const& _h, bytesConstRef _v)
{
#if DEV_GUARDED_DB
WriteGuard l(x_this);
#endif
auto it = m_main.find(_h);
if (it != m_main.end())
{
it->second.first = _v.toString();
it->second.second++;
}
else
m_main[_h] = make_pair(_v.toString(), 1);
#if ETH_PARANOIA
dbdebug << "INST" << _h << "=>" << m_main[_h].second;
#endif
}
bool MemoryDB::kill(h256 const& _h)
{
#if DEV_GUARDED_DB
ReadGuard l(x_this);
#endif
if (m_main.count(_h))
{
if (m_main[_h].second > 0)
{
m_main[_h].second--;
return true;
}
#if ETH_PARANOIA
else
{
// If we get to this point, then there was probably a node in the level DB which we need to remove and which we have previously
// used as part of the memory-based MemoryDB. Nothing to be worried about *as long as the node exists in the DB*.
dbdebug << "NOKILL-WAS" << _h;
}
dbdebug << "KILL" << _h << "=>" << m_main[_h].second;
}
else
{
dbdebug << "NOKILL" << _h;
#endif
}
return false;
}
bytes MemoryDB::lookupAux(h256 const& _h) const
{
#if DEV_GUARDED_DB
ReadGuard l(x_this);
#endif
auto it = m_aux.find(_h);
if (it != m_aux.end() && (!m_enforceRefs || it->second.second))
return it->second.first;
return bytes();
}
void MemoryDB::removeAux(h256 const& _h)
{
#if DEV_GUARDED_DB
WriteGuard l(x_this);
#endif
m_aux[_h].second = false;
}
void MemoryDB::insertAux(h256 const& _h, bytesConstRef _v)
{
#if DEV_GUARDED_DB
WriteGuard l(x_this);
#endif
m_aux[_h] = make_pair(_v.toBytes(), true);
}
void MemoryDB::purge()
{
#if DEV_GUARDED_DB
WriteGuard l(x_this);
#endif
for (auto it = m_main.begin(); it != m_main.end(); )
if (it->second.second)
++it;
else
it = m_main.erase(it);
}
h256Hash MemoryDB::keys() const
{
#if DEV_GUARDED_DB
ReadGuard l(x_this);
#endif
h256Hash ret;
for (auto const& i: m_main)
if (i.second.second)
ret.insert(i.first);
return ret;
}
}

99
libdevcore/MemoryDB.h

@ -1,99 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file MemoryDB.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
#include <unordered_map>
#include <libdevcore/Common.h>
#include <libdevcore/Guards.h>
#include <libdevcore/FixedHash.h>
#include <libdevcore/Log.h>
#include <libdevcore/RLP.h>
#include "SHA3.h"
namespace dev
{
struct DBChannel: public LogChannel { static const char* name(); static const int verbosity = 18; };
struct DBWarn: public LogChannel { static const char* name(); static const int verbosity = 1; };
#define dbdebug clog(DBChannel)
#define dbwarn clog(DBWarn)
class MemoryDB
{
friend class EnforceRefs;
public:
MemoryDB() {}
MemoryDB(MemoryDB const& _c) { operator=(_c); }
MemoryDB& operator=(MemoryDB const& _c);
void clear() { m_main.clear(); } // WARNING !!!! didn't originally clear m_refCount!!!
std::unordered_map<h256, std::string> get() const;
std::string lookup(h256 const& _h) const;
bool exists(h256 const& _h) const;
void insert(h256 const& _h, bytesConstRef _v);
bool kill(h256 const& _h);
void purge();
bytes lookupAux(h256 const& _h) const;
void removeAux(h256 const& _h);
void insertAux(h256 const& _h, bytesConstRef _v);
h256Hash keys() const;
protected:
#if DEV_GUARDED_DB
mutable SharedMutex x_this;
#endif
std::unordered_map<h256, std::pair<std::string, unsigned>> m_main;
std::unordered_map<h256, std::pair<bytes, bool>> m_aux;
mutable bool m_enforceRefs = false;
};
class EnforceRefs
{
public:
EnforceRefs(MemoryDB const& _o, bool _r): m_o(_o), m_r(_o.m_enforceRefs) { _o.m_enforceRefs = _r; }
~EnforceRefs() { m_o.m_enforceRefs = m_r; }
private:
MemoryDB const& m_o;
bool m_r;
};
inline std::ostream& operator<<(std::ostream& _out, MemoryDB const& _m)
{
for (auto const& i: _m.get())
{
_out << i.first << ": ";
_out << RLP(i.second);
_out << " " << toHex(i.second);
_out << std::endl;
}
return _out;
}
}

22
libdevcore/RangeMask.cpp

@ -1,22 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file RangeMask.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "RangeMask.h"

294
libdevcore/RangeMask.h

@ -1,294 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file RangeMask.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
#include <map>
#include <utility>
#include <vector>
#include <iterator>
#include <iostream>
#include <assert.h>
namespace dev
{
class RLPStream;
using UnsignedRange = std::pair<unsigned, unsigned>;
using UnsignedRanges = std::vector<UnsignedRange>;
/**
* Set of elements of a certain "ground range" representable by unions of ranges inside this
* ground range.
* Ranges are given as pairs (begin, end), denoting the interval [begin, end), i.e. end is excluded.
* Supports set-theoretic operators, size and iteration.
*/
template <class T>
class RangeMask
{
template <class U> friend std::ostream& operator<<(std::ostream& _out, RangeMask<U> const& _r);
public:
using Range = std::pair<T, T>;
using Ranges = std::vector<Range>;
/// Constructs an empty range mask with empty ground range.
RangeMask(): m_all(0, 0) {}
/// Constructs an empty range mask with ground range [_begin, _end).
RangeMask(T _begin, T _end): m_all(_begin, _end) {}
/// Constructs an empty range mask with ground range _c.
RangeMask(Range const& _c): m_all(_c) {}
/// @returns the union with the range mask _m, taking also the union of the ground ranges.
RangeMask unionedWith(RangeMask const& _m) const { return operator+(_m); }
RangeMask operator+(RangeMask const& _m) const { return RangeMask(*this) += _m; }
/// @returns a new range mask containing the smallest _items elements (not ranges).
RangeMask lowest(decltype(T{} - T{}) _items) const
{
RangeMask ret(m_all);
for (auto i = m_ranges.begin(); i != m_ranges.end() && _items; ++i)
_items -= (ret.m_ranges[i->first] = std::min(i->first + _items, i->second)) - i->first;
return ret;
}
/// @returns the complement of the range mask relative to the ground range.
RangeMask operator~() const { return inverted(); }
/// @returns a copy of this range mask representing the complement relative to the ground range.
RangeMask inverted() const
{
RangeMask ret(m_all);
T last = m_all.first;
for (auto i: m_ranges)
{
if (i.first != last)
ret.m_ranges[last] = i.first;
last = i.second;
}
if (last != m_all.second)
ret.m_ranges[last] = m_all.second;
return ret;
}
/// Changes the range mask to its complement relative to the ground range and returns a
/// reference to itself.
RangeMask& invert() { return *this = inverted(); }
template <class S> RangeMask operator-(S const& _m) const { auto ret = *this; return ret -= _m; }
template <class S> RangeMask& operator-=(S const& _m) { return invert().unionWith(_m).invert(); }
RangeMask& operator+=(RangeMask const& _m) { return unionWith(_m); }
RangeMask& unionWith(RangeMask const& _m)
{
m_all.first = std::min(_m.m_all.first, m_all.first);
m_all.second = std::max(_m.m_all.second, m_all.second);
for (auto const& i: _m.m_ranges)
unionWith(i);
return *this;
}
RangeMask& operator+=(Range const& _m) { return unionWith(_m); }
/// Modifies this range mask to also include the range _m, which has to be a subset of
/// the ground range.
RangeMask& unionWith(Range const& _m);
/// Adds the single element _i to the range mask.
RangeMask& operator+=(T _m) { return unionWith(_m); }
/// Adds the single element _i to the range mask.
RangeMask& unionWith(T _i)
{
return operator+=(Range(_i, _i + 1));
}
bool contains(T _i) const
{
auto it = m_ranges.upper_bound(_i);
if (it == m_ranges.begin())
return false;
return (--it)->second > _i;
}
bool empty() const
{
return m_ranges.empty();
}
bool full() const
{
return m_all.first == m_all.second || (m_ranges.size() == 1 && m_ranges.begin()->first == m_all.first && m_ranges.begin()->second == m_all.second);
}
void clear()
{
m_ranges.clear();
}
void reset()
{
m_ranges.clear();
m_all = std::make_pair(0, 0);
}
/// @returns the ground range.
std::pair<T, T> const& all() const { return m_all; }
/// Extends the ground range to include _i.
void extendAll(T _i) { m_all = std::make_pair(std::min(m_all.first, _i), std::max(m_all.second, _i + 1)); }
class const_iterator: public std::iterator<std::forward_iterator_tag, T>
{
friend class RangeMask;
public:
const_iterator() {}
T operator*() const { return m_value; }
const_iterator& operator++() { if (m_owner) m_value = m_owner->next(m_value); return *this; }
const_iterator operator++(int) { auto ret = *this; if (m_owner) m_value = m_owner->next(m_value); return ret; }
bool operator==(const_iterator const& _i) const { return m_owner == _i.m_owner && m_value == _i.m_value; }
bool operator!=(const_iterator const& _i) const { return !operator==(_i); }
bool operator<(const_iterator const& _i) const { return m_value < _i.m_value; }
private:
const_iterator(RangeMask const& _m, bool _end): m_owner(&_m), m_value(_m.m_ranges.empty() || _end ? _m.m_all.second : _m.m_ranges.begin()->first) {}
RangeMask const* m_owner = nullptr;
T m_value = 0;
};
const_iterator begin() const { return const_iterator(*this, false); }
const_iterator end() const { return const_iterator(*this, true); }
/// @returns the smallest element in the range mask that is larger than _t or the end of the
/// base range if such an element does not exist.
T next(T _t) const
{
_t++;
// find next item in range at least _t
auto uit = m_ranges.upper_bound(_t); // > _t
auto it = uit == m_ranges.begin() ? m_ranges.end() : std::prev(uit);
if (it != m_ranges.end() && it->first <= _t && it->second > _t)
return _t;
return uit == m_ranges.end() ? m_all.second : uit->first;
}
/// @returns the number of elements (not ranges) in the range mask.
size_t size() const
{
size_t c = 0;
for (auto const& r: this->m_ranges)
c += r.second - r.first;
return c;
}
size_t firstOut() const
{
if (m_ranges.empty() || !m_ranges.count(m_all.first))
return m_all.first;
return m_ranges.at(m_all.first);
}
size_t lastIn() const
{
if (m_ranges.empty())
return m_all.first;
return m_ranges.rbegin()->second - 1;
}
private:
/// The ground range.
UnsignedRange m_all;
/// Mapping begin -> end containing the ranges.
std::map<T, T> m_ranges;
};
template <class T> inline std::ostream& operator<<(std::ostream& _out, RangeMask<T> const& _r)
{
_out << _r.m_all.first << "{ ";
for (auto const& i: _r.m_ranges)
_out << "[" << i.first << ", " << i.second << ") ";
_out << "}" << _r.m_all.second;
return _out;
}
template <class T>
RangeMask<T>& RangeMask<T>::unionWith(typename RangeMask<T>::Range const& _m)
{
for (auto i = _m.first; i < _m.second;)
{
assert(i >= m_all.first);
assert(i < m_all.second);
// For each number, we find the element equal or next lower. this, if any, must contain the value.
// First range that starts after i.
auto rangeAfter = m_ranges.upper_bound(i);
// Range before rangeAfter or "end" if the rangeAfter is the first ever...
auto it = rangeAfter == m_ranges.begin() ? m_ranges.end() : std::prev(rangeAfter);
if (it == m_ranges.end() || it->second < i)
{
// i is either before the first range or between two ranges (with some distance
// so that we cannot merge it onto "it").
// lower range is too low to merge.
// if the next higher range is too high.
if (rangeAfter == m_ranges.end() || rangeAfter->first > _m.second)
{
// just create a new range
m_ranges[i] = _m.second;
break;
}
else
{
if (rangeAfter->first == i)
// move i to end of range
i = rangeAfter->second;
else
{
// merge with the next higher range
// move i to end of range
i = m_ranges[i] = rangeAfter->second;
m_ranges.erase(rangeAfter);
}
}
}
else if (it->second == i)
{
// The range before i ends with i.
// if the next higher range is too high.
if (rangeAfter == m_ranges.end() || rangeAfter->first > _m.second)
{
// merge with the next lower range
m_ranges[it->first] = _m.second;
break;
}
else
{
// merge with both next lower & next higher.
i = m_ranges[it->first] = rangeAfter->second;
m_ranges.erase(rangeAfter);
}
}
else
i = it->second;
}
return *this;
}
}

1
libdevcore/SHA3.cpp

@ -25,7 +25,6 @@
#include <cstdlib>
#include <cstring>
#include <libdevcore/RLP.h>
#include "picosha2.h"
using namespace std;
using namespace dev;

25
libdevcore/SHA3.h

@ -24,8 +24,8 @@
#pragma once
#include <string>
#include <libdevcore/FixedHash.h>
#include <libdevcore/vector_ref.h>
#include "FixedHash.h"
#include "vector_ref.h"
namespace dev
{
@ -38,33 +38,12 @@ bool sha3(bytesConstRef _input, bytesRef o_output);
/// Calculate SHA3-256 hash of the given input, returning as a 256-bit hash.
inline h256 sha3(bytesConstRef _input) { h256 ret; sha3(_input, ret.ref()); return ret; }
inline SecureFixedHash<32> sha3Secure(bytesConstRef _input) { SecureFixedHash<32> ret; sha3(_input, ret.writable().ref()); return ret; }
/// Calculate SHA3-256 hash of the given input, returning as a 256-bit hash.
inline h256 sha3(bytes const& _input) { return sha3(bytesConstRef(&_input)); }
inline SecureFixedHash<32> sha3Secure(bytes const& _input) { return sha3Secure(bytesConstRef(&_input)); }
/// Calculate SHA3-256 hash of the given input (presented as a binary-filled string), returning as a 256-bit hash.
inline h256 sha3(std::string const& _input) { return sha3(bytesConstRef(_input)); }
inline SecureFixedHash<32> sha3Secure(std::string const& _input) { return sha3Secure(bytesConstRef(_input)); }
/// Calculate SHA3-256 hash of the given input (presented as a FixedHash), returns a 256-bit hash.
template<unsigned N> inline h256 sha3(FixedHash<N> const& _input) { return sha3(_input.ref()); }
template<unsigned N> inline SecureFixedHash<32> sha3Secure(FixedHash<N> const& _input) { return sha3Secure(_input.ref()); }
/// Fully secure variants are equivalent for sha3 and sha3Secure.
inline SecureFixedHash<32> sha3(bytesSec const& _input) { return sha3Secure(_input.ref()); }
inline SecureFixedHash<32> sha3Secure(bytesSec const& _input) { return sha3Secure(_input.ref()); }
template<unsigned N> inline SecureFixedHash<32> sha3(SecureFixedHash<N> const& _input) { return sha3Secure(_input.ref()); }
template<unsigned N> inline SecureFixedHash<32> sha3Secure(SecureFixedHash<N> const& _input) { return sha3Secure(_input.ref()); }
/// Calculate SHA3-256 hash of the given input, possibly interpreting it as nibbles, and return the hash as a string filled with binary data.
inline std::string sha3(std::string const& _input, bool _isNibbles) { return asString((_isNibbles ? sha3(fromHex(_input)) : sha3(bytesConstRef(&_input))).asBytes()); }
/// Calculate SHA3-256 MAC
inline void sha3mac(bytesConstRef _secret, bytesConstRef _plain, bytesRef _output) { sha3(_secret.toBytes() + _plain.toBytes()).ref().populate(_output); }
extern h256 EmptySHA3;
extern h256 EmptyListSHA3;

251
libdevcore/StructuredLogger.cpp

@ -1,251 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file StructuredLogger.h
* @author Lefteris Karapetsas <lefteris@ethdev.com>
* @date 2015
*
* A simple helper class for the structured logging
*/
#include "StructuredLogger.h"
#include <boost/asio/ip/tcp.hpp>
#if ETH_JSONRPC
#include <json/json.h>
#endif
#include <libdevcore/CommonIO.h>
#include "Guards.h"
namespace ba = boost::asio;
using namespace std;
namespace dev
{
void StructuredLogger::initialize(bool _enabled, std::string const& _timeFormat, std::string const& _destinationURL)
{
m_enabled = _enabled;
m_timeFormat = _timeFormat;
if (_destinationURL.size() > 7 && _destinationURL.substr(0, 7) == "file://")
m_out.open(_destinationURL.substr(7));
// TODO: support tcp://
}
void StructuredLogger::outputJson(Json::Value const& _value, std::string const& _name) const
{
#if ETH_JSONRPC
Json::Value event;
static Mutex s_lock;
Json::FastWriter fastWriter;
Guard l(s_lock);
event[_name] = _value;
(m_out.is_open() ? m_out : cout) << fastWriter.write(event) << endl;
#else
(void)_value;
(void)_name;
#endif
}
void StructuredLogger::starting(string const& _clientImpl, const char* _ethVersion)
{
#if ETH_JSONRPC
if (get().m_enabled)
{
Json::Value event;
event["client_impl"] = _clientImpl;
event["eth_version"] = std::string(_ethVersion);
// TODO net_version
event["ts"] = dev::toString(chrono::system_clock::now(), get().m_timeFormat.c_str());
get().outputJson(event, "starting");
}
#else
(void)_clientImpl;
(void)_ethVersion;
#endif
}
void StructuredLogger::stopping(string const& _clientImpl, const char* _ethVersion)
{
#if ETH_JSONRPC
if (get().m_enabled)
{
Json::Value event;
event["client_impl"] = _clientImpl;
event["eth_version"] = std::string(_ethVersion);
// TODO net_version
event["ts"] = dev::toString(chrono::system_clock::now(), get().m_timeFormat.c_str());
get().outputJson(event, "stopping");
}
#else
(void)_clientImpl;
(void)_ethVersion;
#endif
}
void StructuredLogger::p2pConnected(
string const& _id,
bi::tcp::endpoint const& _addr,
chrono::system_clock::time_point const& _ts,
string const& _remoteVersion,
unsigned int _numConnections)
{
#if ETH_JSONRPC
if (get().m_enabled)
{
std::stringstream addrStream;
addrStream << _addr;
Json::Value event;
event["remote_version_string"] = _remoteVersion;
event["remote_addr"] = addrStream.str();
event["remote_id"] = _id;
event["num_connections"] = Json::Value(_numConnections);
event["ts"] = dev::toString(_ts, get().m_timeFormat.c_str());
get().outputJson(event, "p2p.connected");
}
#else
(void)_id;
(void)_addr;
(void)_ts;
(void)_remoteVersion;
(void)_numConnections;
#endif
}
void StructuredLogger::p2pDisconnected(string const& _id, bi::tcp::endpoint const& _addr, unsigned int _numConnections)
{
#if ETH_JSONRPC
if (get().m_enabled)
{
std::stringstream addrStream;
addrStream << _addr;
Json::Value event;
event["remote_addr"] = addrStream.str();
event["remote_id"] = _id;
event["num_connections"] = Json::Value(_numConnections);
event["ts"] = dev::toString(chrono::system_clock::now(), get().m_timeFormat.c_str());
get().outputJson(event, "p2p.disconnected");
}
#else
(void)_id;
(void)_addr;
(void)_numConnections;
#endif
}
void StructuredLogger::minedNewBlock(
string const& _hash,
string const& _blockNumber,
string const& _chainHeadHash,
string const& _prevHash)
{
#if ETH_JSONRPC
if (get().m_enabled)
{
Json::Value event;
event["block_hash"] = _hash;
event["block_number"] = _blockNumber;
event["chain_head_hash"] = _chainHeadHash;
event["ts"] = dev::toString(chrono::system_clock::now(), get().m_timeFormat.c_str());
event["block_prev_hash"] = _prevHash;
get().outputJson(event, "eth.miner.new_block");
}
#else
(void)_hash;
(void)_blockNumber;
(void)_chainHeadHash;
(void)_prevHash;
#endif
}
void StructuredLogger::chainReceivedNewBlock(
string const& _hash,
string const& _blockNumber,
string const& _chainHeadHash,
string const& _remoteID,
string const& _prevHash)
{
#if ETH_JSONRPC
if (get().m_enabled)
{
Json::Value event;
event["block_hash"] = _hash;
event["block_number"] = _blockNumber;
event["chain_head_hash"] = _chainHeadHash;
event["remote_id"] = _remoteID;
event["ts"] = dev::toString(chrono::system_clock::now(), get().m_timeFormat.c_str());
event["block_prev_hash"] = _prevHash;
get().outputJson(event, "eth.chain.received.new_block");
}
#else
(void)_hash;
(void)_blockNumber;
(void)_chainHeadHash;
(void)_remoteID;
(void)_prevHash;
#endif
}
void StructuredLogger::chainNewHead(
string const& _hash,
string const& _blockNumber,
string const& _chainHeadHash,
string const& _prevHash)
{
#if ETH_JSONRPC
if (get().m_enabled)
{
Json::Value event;
event["block_hash"] = _hash;
event["block_number"] = _blockNumber;
event["chain_head_hash"] = _chainHeadHash;
event["ts"] = dev::toString(chrono::system_clock::now(), get().m_timeFormat.c_str());
event["block_prev_hash"] = _prevHash;
get().outputJson(event, "eth.miner.new_block");
}
#else
(void)_hash;
(void)_blockNumber;
(void)_chainHeadHash;
(void)_prevHash;
#endif
}
void StructuredLogger::transactionReceived(string const& _hash, string const& _remoteId)
{
#if ETH_JSONRPC
if (get().m_enabled)
{
Json::Value event;
event["tx_hash"] = _hash;
event["remote_id"] = _remoteId;
event["ts"] = dev::toString(chrono::system_clock::now(), get().m_timeFormat.c_str());
get().outputJson(event, "eth.tx.received");
}
#else
(void)_hash;
(void)_remoteId;
#endif
}
}

111
libdevcore/StructuredLogger.h

@ -1,111 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file StructuredLogger.h
* @author Lefteris Karapetsas <lefteris@ethdev.com>
* @date 2015
*
* A simple helper class for the structured logging
* The spec for the implemented log events is here:
* https://github.com/ethereum/system-testing/wiki/Log-Events
*/
#pragma once
#include <fstream>
#include <string>
#include <chrono>
namespace Json { class Value; }
namespace boost { namespace asio { namespace ip { template<class T>class basic_endpoint; class tcp; }}}
namespace bi = boost::asio::ip;
namespace dev
{
// TODO: Make the output stream configurable. stdout, stderr, file e.t.c.
class StructuredLogger
{
public:
/**
* Initializes the structured logger object
* @param _enabled Whether logging is on or off
* @param _timeFormat A time format string as described here:
* http://en.cppreference.com/w/cpp/chrono/c/strftime
* with which to display timestamps
*/
void initialize(bool _enabled, std::string const& _timeFormat, std::string const& _destinationURL = "");
static StructuredLogger& get()
{
static StructuredLogger instance;
return instance;
}
static void starting(std::string const& _clientImpl, const char* _ethVersion);
static void stopping(std::string const& _clientImpl, const char* _ethVersion);
static void p2pConnected(
std::string const& _id,
bi::basic_endpoint<bi::tcp> const& _addr,
std::chrono::system_clock::time_point const& _ts,
std::string const& _remoteVersion,
unsigned int _numConnections
);
static void p2pDisconnected(
std::string const& _id,
bi::basic_endpoint<bi::tcp> const& _addr,
unsigned int _numConnections
);
static void minedNewBlock(
std::string const& _hash,
std::string const& _blockNumber,
std::string const& _chainHeadHash,
std::string const& _prevHash
);
static void chainReceivedNewBlock(
std::string const& _hash,
std::string const& _blockNumber,
std::string const& _chainHeadHash,
std::string const& _remoteID,
std::string const& _prevHash
);
static void chainNewHead(
std::string const& _hash,
std::string const& _blockNumber,
std::string const& _chainHeadHash,
std::string const& _prevHash
);
static void transactionReceived(std::string const& _hash, std::string const& _remoteId);
// TODO: static void pendingQueueChanged(std::vector<h256> const& _hashes);
// TODO: static void miningStarted();
// TODO: static void stillMining(unsigned _hashrate);
// TODO: static void miningStopped();
private:
// Singleton class. Private default ctor and no copying
StructuredLogger() = default;
StructuredLogger(StructuredLogger const&) = delete;
void operator=(StructuredLogger const&) = delete;
void outputJson(Json::Value const& _value, std::string const& _name) const;
bool m_enabled = false;
std::string m_timeFormat = "%Y-%m-%dT%H:%M:%S";
mutable std::ofstream m_out;
};
}

66
libdevcore/TransientDirectory.cpp

@ -1,66 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file TransientDirectory.cpp
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
#include <thread>
#include <boost/filesystem.hpp>
#include "Exceptions.h"
#include "TransientDirectory.h"
#include "CommonIO.h"
#include "Log.h"
using namespace std;
using namespace dev;
namespace fs = boost::filesystem;
TransientDirectory::TransientDirectory():
TransientDirectory((boost::filesystem::temp_directory_path() / "eth_transient" / toString(FixedHash<4>::random())).string())
{}
TransientDirectory::TransientDirectory(std::string const& _path):
m_path(_path)
{
// we never ever want to delete a directory (including all its contents) that we did not create ourselves.
if (boost::filesystem::exists(m_path))
BOOST_THROW_EXCEPTION(FileError());
fs::create_directories(m_path);
DEV_IGNORE_EXCEPTIONS(fs::permissions(m_path, fs::owner_all));
}
TransientDirectory::~TransientDirectory()
{
boost::system::error_code ec;
fs::remove_all(m_path, ec);
if (!ec)
return;
// In some cases, antivirus runnig on Windows will scan all the newly created directories.
// As a consequence, directory is locked and can not be deleted immediately.
// Retry after 10 milliseconds usually is successful.
// This will help our tests run smoothly in such environment.
this_thread::sleep_for(chrono::milliseconds(10));
ec.clear();
fs::remove_all(m_path, ec);
if (!ec)
{
cwarn << "Failed to delete directory '" << m_path << "': " << ec.message();
}
}

47
libdevcore/TransientDirectory.h

@ -1,47 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file TransientDirectory.h
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
#pragma once
#include <string>
namespace dev
{
/**
* @brief temporary directory implementation
* It creates temporary directory in the given path. On dealloc it removes the directory
* @throws if the given path already exists, throws an exception
*/
class TransientDirectory
{
public:
TransientDirectory();
TransientDirectory(std::string const& _path);
~TransientDirectory();
std::string const& path() const { return m_path; }
private:
std::string m_path;
};
}

127
libdevcore/TrieCommon.cpp

@ -1,127 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file TrieCommon.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "TrieCommon.h"
namespace dev
{
/*
* Hex-prefix Notation. First nibble has flags: oddness = 2^0 & termination = 2^1
* NOTE: the "termination marker" and "leaf-node" specifier are completely equivalent.
* [0,0,1,2,3,4,5] 0x10012345
* [0,1,2,3,4,5] 0x00012345
* [1,2,3,4,5] 0x112345
* [0,0,1,2,3,4] 0x00001234
* [0,1,2,3,4] 0x101234
* [1,2,3,4] 0x001234
* [0,0,1,2,3,4,5,T] 0x30012345
* [0,0,1,2,3,4,T] 0x20001234
* [0,1,2,3,4,5,T] 0x20012345
* [1,2,3,4,5,T] 0x312345
* [1,2,3,4,T] 0x201234
*/
std::string hexPrefixEncode(bytes const& _hexVector, bool _leaf, int _begin, int _end)
{
unsigned begin = _begin;
unsigned end = _end < 0 ? _hexVector.size() + 1 + _end : _end;
bool odd = ((end - begin) % 2) != 0;
std::string ret(1, ((_leaf ? 2 : 0) | (odd ? 1 : 0)) * 16);
if (odd)
{
ret[0] |= _hexVector[begin];
++begin;
}
for (unsigned i = begin; i < end; i += 2)
ret += _hexVector[i] * 16 + _hexVector[i + 1];
return ret;
}
std::string hexPrefixEncode(bytesConstRef _data, bool _leaf, int _beginNibble, int _endNibble, unsigned _offset)
{
unsigned begin = _beginNibble + _offset;
unsigned end = (_endNibble < 0 ? ((int)(_data.size() * 2 - _offset) + 1) + _endNibble : _endNibble) + _offset;
bool odd = (end - begin) & 1;
std::string ret(1, ((_leaf ? 2 : 0) | (odd ? 1 : 0)) * 16);
ret.reserve((end - begin) / 2 + 1);
unsigned d = odd ? 1 : 2;
for (auto i = begin; i < end; ++i, ++d)
{
byte n = nibble(_data, i);
if (d & 1) // odd
ret.back() |= n; // or the nibble onto the back
else
ret.push_back(n << 4); // push the nibble on to the back << 4
}
return ret;
}
std::string hexPrefixEncode(bytesConstRef _d1, unsigned _o1, bytesConstRef _d2, unsigned _o2, bool _leaf)
{
unsigned begin1 = _o1;
unsigned end1 = _d1.size() * 2;
unsigned begin2 = _o2;
unsigned end2 = _d2.size() * 2;
bool odd = (end1 - begin1 + end2 - begin2) & 1;
std::string ret(1, ((_leaf ? 2 : 0) | (odd ? 1 : 0)) * 16);
ret.reserve((end1 - begin1 + end2 - begin2) / 2 + 1);
unsigned d = odd ? 1 : 2;
for (auto i = begin1; i < end1; ++i, ++d)
{
byte n = nibble(_d1, i);
if (d & 1) // odd
ret.back() |= n; // or the nibble onto the back
else
ret.push_back(n << 4); // push the nibble on to the back << 4
}
for (auto i = begin2; i < end2; ++i, ++d)
{
byte n = nibble(_d2, i);
if (d & 1) // odd
ret.back() |= n; // or the nibble onto the back
else
ret.push_back(n << 4); // push the nibble on to the back << 4
}
return ret;
}
byte uniqueInUse(RLP const& _orig, byte except)
{
byte used = 255;
for (unsigned i = 0; i < 17; ++i)
if (i != except && !_orig[i].isEmpty())
{
if (used == 255)
used = (byte)i;
else
return 255;
}
return used;
}
}

133
libdevcore/TrieCommon.h

@ -1,133 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file TrieCommon.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
#include <libdevcore/Common.h>
#include <libdevcore/RLP.h>
namespace dev
{
inline byte nibble(bytesConstRef _data, unsigned _i)
{
return (_i & 1) ? (_data[_i / 2] & 15) : (_data[_i / 2] >> 4);
}
/// Interprets @a _first and @a _second as vectors of nibbles and returns the length of the longest common
/// prefix of _first[_beginFirst..._endFirst] and _second[_beginSecond..._endSecond].
inline unsigned sharedNibbles(bytesConstRef _first, unsigned _beginFirst, unsigned _endFirst, bytesConstRef _second, unsigned _beginSecond, unsigned _endSecond)
{
unsigned ret = 0;
while (_beginFirst < _endFirst && _beginSecond < _endSecond && nibble(_first, _beginFirst) == nibble(_second, _beginSecond))
{
++_beginFirst;
++_beginSecond;
++ret;
}
return ret;
}
/**
* Nibble-based view on a bytesConstRef.
*/
struct NibbleSlice
{
bytesConstRef data;
unsigned offset;
NibbleSlice(bytesConstRef _data = bytesConstRef(), unsigned _offset = 0): data(_data), offset(_offset) {}
byte operator[](unsigned _index) const { return nibble(data, offset + _index); }
unsigned size() const { return data.size() * 2 - offset; }
bool empty() const { return !size(); }
NibbleSlice mid(unsigned _index) const { return NibbleSlice(data, offset + _index); }
void clear() { data.reset(); offset = 0; }
/// @returns true iff _k is a prefix of this.
bool contains(NibbleSlice _k) const { return shared(_k) == _k.size(); }
/// @returns the number of shared nibbles at the beginning of this and _k.
unsigned shared(NibbleSlice _k) const { return sharedNibbles(data, offset, offset + size(), _k.data, _k.offset, _k.offset + _k.size()); }
/**
* @brief Determine if we, a full key, are situated prior to a particular key-prefix.
* @param _k The prefix.
* @return true if we are strictly prior to the prefix.
*/
bool isEarlierThan(NibbleSlice _k) const
{
unsigned i = 0;
for (; i < _k.size() && i < size(); ++i)
if (operator[](i) < _k[i]) // Byte is lower - we're earlier..
return true;
else if (operator[](i) > _k[i]) // Byte is higher - we're not earlier.
return false;
if (i >= _k.size()) // Ran past the end of the prefix - we're == for the entire prefix - we're not earlier.
return false;
return true; // Ran out before the prefix had finished - we're earlier.
}
bool operator==(NibbleSlice _k) const { return _k.size() == size() && shared(_k) == _k.size(); }
bool operator!=(NibbleSlice _s) const { return !operator==(_s); }
};
inline std::ostream& operator<<(std::ostream& _out, NibbleSlice const& _m)
{
for (unsigned i = 0; i < _m.size(); ++i)
_out << std::hex << (int)_m[i] << std::dec;
return _out;
}
inline bool isLeaf(RLP const& _twoItem)
{
assert(_twoItem.isList() && _twoItem.itemCount() == 2);
auto pl = _twoItem[0].payload();
return (pl[0] & 0x20) != 0;
}
inline NibbleSlice keyOf(bytesConstRef _hpe)
{
if (!_hpe.size())
return NibbleSlice(_hpe, 0);
if (_hpe[0] & 0x10)
return NibbleSlice(_hpe, 1);
else
return NibbleSlice(_hpe, 2);
}
inline NibbleSlice keyOf(RLP const& _twoItem)
{
return keyOf(_twoItem[0].payload());
}
byte uniqueInUse(RLP const& _orig, byte except);
std::string hexPrefixEncode(bytes const& _hexVector, bool _leaf = false, int _begin = 0, int _end = -1);
std::string hexPrefixEncode(bytesConstRef _data, bool _leaf, int _beginNibble, int _endNibble, unsigned _offset);
std::string hexPrefixEncode(bytesConstRef _d1, unsigned _o1, bytesConstRef _d2, unsigned _o2, bool _leaf);
inline std::string hexPrefixEncode(NibbleSlice _s, bool _leaf, int _begin = 0, int _end = -1)
{
return hexPrefixEncode(_s.data, _leaf, _begin, _end, _s.offset);
}
inline std::string hexPrefixEncode(NibbleSlice _s1, NibbleSlice _s2, bool _leaf)
{
return hexPrefixEncode(_s1.data, _s1.offset, _s2.data, _s2.offset, _leaf);
}
}

30
libdevcore/TrieDB.cpp

@ -1,30 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file TrieDB.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include <libdevcore/Common.h>
#include "TrieDB.h"
using namespace std;
using namespace dev;
h256 const dev::c_shaNull = sha3(rlp(""));
h256 const dev::EmptyTrie = sha3(rlp(""));
const char* TrieDBChannel::name() { return "-T-"; }

1224
libdevcore/TrieDB.h

File diff suppressed because it is too large

195
libdevcore/TrieHash.cpp

@ -1,195 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file TrieHash.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "TrieHash.h"
#include <libdevcore/TrieCommon.h>
#include <libdevcore/TrieDB.h> // @TODO replace ASAP!
#include <libdevcore/SHA3.h>
using namespace std;
using namespace dev;
namespace dev
{
/*/
#define APPEND_CHILD appendData
/*/
#define APPEND_CHILD appendRaw
/**/
#define ENABLE_DEBUG_PRINT 0
#if ENABLE_DEBUG_PRINT
bool g_hashDebug = false;
#endif
void hash256aux(HexMap const& _s, HexMap::const_iterator _begin, HexMap::const_iterator _end, unsigned _preLen, RLPStream& _rlp);
void hash256rlp(HexMap const& _s, HexMap::const_iterator _begin, HexMap::const_iterator _end, unsigned _preLen, RLPStream& _rlp)
{
#if ENABLE_DEBUG_PRINT
static std::string s_indent;
if (_preLen)
s_indent += " ";
#endif
if (_begin == _end)
_rlp << ""; // NULL
else if (std::next(_begin) == _end)
{
// only one left - terminate with the pair.
_rlp.appendList(2) << hexPrefixEncode(_begin->first, true, _preLen) << _begin->second;
#if ENABLE_DEBUG_PRINT
if (g_hashDebug)
std::cerr << s_indent << toHex(bytesConstRef(_begin->first.data() + _preLen, _begin->first.size() - _preLen), 1) << ": " << _begin->second << " = " << sha3(_rlp.out()) << std::endl;
#endif
}
else
{
// find the number of common prefix nibbles shared
// i.e. the minimum number of nibbles shared at the beginning between the first hex string and each successive.
unsigned sharedPre = (unsigned)-1;
unsigned c = 0;
for (auto i = std::next(_begin); i != _end && sharedPre; ++i, ++c)
{
unsigned x = std::min(sharedPre, std::min((unsigned)_begin->first.size(), (unsigned)i->first.size()));
unsigned shared = _preLen;
for (; shared < x && _begin->first[shared] == i->first[shared]; ++shared) {}
sharedPre = std::min(shared, sharedPre);
}
if (sharedPre > _preLen)
{
// if they all have the same next nibble, we also want a pair.
#if ENABLE_DEBUG_PRINT
if (g_hashDebug)
std::cerr << s_indent << toHex(bytesConstRef(_begin->first.data() + _preLen, sharedPre), 1) << ": " << std::endl;
#endif
_rlp.appendList(2) << hexPrefixEncode(_begin->first, false, _preLen, (int)sharedPre);
hash256aux(_s, _begin, _end, (unsigned)sharedPre, _rlp);
#if ENABLE_DEBUG_PRINT
if (g_hashDebug)
std::cerr << s_indent << "= " << hex << sha3(_rlp.out()) << dec << std::endl;
#endif
}
else
{
// otherwise enumerate all 16+1 entries.
_rlp.appendList(17);
auto b = _begin;
if (_preLen == b->first.size())
{
#if ENABLE_DEBUG_PRINT
if (g_hashDebug)
std::cerr << s_indent << "@: " << b->second << std::endl;
#endif
++b;
}
for (auto i = 0; i < 16; ++i)
{
auto n = b;
for (; n != _end && n->first[_preLen] == i; ++n) {}
if (b == n)
_rlp << "";
else
{
#if ENABLE_DEBUG_PRINT
if (g_hashDebug)
std::cerr << s_indent << std::hex << i << ": " << std::dec << std::endl;
#endif
hash256aux(_s, b, n, _preLen + 1, _rlp);
}
b = n;
}
if (_preLen == _begin->first.size())
_rlp << _begin->second;
else
_rlp << "";
#if ENABLE_DEBUG_PRINT
if (g_hashDebug)
std::cerr << s_indent << "= " << hex << sha3(_rlp.out()) << dec << std::endl;
#endif
}
}
#if ENABLE_DEBUG_PRINT
if (_preLen)
s_indent.resize(s_indent.size() - 2);
#endif
}
void hash256aux(HexMap const& _s, HexMap::const_iterator _begin, HexMap::const_iterator _end, unsigned _preLen, RLPStream& _rlp)
{
RLPStream rlp;
hash256rlp(_s, _begin, _end, _preLen, rlp);
if (rlp.out().size() < 32)
{
// RECURSIVE RLP
#if ENABLE_DEBUG_PRINT
cerr << "[INLINE: " << dec << rlp.out().size() << " < 32]" << endl;
#endif
_rlp.APPEND_CHILD(rlp.out());
}
else
{
#if ENABLE_DEBUG_PRINT
cerr << "[HASH: " << dec << rlp.out().size() << " >= 32]" << endl;
#endif
_rlp << sha3(rlp.out());
}
}
bytes rlp256(BytesMap const& _s)
{
// build patricia tree.
if (_s.empty())
return rlp("");
HexMap hexMap;
for (auto i = _s.rbegin(); i != _s.rend(); ++i)
hexMap[asNibbles(bytesConstRef(&i->first))] = i->second;
RLPStream s;
hash256rlp(hexMap, hexMap.cbegin(), hexMap.cend(), 0, s);
return s.out();
}
h256 hash256(BytesMap const& _s)
{
return sha3(rlp256(_s));
}
h256 orderedTrieRoot(std::vector<bytes> const& _data)
{
BytesMap m;
unsigned j = 0;
for (auto i: _data)
m[rlp(j++)] = i;
return hash256(m);
}
h256 orderedTrieRoot(std::vector<bytesConstRef> const& _data)
{
BytesMap m;
unsigned j = 0;
for (auto i: _data)
m[rlp(j++)] = i.toBytes();
return hash256(m);
}
}

46
libdevcore/TrieHash.h

@ -1,46 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file TrieHash.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
#include <libdevcore/Common.h>
#include <libdevcore/FixedHash.h>
namespace dev
{
bytes rlp256(BytesMap const& _s);
h256 hash256(BytesMap const& _s);
h256 orderedTrieRoot(std::vector<bytes> const& _data);
template <class T, class U> inline h256 trieRootOver(unsigned _itemCount, T const& _getKey, U const& _getValue)
{
BytesMap m;
for (unsigned i = 0; i < _itemCount; ++i)
m[_getKey(i)] = _getValue(i);
return hash256(m);
}
h256 orderedTrieRoot(std::vector<bytesConstRef> const& _data);
h256 orderedTrieRoot(std::vector<bytes> const& _data);
}

46
libdevcore/UndefMacros.h

@ -1,46 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file UndefMacros.h
* @author Lefteris <lefteris@ethdev.com>
* @date 2015
*
* This header should be used to #undef some really evil macros defined by
* windows.h which result in conflict with our libsolidity/Token.h
*/
#pragma once
#if defined(_MSC_VER) || defined(__MINGW32__)
#undef DELETE
#undef IN
#undef VOID
#undef THIS
#undef CONST
// Conflicting define on MinGW in windows.h
// windows.h(19): #define interface struct
#ifdef interface
#undef interface
#endif
#elif defined(DELETE) || defined(IN) || defined(VOID) || defined(THIS) || defined(CONST) || defined(interface)
#error "The preceding macros in this header file are reserved for V8's "\
"TOKEN_LIST. Please add a platform specific define above to undefine "\
"overlapping macros."
#endif

21
libdevcore/Worker.cpp

@ -69,17 +69,14 @@ void Worker::startWorking()
if (ex == WorkerState::Killing || ex == WorkerState::Starting)
m_state.exchange(ex);
// cnote << "Waiting until not Stopped...";
DEV_TIMED_ABOVE("Worker stopping", 100)
while (m_state == WorkerState::Stopped)
this_thread::sleep_for(chrono::milliseconds(20));
while (m_state == WorkerState::Stopped)
this_thread::sleep_for(chrono::milliseconds(20));
}
}));
// cnote << "Spawning" << m_name;
}
DEV_TIMED_ABOVE("Start worker", 100)
while (m_state == WorkerState::Starting)
this_thread::sleep_for(chrono::microseconds(20));
while (m_state == WorkerState::Starting)
this_thread::sleep_for(chrono::microseconds(20));
}
void Worker::stopWorking()
@ -90,9 +87,8 @@ void Worker::stopWorking()
WorkerState ex = WorkerState::Started;
m_state.compare_exchange_strong(ex, WorkerState::Stopping);
DEV_TIMED_ABOVE("Stop worker", 100)
while (m_state != WorkerState::Stopped)
this_thread::sleep_for(chrono::microseconds(20));
while (m_state != WorkerState::Stopped)
this_thread::sleep_for(chrono::microseconds(20));
}
}
@ -103,10 +99,7 @@ void Worker::terminate()
if (m_work)
{
m_state.exchange(WorkerState::Killing);
DEV_TIMED_ABOVE("Terminate worker", 100)
m_work->join();
m_work->join();
m_work.reset();
}
}

60
libdevcore/concurrent_queue.h

@ -1,60 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <utility>
#include <queue>
#include <condition_variable>
#include <mutex>
namespace dev
{
/// Concurrent queue.
/// You can push and pop elements to/from the queue. Pop will block until the queue is not empty.
/// The default backend (_QueueT) is std::queue. It can be changed to any type that has
/// proper push(), pop(), empty() and front() methods.
template<typename _T, typename _QueueT = std::queue<_T>>
class concurrent_queue
{
public:
template<typename _U>
void push(_U&& _elem)
{
{
std::lock_guard<decltype(x_mutex)> guard{x_mutex};
m_queue.push(std::forward<_U>(_elem));
}
m_cv.notify_one();
}
_T pop()
{
std::unique_lock<std::mutex> lock{x_mutex};
m_cv.wait(lock, [this]{ return !m_queue.empty(); });
auto item = std::move(m_queue.front());
m_queue.pop();
return item;
}
private:
_QueueT m_queue;
std::mutex x_mutex;
std::condition_variable m_cv;
};
}

30
libdevcore/db.h

@ -1,30 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file DB.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
#pragma warning(push)
#pragma warning(disable: 4100 4267)
#include <leveldb/db.h>
#include <leveldb/write_batch.h>
namespace ldb = leveldb;
#pragma warning(pop)
#define DEV_LDB 1

121
libdevcore/debugbreak.h

@ -1,121 +0,0 @@
/* Copyright (c) 2013, Scott Tsai
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DEBUG_BREAK_H
#define DEBUG_BREAK_H
#if defined(_MSC_VER) || defined(__MINGW32__)
#define debug_break __debugbreak
#else
#include <signal.h>
#include <unistd.h>
#include <sys/syscall.h>
#ifdef __cplusplus
extern "C" {
#endif
enum {
/* gcc optimizers consider code after __builtin_trap() dead.
* Making __builtin_trap() unsuitable for breaking into the debugger */
DEBUG_BREAK_PREFER_BUILTIN_TRAP_TO_SIGTRAP = 0,
};
#if defined(__i386__) || defined(__x86_64__)
enum { HAVE_TRAP_INSTRUCTION = 1, };
__attribute__((gnu_inline, always_inline))
static void __inline__ trap_instruction(void)
{
__asm__ volatile("int $0x03");
}
#elif defined(__thumb__)
enum { HAVE_TRAP_INSTRUCTION = 1, };
/* FIXME: handle __THUMB_INTERWORK__ */
__attribute__((gnu_inline, always_inline))
static void __inline__ trap_instruction(void)
{
/* See 'arm-linux-tdep.c' in GDB source.
* Both instruction sequences below works. */
#if 1
/* 'eabi_linux_thumb_le_breakpoint' */
__asm__ volatile(".inst 0xde01");
#else
/* 'eabi_linux_thumb2_le_breakpoint' */
__asm__ volatile(".inst.w 0xf7f0a000");
#endif
/* Known problem:
* After a breakpoint hit, can't stepi, step, or continue in GDB.
* 'step' stuck on the same instruction.
*
* Workaround: a new GDB command,
* 'debugbreak-step' is defined in debugbreak-gdb.py
* that does:
* (gdb) set $instruction_len = 2
* (gdb) tbreak *($pc + $instruction_len)
* (gdb) jump *($pc + $instruction_len)
*/
}
#elif defined(__arm__) && !defined(__thumb__)
enum { HAVE_TRAP_INSTRUCTION = 1, };
__attribute__((gnu_inline, always_inline))
static void __inline__ trap_instruction(void)
{
/* See 'arm-linux-tdep.c' in GDB source,
* 'eabi_linux_arm_le_breakpoint' */
__asm__ volatile(".inst 0xe7f001f0");
/* Has same known problem and workaround
* as Thumb mode */
}
#else
enum { HAVE_TRAP_INSTRUCTION = 0, };
#endif
__attribute__((gnu_inline, always_inline))
static void __inline__ debug_break(void)
{
if (HAVE_TRAP_INSTRUCTION) {
trap_instruction();
} else if (DEBUG_BREAK_PREFER_BUILTIN_TRAP_TO_SIGTRAP) {
/* raises SIGILL on Linux x86{,-64}, to continue in gdb:
* (gdb) handle SIGILL stop nopass
* */
__builtin_trap();
} else {
raise(SIGTRAP);
}
}
#ifdef __cplusplus
}
#endif
#endif
#endif

360
libdevcore/picosha2.h

@ -1,360 +0,0 @@
/*
The MIT License (MIT)
Copyright (C) 2014 okdshin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef PICOSHA2_H
#define PICOSHA2_H
//picosha2:20140213
#include <cstdint>
#include <iostream>
#include <vector>
#include <iterator>
#include <cassert>
#include <sstream>
#include <algorithm>
namespace picosha2
{
namespace detail
{
inline uint8_t mask_8bit(uint8_t x){
return x&0xff;
}
inline uint32_t mask_32bit(uint32_t x){
return x&0xffffffff;
}
static const uint32_t add_constant[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
static const uint32_t initial_message_digest[8] = {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
};
inline uint32_t ch(uint32_t x, uint32_t y, uint32_t z){
return (x&y)^((~x)&z);
}
inline uint32_t maj(uint32_t x, uint32_t y, uint32_t z){
return (x&y)^(x&z)^(y&z);
}
inline uint32_t rotr(uint32_t x, std::size_t n){
assert(n < 32);
return mask_32bit((x>>n)|(x<<(32-n)));
}
inline uint32_t bsig0(uint32_t x){
return rotr(x, 2)^rotr(x, 13)^rotr(x, 22);
}
inline uint32_t bsig1(uint32_t x){
return rotr(x, 6)^rotr(x, 11)^rotr(x, 25);
}
inline uint32_t shr(uint32_t x, std::size_t n){
assert(n < 32);
return x >> n;
}
inline uint32_t ssig0(uint32_t x){
return rotr(x, 7)^rotr(x, 18)^shr(x, 3);
}
inline uint32_t ssig1(uint32_t x){
return rotr(x, 17)^rotr(x, 19)^shr(x, 10);
}
template<typename RaIter1, typename RaIter2>
void hash256_block(RaIter1 message_digest, RaIter2 first, RaIter2 last){
(void)last; // FIXME: check this is valid
uint32_t w[64];
std::fill(w, w+64, 0);
for(std::size_t i = 0; i < 16; ++i){
w[i] = (static_cast<uint32_t>(mask_8bit(*(first+i*4)))<<24)
|(static_cast<uint32_t>(mask_8bit(*(first+i*4+1)))<<16)
|(static_cast<uint32_t>(mask_8bit(*(first+i*4+2)))<<8)
|(static_cast<uint32_t>(mask_8bit(*(first+i*4+3))));
}
for(std::size_t i = 16; i < 64; ++i){
w[i] = mask_32bit(ssig1(w[i-2])+w[i-7]+ssig0(w[i-15])+w[i-16]);
}
uint32_t a = *message_digest;
uint32_t b = *(message_digest+1);
uint32_t c = *(message_digest+2);
uint32_t d = *(message_digest+3);
uint32_t e = *(message_digest+4);
uint32_t f = *(message_digest+5);
uint32_t g = *(message_digest+6);
uint32_t h = *(message_digest+7);
for(std::size_t i = 0; i < 64; ++i){
uint32_t temp1 = h+bsig1(e)+ch(e,f,g)+add_constant[i]+w[i];
uint32_t temp2 = bsig0(a)+maj(a,b,c);
h = g;
g = f;
f = e;
e = mask_32bit(d+temp1);
d = c;
c = b;
b = a;
a = mask_32bit(temp1+temp2);
}
*message_digest += a;
*(message_digest+1) += b;
*(message_digest+2) += c;
*(message_digest+3) += d;
*(message_digest+4) += e;
*(message_digest+5) += f;
*(message_digest+6) += g;
*(message_digest+7) += h;
for(std::size_t i = 0; i < 8; ++i){
*(message_digest+i) = mask_32bit(*(message_digest+i));
}
}
}//namespace detail
template<typename InIter>
void output_hex(InIter first, InIter last, std::ostream& os){
os.setf(std::ios::hex, std::ios::basefield);
while(first != last){
os.width(2);
os.fill('0');
os << static_cast<unsigned int>(*first);
++first;
}
os.setf(std::ios::dec, std::ios::basefield);
}
template<typename InIter>
void bytes_to_hex_string(InIter first, InIter last, std::string& hex_str){
std::ostringstream oss;
output_hex(first, last, oss);
hex_str.assign(oss.str());
}
template<typename InContainer>
void bytes_to_hex_string(const InContainer& bytes, std::string& hex_str){
bytes_to_hex_string(bytes.begin(), bytes.end(), hex_str);
}
template<typename InIter>
std::string bytes_to_hex_string(InIter first, InIter last){
std::string hex_str;
bytes_to_hex_string(first, last, hex_str);
return hex_str;
}
template<typename InContainer>
std::string bytes_to_hex_string(const InContainer& bytes){
std::string hex_str;
bytes_to_hex_string(bytes, hex_str);
return hex_str;
}
class hash256_one_by_one {
public:
hash256_one_by_one(){
init();
}
void init(){
buffer_.clear();
std::fill(data_length_digits_, data_length_digits_+4, 0);
std::copy(detail::initial_message_digest, detail::initial_message_digest+8, h_);
}
template<typename RaIter>
void process(RaIter first, RaIter last){
add_to_data_length(std::distance(first, last));
std::copy(first, last, std::back_inserter(buffer_));
std::size_t i = 0;
for(;i+64 <= buffer_.size(); i+=64){
detail::hash256_block(h_, buffer_.begin()+i, buffer_.begin()+i+64);
}
buffer_.erase(buffer_.begin(), buffer_.begin()+i);
}
void finish(){
uint8_t temp[64];
std::fill(temp, temp+64, 0);
std::size_t remains = buffer_.size();
std::copy(buffer_.begin(), buffer_.end(), temp);
temp[remains] = 0x80;
if(remains > 55){
std::fill(temp+remains+1, temp+64, 0);
detail::hash256_block(h_, temp, temp+64);
std::fill(temp, temp+64-4, 0);
}
else {
std::fill(temp+remains+1, temp+64-4, 0);
}
write_data_bit_length(&(temp[56]));
detail::hash256_block(h_, temp, temp+64);
}
template<typename OutIter>
void get_hash_bytes(OutIter first, OutIter last)const{
for(const uint32_t* iter = h_; iter != h_+8; ++iter){
for(std::size_t i = 0; i < 4 && first != last; ++i){
*(first++) = detail::mask_8bit(static_cast<uint8_t>((*iter >> (24-8*i))));
}
}
}
private:
void add_to_data_length(uint32_t n) {
uint32_t carry = 0;
data_length_digits_[0] += n;
for(std::size_t i = 0; i < 4; ++i) {
data_length_digits_[i] += carry;
if(data_length_digits_[i] >= 65536u) {
data_length_digits_[i] -= 65536u;
carry = 1;
}
else {
break;
}
}
}
void write_data_bit_length(uint8_t* begin) {
uint32_t data_bit_length_digits[4];
std::copy(
data_length_digits_, data_length_digits_+4,
data_bit_length_digits
);
// convert byte length to bit length (multiply 8 or shift 3 times left)
uint32_t carry = 0;
for(std::size_t i = 0; i < 4; ++i) {
uint32_t before_val = data_bit_length_digits[i];
data_bit_length_digits[i] <<= 3;
data_bit_length_digits[i] |= carry;
data_bit_length_digits[i] &= 65535u;
carry = (before_val >> (16-3)) & 65535u;
}
// write data_bit_length
for(int i = 3; i >= 0; --i) {
(*begin++) = static_cast<uint8_t>(data_bit_length_digits[i] >> 8);
(*begin++) = static_cast<uint8_t>(data_bit_length_digits[i]);
}
}
std::vector<uint8_t> buffer_;
uint32_t data_length_digits_[4]; //as 64bit integer (16bit x 4 integer)
uint32_t h_[8];
};
inline void get_hash_hex_string(const hash256_one_by_one& hasher, std::string& hex_str){
uint8_t hash[32];
hasher.get_hash_bytes(hash, hash+32);
return bytes_to_hex_string(hash, hash+32, hex_str);
}
inline std::string get_hash_hex_string(const hash256_one_by_one& hasher){
std::string hex_str;
get_hash_hex_string(hasher, hex_str);
return hex_str;
}
template<typename RaIter, typename OutIter>
void hash256(RaIter first, RaIter last, OutIter first2, OutIter last2){
hash256_one_by_one hasher;
//hasher.init();
hasher.process(first, last);
hasher.finish();
hasher.get_hash_bytes(first2, last2);
}
template<typename RaIter, typename OutContainer>
void hash256(RaIter first, RaIter last, OutContainer& dst){
hash256(first, last, dst.begin(), dst.end());
}
template<typename RaContainer, typename OutIter>
void hash256(const RaContainer& src, OutIter first, OutIter last){
hash256(src.begin(), src.end(), first, last);
}
template<typename RaContainer, typename OutContainer>
void hash256(const RaContainer& src, OutContainer& dst){
hash256(src.begin(), src.end(), dst.begin(), dst.end());
}
template<typename RaIter>
void hash256_hex_string(RaIter first, RaIter last, std::string& hex_str){
uint8_t hashed[32];
hash256(first, last, hashed, hashed+32);
std::ostringstream oss;
output_hex(hashed, hashed+32, oss);
hex_str.assign(oss.str());
}
template<typename RaIter>
std::string hash256_hex_string(RaIter first, RaIter last){
std::string hex_str;
hash256_hex_string(first, last, hex_str);
return hex_str;
}
inline void hash256_hex_string(const std::string& src, std::string& hex_str){
hash256_hex_string(src.begin(), src.end(), hex_str);
}
template<typename RaContainer>
void hash256_hex_string(const RaContainer& src, std::string& hex_str){
hash256_hex_string(src.begin(), src.end(), hex_str);
}
template<typename RaContainer>
std::string hash256_hex_string(const RaContainer& src){
return hash256_hex_string(src.begin(), src.end());
}
}//namespace picosha2
#endif //PICOSHA2_H

13054
libethash-cl/CL/cl.hpp

File diff suppressed because it is too large

2
libethash-cl/CMakeLists.txt

@ -23,7 +23,7 @@ include_directories(${CMAKE_CURRENT_BINARY_DIR})
include_directories(${Boost_INCLUDE_DIRS})
include_directories(..)
add_library(${EXECUTABLE} ${SRC_LIST} ${HEADERS})
target_include_directories(${EXECUTABLE} PUBLIC ${OpenCL_INCLUDE_DIR})
target_include_directories(${EXECUTABLE} PUBLIC SYSTEM ${OpenCL_INCLUDE_DIR})
target_link_libraries(${EXECUTABLE} ${OpenCL_LIBRARIES} ethash)
install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )

17
libethash-cl/ethash_cl_miner.h

@ -1,15 +1,24 @@
#pragma once
#define __CL_ENABLE_EXCEPTIONS
#define CL_USE_DEPRECATED_OPENCL_2_0_APIS
#define CL_HPP_TARGET_OPENCL_VERSION 120
#define CL_HPP_MINIMUM_OPENCL_VERSION 110
#define CL_HPP_ENABLE_EXCEPTIONS 1
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wignored-qualifiers"
#pragma GCC diagnostic ignored "-Wignored-attributes"
#endif
#include "CL/cl.hpp"
#if defined(__clang__)
#pragma clang diagnostic pop
#else
#include "CL/cl.hpp"
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#include <time.h>

12
libethash/CMakeLists.txt

@ -25,17 +25,7 @@ else()
list(APPEND FILES io_posix.c)
endif()
if (NOT CRYPTOPP_FOUND)
find_package(CryptoPP 5.6.2)
endif()
if (CRYPTOPP_FOUND)
add_definitions(-DWITH_CRYPTOPP)
include_directories( ${CRYPTOPP_INCLUDE_DIRS} )
list(APPEND FILES sha3_cryptopp.cpp sha3_cryptopp.h)
else()
list(APPEND FILES sha3.c sha3.h)
endif()
list(APPEND FILES sha3.c sha3.h)
add_library(${LIBRARY} ${FILES})

97
libethcore/BlockInfo.cpp

@ -22,10 +22,7 @@
#include <libdevcore/Common.h>
#include <libdevcore/Log.h>
#include <libdevcore/RLP.h>
#include <libdevcore/TrieDB.h>
#include <libdevcore/TrieHash.h>
#include <libethcore/Common.h>
#include <libethcore/Params.h>
#include "EthashAux.h"
#include "Exceptions.h"
#include "BlockInfo.h"
@ -33,6 +30,11 @@ using namespace std;
using namespace dev;
using namespace dev::eth;
namespace
{
h256 const EmptyTrie = sha3(rlp(""));
}
BlockInfo::BlockInfo(): m_timestamp(Invalid256)
{
}
@ -137,92 +139,3 @@ void BlockInfo::populateFromHeader(RLP const& _header, Strictness _s)
if (_s != CheckNothing && m_gasUsed > m_gasLimit)
BOOST_THROW_EXCEPTION(TooMuchGasUsed() << RequirementError(bigint(m_gasLimit), bigint(m_gasUsed)));
}
struct BlockInfoDiagnosticsChannel: public LogChannel { static const char* name() { return EthBlue "" EthWhite ""; } static const int verbosity = 9; };
void BlockInfo::verifyInternals(bytesConstRef _block) const
{
RLP root(_block);
auto txList = root[1];
auto expectedRoot = trieRootOver(txList.itemCount(), [&](unsigned i){ return rlp(i); }, [&](unsigned i){ return txList[i].data().toBytes(); });
clog(BlockInfoDiagnosticsChannel) << "Expected trie root:" << toString(expectedRoot);
if (m_transactionsRoot != expectedRoot)
{
MemoryDB tm;
GenericTrieDB<MemoryDB> transactionsTrie(&tm);
transactionsTrie.init();
vector<bytesConstRef> txs;
for (unsigned i = 0; i < txList.itemCount(); ++i)
{
RLPStream k;
k << i;
transactionsTrie.insert(&k.out(), txList[i].data());
txs.push_back(txList[i].data());
cdebug << toHex(k.out()) << toHex(txList[i].data());
}
cdebug << "trieRootOver" << expectedRoot;
cdebug << "orderedTrieRoot" << orderedTrieRoot(txs);
cdebug << "TrieDB" << transactionsTrie.root();
cdebug << "Contents:";
for (auto const& t: txs)
cdebug << toHex(t);
BOOST_THROW_EXCEPTION(InvalidTransactionsRoot() << Hash256RequirementError(expectedRoot, m_transactionsRoot));
}
clog(BlockInfoDiagnosticsChannel) << "Expected uncle hash:" << toString(sha3(root[2].data()));
if (m_sha3Uncles != sha3(root[2].data()))
BOOST_THROW_EXCEPTION(InvalidUnclesHash() << Hash256RequirementError(sha3(root[2].data()), m_sha3Uncles));
}
void BlockInfo::populateFromParent(BlockInfo const& _parent)
{
m_stateRoot = _parent.stateRoot();
m_number = _parent.m_number + 1;
m_parentHash = _parent.m_hash;
m_gasLimit = _parent.childGasLimit();
m_gasUsed = 0;
m_difficulty = calculateDifficulty(_parent);
}
u256 BlockInfo::childGasLimit(u256 const& _gasFloorTarget) const
{
u256 gasFloorTarget =
_gasFloorTarget == UndefinedU256 ? c_gasFloorTarget : _gasFloorTarget;
if (m_gasLimit < gasFloorTarget)
return min<u256>(gasFloorTarget, m_gasLimit + m_gasLimit / c_gasLimitBoundDivisor - 1);
else
return max<u256>(gasFloorTarget, m_gasLimit - m_gasLimit / c_gasLimitBoundDivisor + 1 + (m_gasUsed * 6 / 5) / c_gasLimitBoundDivisor);
}
u256 BlockInfo::calculateDifficulty(BlockInfo const& _parent) const
{
const unsigned c_expDiffPeriod = 100000;
if (!m_number)
throw GenesisBlockCannotBeCalculated();
u256 o = max<u256>(c_minimumDifficulty, m_timestamp >= _parent.m_timestamp + c_durationLimit ? _parent.m_difficulty - (_parent.m_difficulty / c_difficultyBoundDivisor) : (_parent.m_difficulty + (_parent.m_difficulty / c_difficultyBoundDivisor)));
unsigned periodCount = unsigned(_parent.number() + 1) / c_expDiffPeriod;
if (periodCount > 1)
o = max<u256>(c_minimumDifficulty, o + (u256(1) << (periodCount - 2))); // latter will eventually become huge, so ensure it's a bigint.
return o;
}
void BlockInfo::verifyParent(BlockInfo const& _parent) const
{
// Check timestamp is after previous timestamp.
if (m_parentHash)
{
if (m_timestamp <= _parent.m_timestamp)
BOOST_THROW_EXCEPTION(InvalidTimestamp());
if (m_number != _parent.m_number + 1)
BOOST_THROW_EXCEPTION(InvalidNumber());
}
}

21
libethcore/BlockInfo.h

@ -111,10 +111,6 @@ public:
}
bool operator!=(BlockInfo const& _cmp) const { return !operator==(_cmp); }
void verifyInternals(bytesConstRef _block) const;
void verifyParent(BlockInfo const& _parent) const;
void populateFromParent(BlockInfo const& parent);
u256 calculateDifficulty(BlockInfo const& _parent) const;
u256 childGasLimit(u256 const& _gasFloorTarget = UndefinedU256) const;
h256 const& boundary() const;
@ -210,23 +206,6 @@ public:
populateFromHeader(_bdt == BlockData ? BlockInfo::extractHeader(_data) : RLP(_data), _s, _h);
}
void populateFromParent(BlockHeaderPolished const& _parent)
{
noteDirty();
BlockInfo::m_parentHash = _parent.hash();
BlockInfo::populateFromParent(_parent);
BlockInfoSub::populateFromParent(_parent);
}
// TODO: consider making private.
void verifyParent(BlockHeaderPolished const& _parent)
{
if (BlockInfo::parentHash() && BlockInfo::parentHash() != _parent.hash())
BOOST_THROW_EXCEPTION(InvalidParentHash());
BlockInfo::verifyParent(_parent);
BlockInfoSub::verifyParent(_parent);
}
// deprecated for public API - use constructor.
// TODO: make private.
void populateFromHeader(RLP const& _header, Strictness _s = IgnoreSeal, h256 const& _h = h256())

27
libethcore/CMakeLists.txt

@ -1,36 +1,21 @@
cmake_policy(SET CMP0015 NEW)
set(CMAKE_AUTOMOC OFF)
aux_source_directory(. SRC_LIST)
file(GLOB SOURCES "*.cpp")
file(GLOB HEADERS "*.h")
include_directories(BEFORE ..)
include_directories(${Boost_INCLUDE_DIRS})
if (CPUID_FOUND)
include_directories(${Cpuid_INCLUDE_DIRS})
endif ()
if (ETHASHCUDA)
include_directories(${CUDA_INCLUDE_DIRS})
endif ()
set(EXECUTABLE ethcore)
file(GLOB HEADERS "*.h")
add_library(${EXECUTABLE} ${SRC_LIST} ${HEADERS})
target_link_libraries(${EXECUTABLE} ethash)
add_library(ethcore ${SOURCES} ${HEADERS})
target_link_libraries(ethcore ethash pthread)
if (ETHASHCL)
target_link_libraries(${EXECUTABLE} ethash-cl)
target_link_libraries(ethcore ethash-cl)
endif ()
if (ETHASHCUDA)
target_link_libraries(${EXECUTABLE} ethash-cuda)
target_link_libraries(ethcore ethash-cuda)
endif ()
if (CPUID_FOUND)
target_link_libraries(${EXECUTABLE} ${CPUID_LIBRARIES})
endif ()
install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

143
libethcore/Common.cpp

@ -1,143 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Common.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "Common.h"
#include <boost/algorithm/string/case_conv.hpp>
#include <libdevcore/Base64.h>
#include <libdevcore/Terminal.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/Log.h>
#include <libdevcore/SHA3.h>
#include "Exceptions.h"
#include "Params.h"
#include "BlockInfo.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
namespace dev
{
namespace eth
{
const unsigned c_protocolVersion = 61;
const unsigned c_minorProtocolVersion = 2;
const unsigned c_databaseBaseVersion = 9;
const unsigned c_databaseVersionModifier = 0;
const unsigned c_databaseVersion = c_databaseBaseVersion + (c_databaseVersionModifier << 8) + (23 << 9);
Address toAddress(std::string const& _s)
{
try
{
auto b = fromHex(_s.substr(0, 2) == "0x" ? _s.substr(2) : _s, WhenError::Throw);
if (b.size() == 20)
return Address(b);
}
catch (BadHexCharacter&) {}
BOOST_THROW_EXCEPTION(InvalidAddress());
}
vector<pair<u256, string>> const& units()
{
static const vector<pair<u256, string>> s_units =
{
{exp10<54>(), "Uether"},
{exp10<51>(), "Vether"},
{exp10<48>(), "Dether"},
{exp10<45>(), "Nether"},
{exp10<42>(), "Yether"},
{exp10<39>(), "Zether"},
{exp10<36>(), "Eether"},
{exp10<33>(), "Pether"},
{exp10<30>(), "Tether"},
{exp10<27>(), "Gether"},
{exp10<24>(), "Mether"},
{exp10<21>(), "grand"},
{exp10<18>(), "ether"},
{exp10<15>(), "finney"},
{exp10<12>(), "szabo"},
{exp10<9>(), "Gwei"},
{exp10<6>(), "Mwei"},
{exp10<3>(), "Kwei"},
{exp10<0>(), "wei"}
};
return s_units;
}
std::string formatBalance(bigint const& _b)
{
ostringstream ret;
u256 b;
if (_b < 0)
{
ret << "-";
b = (u256)-_b;
}
else
b = (u256)_b;
if (b > units()[0].first * 1000)
{
ret << (b / units()[0].first) << " " << units()[0].second;
return ret.str();
}
ret << setprecision(5);
for (auto const& i: units())
if (i.first != 1 && b >= i.first * 1)
{
ret << (double(b / (i.first / 1000)) / 1000.0) << " " << i.second;
return ret.str();
}
ret << b << " wei";
return ret.str();
}
static void badBlockInfo(BlockInfo const& _bi, string const& _err)
{
string const c_line = EthReset EthOnMaroon + string(80, ' ') + EthReset;
string const c_border = EthReset EthOnMaroon + string(2, ' ') + EthReset EthMaroonBold;
string const c_space = c_border + string(76, ' ') + c_border + EthReset;
stringstream ss;
ss << c_line << endl;
ss << c_space << endl;
ss << c_border + " Import Failure " + _err + string(max<int>(0, 53 - _err.size()), ' ') + " " + c_border << endl;
ss << c_space << endl;
string bin = toString(_bi.number());
ss << c_border + (" Guru Meditation #" + string(max<int>(0, 8 - bin.size()), '0') + bin + "." + _bi.hash().abridged() + " ") + c_border << endl;
ss << c_space << endl;
ss << c_line;
cwarn << "\n" + ss.str();
}
void badBlock(bytesConstRef _block, string const& _err)
{
BlockInfo bi;
DEV_IGNORE_EXCEPTIONS(bi = BlockInfo(_block, CheckNothing));
badBlockInfo(bi, _err);
}
}
}

175
libethcore/Common.h

@ -34,190 +34,22 @@ namespace dev
namespace eth
{
/// Current protocol version.
extern const unsigned c_protocolVersion;
/// Current minor protocol version.
extern const unsigned c_minorProtocolVersion;
/// Current database version.
extern const unsigned c_databaseVersion;
/// The network id.
enum class Network
{
Olympic = 0,
Frontier = 1,
Turbo = 2
};
extern Network c_network;
Network resetNetwork(Network _n);
/// User-friendly string representation of the amount _b in wei.
std::string formatBalance(bigint const& _b);
/// An Ethereum address: 20 bytes.
/// @NOTE This is not endian-specific; it's just a bunch of bytes.
using Address = h160;
DEV_SIMPLE_EXCEPTION(InvalidAddress);
/// Convert the given string into an address.
Address toAddress(std::string const& _s);
/// Get information concerning the currency denominations.
std::vector<std::pair<u256, std::string>> const& units();
/// The log bloom's size (2048-bit).
using LogBloom = h2048;
/// Many log blooms.
using LogBlooms = std::vector<LogBloom>;
template <size_t n> inline u256 exp10()
{
return exp10<n - 1>() * u256(10);
}
template <> inline u256 exp10<0>()
{
return u256(1);
}
// The various denominations; here for ease of use where needed within code.
static const u256 ether = exp10<18>();
static const u256 finney = exp10<15>();
static const u256 szabo = exp10<12>();
static const u256 shannon = exp10<9>();
static const u256 wei = exp10<0>();
using Nonce = h64;
using BlockNumber = unsigned;
static const BlockNumber LatestBlock = (BlockNumber)-2;
static const BlockNumber PendingBlock = (BlockNumber)-1;
static const h256 LatestBlockHash = h256(2);
static const h256 EarliestBlockHash = h256(1);
static const h256 PendingBlockHash = h256(0);
enum class RelativeBlock: BlockNumber
{
Latest = LatestBlock,
Pending = PendingBlock
};
class Transaction;
struct ImportRoute
{
h256s deadBlocks;
h256s liveBlocks;
std::vector<Transaction> goodTranactions;
};
enum class ImportResult
{
Success = 0,
UnknownParent,
FutureTimeKnown,
FutureTimeUnknown,
AlreadyInChain,
AlreadyKnown,
Malformed,
OverbidGasPrice,
BadChain
};
struct ImportRequirements
{
using value = unsigned;
enum
{
ValidSeal = 1, ///< Validate seal
UncleBasic = 4, ///< Check the basic structure of the uncles.
TransactionBasic = 8, ///< Check the basic structure of the transactions.
UncleSeals = 16, ///< Check the basic structure of the uncles.
TransactionSignatures = 32, ///< Check the basic structure of the transactions.
Parent = 64, ///< Check parent block header.
UncleParent = 128, ///< Check uncle parent block header.
CheckUncles = UncleBasic | UncleSeals, ///< Check uncle seals.
CheckTransactions = TransactionBasic | TransactionSignatures, ///< Check transaction signatures.
OutOfOrderChecks = ValidSeal | CheckUncles | CheckTransactions, ///< Do all checks that can be done independently of prior blocks having been imported.
InOrderChecks = Parent | UncleParent, ///< Do all checks that cannot be done independently of prior blocks having been imported.
Everything = ValidSeal | CheckUncles | CheckTransactions | Parent | UncleParent,
None = 0
};
};
/// Super-duper signal mechanism. TODO: replace with somthing a bit heavier weight.
template<typename... Args> class Signal
{
public:
using Callback = std::function<void(Args...)>;
class HandlerAux
{
friend class Signal;
public:
~HandlerAux() { if (m_s) m_s->m_fire.erase(m_i); }
void reset() { m_s = nullptr; }
void fire(Args const&... _args) { m_h(_args...); }
private:
HandlerAux(unsigned _i, Signal* _s, Callback const& _h): m_i(_i), m_s(_s), m_h(_h) {}
unsigned m_i = 0;
Signal* m_s = nullptr;
Callback m_h;
};
~Signal()
{
for (auto const& h : m_fire)
if (auto l = h.second.lock())
l->reset();
}
std::shared_ptr<HandlerAux> add(Callback const& _h)
{
auto n = m_fire.empty() ? 0 : (m_fire.rbegin()->first + 1);
auto h = std::shared_ptr<HandlerAux>(new HandlerAux(n, this, _h));
m_fire[n] = h;
return h;
}
void operator()(Args const&... _args)
{
for (auto const& f: valuesOf(m_fire))
if (auto h = f.lock())
h->fire(_args...);
}
private:
std::map<unsigned, std::weak_ptr<typename Signal::HandlerAux>> m_fire;
};
template<class... Args> using Handler = std::shared_ptr<typename Signal<Args...>::HandlerAux>;
struct TransactionSkeleton
{
bool creation = false;
Address from;
Address to;
u256 value;
bytes data;
u256 nonce = UndefinedU256;
u256 gas = UndefinedU256;
u256 gasPrice = UndefinedU256;
};
void badBlock(bytesConstRef _header, std::string const& _err);
inline void badBlock(bytes const& _header, std::string const& _err) { badBlock(&_header, _err); }
// TODO: move back into a mining subsystem and have it be accessible from Sealant only via a dynamic_cast.
/**
* @brief Describes the progress of a mining operation.
@ -230,12 +62,5 @@ struct WorkingProgress
uint64_t rate() const { return ms == 0 ? 0 : hashes * 1000 / ms; }
};
/// Import transaction policy
enum class IfDropped
{
Ignore, ///< Don't import transaction that was previously dropped.
Retry ///< Import transaction even if it was dropped before.
};
}
}

196
libethcore/Ethash.cpp

@ -20,33 +20,7 @@
*/
#include "Ethash.h"
#include <boost/detail/endian.hpp>
#include <boost/filesystem.hpp>
#include <chrono>
#include <array>
#include <thread>
#include <thread>
#include <libdevcore/Guards.h>
#include <libdevcore/Log.h>
#include <libdevcore/Common.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/CommonJS.h>
#include <libdevcore/FileSystem.h>
#include <libethash/ethash.h>
#include <libethash/internal.h>
#include "BlockInfo.h"
#include "EthashAux.h"
#include "Exceptions.h"
#include "Farm.h"
#include "Miner.h"
#include "Params.h"
#include "EthashSealEngine.h"
#include "EthashCPUMiner.h"
#include "EthashGPUMiner.h"
#include "EthashCUDAMiner.h"
using namespace std;
using namespace std::chrono;
namespace dev
{
@ -60,175 +34,5 @@ h256 const& Ethash::BlockHeaderRaw::seedHash() const
return m_seedHash;
}
void Ethash::BlockHeaderRaw::populateFromHeader(RLP const& _header, Strictness _s)
{
m_mixHash = _header[BlockInfo::BasicFields].toHash<h256>();
m_nonce = _header[BlockInfo::BasicFields + 1].toHash<h64>();
// check it hashes according to proof of work or that it's the genesis block.
if (_s == CheckEverything && m_parentHash && !verify())
{
InvalidBlockNonce ex;
ex << errinfo_nonce(m_nonce);
ex << errinfo_mixHash(m_mixHash);
ex << errinfo_seedHash(seedHash());
EthashProofOfWork::Result er = EthashAux::eval(seedHash(), hashWithout(), m_nonce);
ex << errinfo_ethashResult(make_tuple(er.value, er.mixHash));
ex << errinfo_hash256(hashWithout());
ex << errinfo_difficulty(m_difficulty);
ex << errinfo_target(boundary());
BOOST_THROW_EXCEPTION(ex);
}
else if (_s == QuickNonce && m_parentHash && !preVerify())
{
InvalidBlockNonce ex;
ex << errinfo_hash256(hashWithout());
ex << errinfo_difficulty(m_difficulty);
ex << errinfo_nonce(m_nonce);
BOOST_THROW_EXCEPTION(ex);
}
if (_s != CheckNothing)
{
if (m_difficulty < c_minimumDifficulty)
BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError(bigint(c_minimumDifficulty), bigint(m_difficulty)) );
if (m_gasLimit < c_minGasLimit)
BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(c_minGasLimit), bigint(m_gasLimit)) );
if (m_number && m_extraData.size() > c_maximumExtraDataSize)
BOOST_THROW_EXCEPTION(ExtraDataTooBig() << RequirementError(bigint(c_maximumExtraDataSize), bigint(m_extraData.size())) << errinfo_extraData(m_extraData));
}
}
void Ethash::BlockHeaderRaw::verifyParent(BlockHeaderRaw const& _parent)
{
// Check difficulty is correct given the two timestamps.
if (m_difficulty != calculateDifficulty(_parent))
BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError((bigint)calculateDifficulty(_parent), (bigint)m_difficulty));
if (m_gasLimit < c_minGasLimit ||
m_gasLimit <= _parent.m_gasLimit - _parent.m_gasLimit / c_gasLimitBoundDivisor ||
m_gasLimit >= _parent.m_gasLimit + _parent.m_gasLimit / c_gasLimitBoundDivisor)
BOOST_THROW_EXCEPTION(InvalidGasLimit() << errinfo_min((bigint)(_parent.m_gasLimit - _parent.m_gasLimit / c_gasLimitBoundDivisor)) << errinfo_got((bigint)m_gasLimit) << errinfo_max((bigint)(_parent.m_gasLimit + _parent.m_gasLimit / c_gasLimitBoundDivisor)));
}
void Ethash::BlockHeaderRaw::populateFromParent(BlockHeaderRaw const& _parent)
{
(void)_parent;
}
bool Ethash::BlockHeaderRaw::preVerify() const
{
if (m_number >= ETHASH_EPOCH_LENGTH * 2048)
return false;
bool ret = !!ethash_quick_check_difficulty(
(ethash_h256_t const*)hashWithout().data(),
(uint64_t)(u64)m_nonce,
(ethash_h256_t const*)m_mixHash.data(),
(ethash_h256_t const*)boundary().data());
return ret;
}
bool Ethash::BlockHeaderRaw::verify() const
{
bool pre = preVerify();
#if !ETH_DEBUG
if (!pre)
{
cwarn << "Fail on preVerify";
return false;
}
#endif
auto result = EthashAux::eval(seedHash(), hashWithout(), m_nonce);
bool slow = result.value <= boundary() && result.mixHash == m_mixHash;
// cdebug << (slow ? "VERIFY" : "VERYBAD");
// cdebug << result.value.hex() << _header.boundary().hex();
// cdebug << result.mixHash.hex() << _header.mixHash.hex();
#if ETH_DEBUG || !ETH_TRUE
if (!pre && slow)
{
cwarn << "WARNING: evaluated result gives true whereas ethash_quick_check_difficulty gives false.";
cwarn << "headerHash:" << hashWithout();
cwarn << "nonce:" << m_nonce;
cwarn << "mixHash:" << m_mixHash;
cwarn << "difficulty:" << m_difficulty;
cwarn << "boundary:" << boundary();
cwarn << "result.value:" << result.value;
cwarn << "result.mixHash:" << result.mixHash;
}
#endif
return slow;
}
void Ethash::BlockHeaderRaw::prep(std::function<int(unsigned)> const& _f) const
{
EthashAux::full(seedHash(), true, _f);
}
StringHashMap Ethash::BlockHeaderRaw::jsInfo() const
{
return { { "nonce", toJS(m_nonce) }, { "seedHash", toJS(seedHash()) }, { "mixHash", toJS(m_mixHash) } };
}
void Ethash::manuallySetWork(SealEngineFace* _engine, BlockHeader const& _work)
{
// set m_sealing to the current problem.
if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine))
e->m_sealing = _work;
}
void Ethash::manuallySubmitWork(SealEngineFace* _engine, h256 const& _mixHash, Nonce _nonce)
{
if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine))
{
// Go via the farm since the handler function object is stored as a local within the Farm's lambda.
// Has the side effect of stopping local workers, which is good, as long as it only does it for
// valid submissions.
static_cast<GenericFarmFace<EthashProofOfWork>&>(e->m_farm).submitProof(EthashProofOfWork::Solution{_nonce, _mixHash}, nullptr);
}
}
bool Ethash::isWorking(SealEngineFace* _engine)
{
if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine))
return e->m_farm.isMining();
return false;
}
WorkingProgress Ethash::workingProgress(SealEngineFace* _engine)
{
if (EthashSealEngine* e = dynamic_cast<EthashSealEngine*>(_engine))
return e->m_farm.miningProgress();
return WorkingProgress();
}
SealEngineFace* Ethash::createSealEngine()
{
return new EthashSealEngine;
}
std::string Ethash::name()
{
return "Ethash";
}
unsigned Ethash::revision()
{
return ETHASH_REVISION;
}
void Ethash::ensurePrecomputed(unsigned _number)
{
if (_number % ETHASH_EPOCH_LENGTH > ETHASH_EPOCH_LENGTH * 9 / 10)
// 90% of the way to the new epoch
EthashAux::computeFull(EthashAux::seedHash(_number + ETHASH_EPOCH_LENGTH), true);
}
}
}

32
libethcore/Ethash.h

@ -26,11 +26,9 @@
#include <chrono>
#include <thread>
#include <cstdint>
#include <libdevcore/CommonIO.h>
#include "Common.h"
#include "Miner.h"
#include "Farm.h"
#include "Sealer.h"
class ethash_cl_miner;
class ethash_cuda_miner;
@ -51,60 +49,30 @@ class EthashCUDAHook;
class Ethash
{
public:
static std::string name();
static unsigned revision();
static SealEngineFace* createSealEngine();
using Nonce = h64;
static void manuallySubmitWork(SealEngineFace* _engine, h256 const& _mixHash, Nonce _nonce);
static bool isWorking(SealEngineFace* _engine);
static WorkingProgress workingProgress(SealEngineFace* _engine);
class BlockHeaderRaw: public BlockInfo
{
friend class EthashSealEngine;
public:
static const unsigned SealFields = 2;
bool verify() const;
bool preVerify() const;
void prep(std::function<int(unsigned)> const& _f = std::function<int(unsigned)>()) const;
h256 const& seedHash() const;
Nonce const& nonce() const { return m_nonce; }
h256 const& mixHash() const { return m_mixHash; }
void setNonce(Nonce const& _n) { m_nonce = _n; noteDirty(); }
void setMixHash(h256 const& _n) { m_mixHash = _n; noteDirty(); }
StringHashMap jsInfo() const;
protected:
BlockHeaderRaw() = default;
BlockHeaderRaw(BlockInfo const& _bi): BlockInfo(_bi) {}
void populateFromHeader(RLP const& _header, Strictness _s);
void populateFromParent(BlockHeaderRaw const& _parent);
void verifyParent(BlockHeaderRaw const& _parent);
void clear() { m_mixHash = h256(); m_nonce = Nonce(); }
void noteDirty() const { m_seedHash = h256(); }
void streamRLPFields(RLPStream& _s) const { _s << m_mixHash << m_nonce; }
private:
Nonce m_nonce;
h256 m_mixHash;
mutable h256 m_seedHash;
mutable h256 m_hash; ///< SHA3 hash of the block header! Not serialised.
};
using BlockHeader = BlockHeaderPolished<BlockHeaderRaw>;
static void manuallySetWork(SealEngineFace* _engine, BlockHeader const& _work);
// TODO: Move elsewhere (EthashAux?)
static void ensurePrecomputed(unsigned _number);
};
}

1
libethcore/EthashAux.cpp

@ -30,7 +30,6 @@
#include <libdevcore/Guards.h>
#include <libdevcore/Log.h>
#include <libdevcore/SHA3.h>
#include <libdevcore/FileSystem.h>
#include <libethash/internal.h>
#include <libethash/io.h>
#include "BlockInfo.h"

55
libethcore/EthashCPUMiner.cpp

@ -26,34 +26,12 @@
#include <chrono>
#include <boost/algorithm/string.hpp>
#include <random>
#if ETH_CPUID || !ETH_TRUE
#define HAVE_STDINT_H
#include <libcpuid/libcpuid.h>
#endif
using namespace std;
using namespace dev;
using namespace eth;
unsigned EthashCPUMiner::s_numInstances = 0;
#if ETH_CPUID || !ETH_TRUE
static string jsonEncode(map<string, string> const& _m)
{
string ret = "{";
for (auto const& i: _m)
{
string k = boost::replace_all_copy(boost::replace_all_copy(i.first, "\\", "\\\\"), "'", "\\'");
string v = boost::replace_all_copy(boost::replace_all_copy(i.second, "\\", "\\\\"), "'", "\\'");
if (ret.size() > 1)
ret += ", ";
ret += "\"" + k + "\":\"" + v + "\"";
}
return ret + "}";
}
#endif
EthashCPUMiner::EthashCPUMiner(GenericMiner<EthashProofOfWork>::ConstructionInfo const& _ci):
GenericMiner<EthashProofOfWork>(_ci), Worker("miner" + toString(index()))
{
@ -107,36 +85,5 @@ void EthashCPUMiner::workLoop()
std::string EthashCPUMiner::platformInfo()
{
string baseline = toString(std::thread::hardware_concurrency()) + "-thread CPU";
#if ETH_CPUID || !ETH_TRUE
if (!cpuid_present())
return baseline;
struct cpu_raw_data_t raw;
struct cpu_id_t data;
if (cpuid_get_raw_data(&raw) < 0)
return baseline;
if (cpu_identify(&raw, &data) < 0)
return baseline;
map<string, string> m;
m["vendor"] = data.vendor_str;
m["codename"] = data.cpu_codename;
m["brand"] = data.brand_str;
m["L1 cache"] = toString(data.l1_data_cache);
m["L2 cache"] = toString(data.l2_cache);
m["L3 cache"] = toString(data.l3_cache);
m["cores"] = toString(data.num_cores);
m["threads"] = toString(data.num_logical_cpus);
m["clocknominal"] = toString(cpu_clock_by_os());
m["clocktested"] = toString(cpu_clock_measure(200, 0));
/*
printf(" MMX : %s\n", data.flags[CPU_FEATURE_MMX] ? "present" : "absent");
printf(" MMX-extended: %s\n", data.flags[CPU_FEATURE_MMXEXT] ? "present" : "absent");
printf(" SSE : %s\n", data.flags[CPU_FEATURE_SSE] ? "present" : "absent");
printf(" SSE2 : %s\n", data.flags[CPU_FEATURE_SSE2] ? "present" : "absent");
printf(" 3DNow! : %s\n", data.flags[CPU_FEATURE_3DNOW] ? "present" : "absent");
*/
return jsonEncode(m);
#else
return baseline;
#endif
return toString(std::thread::hardware_concurrency()) + "-thread CPU";
}

2
libethcore/EthashCUDAMiner.cpp

@ -21,7 +21,7 @@ along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
* Determines the PoW algorithm.
*/
#if ETH_ETHASHCUDA || !ETH_TRUE
#if ETH_ETHASHCUDA
#if defined(WIN32)
#include <Windows.h>

2
libethcore/EthashCUDAMiner.h

@ -22,7 +22,7 @@ along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#if ETH_ETHASHCUDA || !ETH_TRUE
#if ETH_ETHASHCUDA
#include "libdevcore/Worker.h"
#include "EthashAux.h"

2
libethcore/EthashGPUMiner.cpp

@ -21,7 +21,7 @@
* Determines the PoW algorithm.
*/
#if ETH_ETHASHCL || !ETH_TRUE
#if ETH_ETHASHCL
#include "EthashGPUMiner.h"
#include <thread>

2
libethcore/EthashGPUMiner.h

@ -22,7 +22,7 @@
*/
#pragma once
#if ETH_ETHASHCL || !ETH_TRUE
#if ETH_ETHASHCL
#include "libdevcore/Worker.h"
#include "EthashAux.h"

27
libethcore/EthashSealEngine.cpp

@ -54,30 +54,3 @@ strings EthashSealEngine::sealers() const
#endif
};
}
void EthashSealEngine::generateSeal(BlockInfo const& _bi)
{
m_sealing = Ethash::BlockHeader(_bi);
m_farm.setWork(m_sealing);
m_farm.start(m_sealer, false);
m_farm.setWork(m_sealing); // TODO: take out one before or one after...
bytes shouldPrecompute = option("precomputeDAG");
if (!shouldPrecompute.empty() && shouldPrecompute[0] == 1)
Ethash::ensurePrecomputed((unsigned)_bi.number());
}
void EthashSealEngine::onSealGenerated(std::function<void(bytes const&)> const& _f)
{
m_farm.onSolutionFound([=](EthashProofOfWork::Solution const& sol)
{
// cdebug << m_farm.work().seedHash << m_farm.work().headerHash << sol.nonce << EthashAux::eval(m_farm.work().seedHash, m_farm.work().headerHash, sol.nonce).value;
m_sealing.m_mixHash = sol.mixHash;
m_sealing.m_nonce = sol.nonce;
if (!m_sealing.preVerify())
return false;
RLPStream ret;
m_sealing.streamRLP(ret);
_f(ret.out());
return true;
});
}

12
libethcore/EthashSealEngine.h

@ -23,7 +23,6 @@
#pragma once
#include "Sealer.h"
#include "Ethash.h"
#include "EthashAux.h"
@ -32,24 +31,17 @@ namespace dev
namespace eth
{
class EthashSealEngine: public SealEngineBase<Ethash>
class EthashSealEngine
{
friend class Ethash;
public:
EthashSealEngine();
strings sealers() const override;
void setSealer(std::string const& _sealer) override { m_sealer = _sealer; }
void cancelGeneration() override { m_farm.stop(); }
void generateSeal(BlockInfo const& _bi) override;
void onSealGenerated(std::function<void(bytes const&)> const& _f) override;
strings sealers() const;
private:
bool m_opencl = false;
eth::GenericFarm<EthashProofOfWork> m_farm;
std::string m_sealer = "cpu";
Ethash::BlockHeader m_sealing;
};
}

6
libethcore/Miner.h

@ -165,10 +165,8 @@ public:
}
if (!!_work)
{
DEV_TIMED_ABOVE("pause", 250)
pause();
DEV_TIMED_ABOVE("kickOff", 250)
kickOff();
pause();
kickOff();
}
else if (!_work && !!old)
pause();

75
libethcore/Params.cpp

@ -1,75 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Params.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "Params.h"
#include "Common.h"
using namespace std;
namespace dev
{
namespace eth
{
//--- BEGIN: AUTOGENERATED FROM github.com/ethereum/common/params.json
u256 c_maximumExtraDataSize;
u256 c_minGasLimit;
u256 c_gasLimitBoundDivisor;
u256 c_minimumDifficulty;
u256 c_difficultyBoundDivisor;
u256 c_durationLimit;
u256 c_blockReward;
u256 c_gasFloorTarget;
//--- END: AUTOGENERATED FROM /feeStructure.json
#if ETH_FRONTIER
Network c_network = resetNetwork(Network::Frontier);
#else
Network c_network = resetNetwork(Network::Olympic);
#endif
Network resetNetwork(Network _n)
{
c_network = _n;
c_maximumExtraDataSize = c_network == Network::Olympic ? 1024 : 32;
switch(_n)
{
case Network::Turbo:
c_minGasLimit = 100000000;
break;
case Network::Olympic:
c_minGasLimit = 125000;
break;
case Network::Frontier:
c_minGasLimit = 5000;
break;
}
c_gasFloorTarget = 3141592;
c_gasLimitBoundDivisor = 1024;
c_minimumDifficulty = 131072;
c_difficultyBoundDivisor = 2048;
c_durationLimit = c_network == Network::Turbo ? 2 : c_network == Network::Olympic ? 8 : 13;
c_blockReward = c_network == Network::Olympic ? (1500 * finney) : (5 * ether);
return _n;
}
}
}

43
libethcore/Params.h

@ -1,43 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Params.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
#include <libdevcore/Common.h>
namespace dev
{
namespace eth
{
//--- BEGIN: AUTOGENERATED FROM /feeStructure.json
extern u256 c_minGasLimit;
extern u256 c_gasLimitBoundDivisor;
extern u256 c_minimumDifficulty;
extern u256 c_difficultyBoundDivisor;
extern u256 c_durationLimit;
extern u256 c_maximumExtraDataSize;
extern u256 c_blockReward;
extern u256 c_gasFloorTarget;
//--- END: AUTOGENERATED FROM /feeStructure.json
}
}

26
libethcore/Sealer.cpp

@ -1,26 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Sealer.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "Sealer.h"
using namespace std;
using namespace dev;
using namespace eth;

77
libethcore/Sealer.h

@ -1,77 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Sealer.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*
* Determines the PoW algorithm.
*/
#pragma once
#include <functional>
#include <libdevcore/Guards.h>
#include <libdevcore/RLP.h>
#include "Common.h"
namespace dev
{
namespace eth
{
class BlockInfo;
class SealEngineFace
{
public:
virtual ~SealEngineFace() {}
virtual std::string name() const = 0;
virtual unsigned revision() const = 0;
virtual unsigned sealFields() const = 0;
virtual bytes sealRLP() const = 0;
bytes option(std::string const& _name) const { Guard l(x_options); return m_options.count(_name) ? m_options.at(_name) : bytes(); }
bool setOption(std::string const& _name, bytes const& _value) { Guard l(x_options); try { if (onOptionChanging(_name, _value)) { m_options[_name] = _value; return true; } } catch (...) {} return false; }
virtual strings sealers() const { return { "default" }; }
virtual void setSealer(std::string const&) {}
virtual void generateSeal(BlockInfo const& _bi) = 0;
virtual void onSealGenerated(std::function<void(bytes const& s)> const& _f) = 0;
virtual void cancelGeneration() {}
protected:
virtual bool onOptionChanging(std::string const&, bytes const&) { return true; }
void injectOption(std::string const& _name, bytes const& _value) { Guard l(x_options); m_options[_name] = _value; }
private:
mutable Mutex x_options;
std::unordered_map<std::string, bytes> m_options;
};
template <class Sealer>
class SealEngineBase: public SealEngineFace
{
public:
std::string name() const override { return Sealer::name(); }
unsigned revision() const override { return Sealer::revision(); }
unsigned sealFields() const override { return Sealer::BlockHeader::SealFields; }
bytes sealRLP() const override { RLPStream s(sealFields()); s.appendRaw(typename Sealer::BlockHeader().sealFieldsRLP(), sealFields()); return s.out(); }
};
}
}

4
libstratum/CMakeLists.txt

@ -9,7 +9,7 @@ include_directories(${JSONCPP_INCLUDE_DIRS})
file(GLOB HEADERS "*.h")
add_library(${EXECUTABLE} ${SRC_LIST} ${HEADERS})
target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY} ${Boost_THREAD_LIBRARY} ${Boost_REGEX_LIBRARY})
target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY} ${Boost_THREAD_LIBRARY} ${Boost_REGEX_LIBRARY} pthread)
install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

1
libstratum/EthStratumClient.cpp

@ -395,7 +395,6 @@ void EthStratumClient::processReponse(Json::Value& responseObject)
cnote << "Received new job #" + job;
h256 seedHash = h256(sSeedHash);
h256 headerHash = h256(sHeaderHash);
m_previous.headerHash = m_current.headerHash;
m_previous.seedHash = m_current.seedHash;

1
libstratum/EthStratumClientV2.cpp

@ -347,7 +347,6 @@ void EthStratumClientV2::processReponse(Json::Value& responseObject)
cnote << "Received new job #" + job;
h256 seedHash = h256(sSeedHash);
h256 headerHash = h256(sHeaderHash);
m_previous.headerHash = m_current.headerHash;
m_previous.seedHash = m_current.seedHash;

Loading…
Cancel
Save