Browse Source

Merge branch 'develop' of https://github.com/ethereum/cpp-ethereum into mix_ux

cl-refactor
arkpar 10 years ago
parent
commit
7f1c21bad1
  1. 19
      CMakeLists.txt
  2. 2
      alethzero/CMakeLists.txt
  3. 12
      alethzero/MainWin.cpp
  4. 161
      cmake/CMakeParseArguments.cmake
  5. 0
      cmake/EthCompilerSettings.cmake
  6. 23
      cmake/EthDependencies.cmake
  7. 21
      cmake/EthExecutableHelper.cmake
  8. 1
      cmake/FindCURL.cmake
  9. 33
      cmake/FindCpuid.cmake
  10. 1
      cmake/FindJsoncpp.cmake
  11. 1
      cmake/FindLevelDB.cmake
  12. 16
      cmake/FindMHD.cmake
  13. 136
      cmake/FindOpenCL.cmake
  14. 382
      cmake/FindPackageHandleStandardArgs.cmake
  15. 57
      cmake/FindPackageMessage.cmake
  16. 1
      cmake/Findjson_rpc_cpp.cmake
  17. 18
      cmake/scripts/copydlls.cmake
  18. 3
      eth/CMakeLists.txt
  19. 38
      eth/Farm.h
  20. 28
      eth/PhoneHome.h
  21. 4
      eth/farm.json
  22. 291
      eth/main.cpp
  23. 3
      eth/phonehome.json
  24. 2
      ethrpctest/CMakeLists.txt
  25. 25
      extdep/CMakeLists.txt
  26. 32
      extdep/getstuff.bat
  27. 2
      libdevcore/Common.cpp
  28. 52
      libethash-cl/CMakeLists.txt
  29. 38
      libethash-cl/ethash_cl_miner.cpp
  30. 12
      libethash-cl/ethash_cl_miner.h
  31. 16
      libethcore/CMakeLists.txt
  32. 11
      libethcore/Common.h
  33. 66
      libethcore/Ethash.cpp
  34. 6
      libethcore/Ethash.h
  35. 7
      libethcore/Miner.h
  36. 12
      libethereum/BlockChain.cpp
  37. 10
      libethereum/BlockChain.h
  38. 4
      libethereum/CMakeLists.txt
  39. 11
      libethereum/ClientBase.cpp
  40. 2
      libethereum/ClientBase.h
  41. 9
      libethereum/DownloadMan.h
  42. 9
      libethereum/EthereumHost.cpp
  43. 26
      libethereum/Farm.h
  44. 2
      libethereum/Interface.h
  45. 14
      libethereum/State.cpp
  46. 6
      libethereum/State.h
  47. 12
      libjsqrc/ethereumjs/README.md
  48. 12
      libjsqrc/ethereumjs/bower.json
  49. 242
      libjsqrc/ethereumjs/dist/web3-light.js
  50. 18
      libjsqrc/ethereumjs/dist/web3-light.js.map
  51. 2
      libjsqrc/ethereumjs/dist/web3-light.min.js
  52. 4095
      libjsqrc/ethereumjs/dist/web3.js
  53. 24
      libjsqrc/ethereumjs/dist/web3.js.map
  54. 4
      libjsqrc/ethereumjs/dist/web3.min.js
  55. 13
      libjsqrc/ethereumjs/index.js
  56. 23
      libjsqrc/ethereumjs/lib/solidity/abi.js
  57. 68
      libjsqrc/ethereumjs/lib/solidity/utils.js
  58. 46
      libjsqrc/ethereumjs/lib/utils/utils.js
  59. 2
      libjsqrc/ethereumjs/lib/version.json
  60. 2
      libjsqrc/ethereumjs/lib/web3.js
  61. 28
      libjsqrc/ethereumjs/lib/web3/contract.js
  62. 8
      libjsqrc/ethereumjs/lib/web3/eth.js
  63. 2
      libjsqrc/ethereumjs/package.js
  64. 8
      libjsqrc/ethereumjs/package.json
  65. 106
      libjsqrc/ethereumjs/test/abi.formatConstructorParams.js
  66. 11
      libjsqrc/ethereumjs/test/abi.inputParser.js
  67. 2
      libjsqrc/ethereumjs/test/utils.filters.js
  68. 2
      libjsqrc/ethereumjs/test/utils.isAddress.js
  69. 23
      libjsqrc/ethereumjs/test/utils.isStrictAddress.js
  70. 49
      libjsqrc/ethereumjs/test/web3.eth.contract.js
  71. 39
      libjsqrc/ethereumjs/test/web3.eth.gasPrice.js
  72. 6
      libjsqrc/ethereumjs/test/web3.eth.getUncle.js
  73. 2
      libp2p/Common.h
  74. 2
      libp2p/Network.cpp
  75. 11
      libp2p/NodeTable.cpp
  76. 1
      libp2p/Session.cpp
  77. 2
      libp2p/Session.h
  78. 23
      libweb3jsonrpc/WebThreeStubServerBase.cpp
  79. 6
      mix/MixClient.cpp
  80. 1
      mix/MixClient.h
  81. 27
      test/net.cpp
  82. 2
      third/CMakeLists.txt

19
CMakeLists.txt

@ -63,6 +63,14 @@ function(configureProject)
add_definitions(-DETH_GUI)
endif()
if (CPUID_FOUND)
add_definitions(-DETH_CPUID)
endif()
if (CURL_FOUND)
add_definitions(-DETH_CURL)
endif()
add_definitions(-DETH_TRUE)
endfunction()
@ -149,6 +157,7 @@ else ()
endif ()
# Backwards compatibility
if (HEADLESS)
message("*** WARNING: -DHEADLESS=1 option is DEPRECATED! Use -DBUNDLE=minimal or -DGUI=0")
set(BUNDLE "minimal")
endif ()
@ -271,8 +280,6 @@ elseif (BUNDLE STREQUAL "user")
set(TESTS OFF)
endif ()
configureProject()
# Default CMAKE_BUILD_TYPE to "Release".
set(CMAKE_BUILD_TYPE CACHE STRING "Release")
if ("x${CMAKE_BUILD_TYPE}" STREQUAL "x")
@ -289,6 +296,10 @@ if ("x${TARGET_PLATFORM}" STREQUAL "x")
endif ()
endif ()
include(EthDependencies)
configureProject()
message("------------------------------------------------------------------------")
message("-- CMake Version ${CMAKE_VERSION}")
message("-- CMAKE_BUILD_TYPE Build type ${CMAKE_BUILD_TYPE}")
@ -296,6 +307,8 @@ message("-- TARGET_PLATFORM Target platform ${TARGET_P
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}")
@ -321,9 +334,7 @@ endif ()
include(EthCompilerSettings)
message("-- CXXFLAGS: ${CMAKE_CXX_FLAGS}")
# this must be an include, as a function it would mess up with variable scope!
include(EthDependencies)
include(EthExecutableHelper)
createBuildInfo()

2
alethzero/CMakeLists.txt

@ -64,5 +64,5 @@ if (SERPENT)
endif()
# eth_install_executable is defined in cmake/EthExecutableHelper.cmake
eth_install_executable(${EXECUTABLE} DLLS ${MHD_DLL_RELEASE})
eth_install_executable(${EXECUTABLE} DLLS MHD_DLLS)

12
alethzero/MainWin.cpp

@ -890,12 +890,16 @@ void Main::on_usePrivate_triggered()
{
m_privateChain = QInputDialog::getText(this, "Enter Name", "Enter the name of your private chain", QLineEdit::Normal, QString("NewChain-%1").arg(time(0)));
if (m_privateChain.isEmpty())
ui->usePrivate->setChecked(false);
{
if (ui->usePrivate->isChecked())
ui->usePrivate->setChecked(false);
else
// was cancelled.
return;
}
}
else
{
m_privateChain.clear();
}
on_killBlockchain_triggered();
}
@ -1027,7 +1031,7 @@ void Main::refreshNetwork()
.arg(sessions[i.id] = QString::fromStdString(i.clientVersion))
.arg(QString::fromStdString(toString(i.caps)))
.arg(QString::fromStdString(toString(i.notes)))
.arg(i.socket)
.arg(i.socketId)
.arg(QString::fromStdString(i.id.abridged())));
auto ns = web3()->nodes();

161
cmake/CMakeParseArguments.cmake

@ -0,0 +1,161 @@
#.rst:
# CMakeParseArguments
# -------------------
#
#
#
# CMAKE_PARSE_ARGUMENTS(<prefix> <options> <one_value_keywords>
# <multi_value_keywords> args...)
#
# CMAKE_PARSE_ARGUMENTS() is intended to be used in macros or functions
# for parsing the arguments given to that macro or function. It
# processes the arguments and defines a set of variables which hold the
# values of the respective options.
#
# The <options> argument contains all options for the respective macro,
# i.e. keywords which can be used when calling the macro without any
# value following, like e.g. the OPTIONAL keyword of the install()
# command.
#
# The <one_value_keywords> argument contains all keywords for this macro
# which are followed by one value, like e.g. DESTINATION keyword of the
# install() command.
#
# The <multi_value_keywords> argument contains all keywords for this
# macro which can be followed by more than one value, like e.g. the
# TARGETS or FILES keywords of the install() command.
#
# When done, CMAKE_PARSE_ARGUMENTS() will have defined for each of the
# keywords listed in <options>, <one_value_keywords> and
# <multi_value_keywords> a variable composed of the given <prefix>
# followed by "_" and the name of the respective keyword. These
# variables will then hold the respective value from the argument list.
# For the <options> keywords this will be TRUE or FALSE.
#
# All remaining arguments are collected in a variable
# <prefix>_UNPARSED_ARGUMENTS, this can be checked afterwards to see
# whether your macro was called with unrecognized parameters.
#
# As an example here a my_install() macro, which takes similar arguments
# as the real install() command:
#
# ::
#
# function(MY_INSTALL)
# set(options OPTIONAL FAST)
# set(oneValueArgs DESTINATION RENAME)
# set(multiValueArgs TARGETS CONFIGURATIONS)
# cmake_parse_arguments(MY_INSTALL "${options}" "${oneValueArgs}"
# "${multiValueArgs}" ${ARGN} )
# ...
#
#
#
# Assume my_install() has been called like this:
#
# ::
#
# my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub)
#
#
#
# After the cmake_parse_arguments() call the macro will have set the
# following variables:
#
# ::
#
# MY_INSTALL_OPTIONAL = TRUE
# MY_INSTALL_FAST = FALSE (this option was not used when calling my_install()
# MY_INSTALL_DESTINATION = "bin"
# MY_INSTALL_RENAME = "" (was not used)
# MY_INSTALL_TARGETS = "foo;bar"
# MY_INSTALL_CONFIGURATIONS = "" (was not used)
# MY_INSTALL_UNPARSED_ARGUMENTS = "blub" (no value expected after "OPTIONAL"
#
#
#
# You can then continue and process these variables.
#
# Keywords terminate lists of values, e.g. if directly after a
# one_value_keyword another recognized keyword follows, this is
# interpreted as the beginning of the new option. E.g.
# my_install(TARGETS foo DESTINATION OPTIONAL) would result in
# MY_INSTALL_DESTINATION set to "OPTIONAL", but MY_INSTALL_DESTINATION
# would be empty and MY_INSTALL_OPTIONAL would be set to TRUE therefor.
#=============================================================================
# Copyright 2010 Alexander Neundorf <neundorf@kde.org>
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
if(__CMAKE_PARSE_ARGUMENTS_INCLUDED)
return()
endif()
set(__CMAKE_PARSE_ARGUMENTS_INCLUDED TRUE)
function(CMAKE_PARSE_ARGUMENTS prefix _optionNames _singleArgNames _multiArgNames)
# first set all result variables to empty/FALSE
foreach(arg_name ${_singleArgNames} ${_multiArgNames})
set(${prefix}_${arg_name})
endforeach()
foreach(option ${_optionNames})
set(${prefix}_${option} FALSE)
endforeach()
set(${prefix}_UNPARSED_ARGUMENTS)
set(insideValues FALSE)
set(currentArgName)
# now iterate over all arguments and fill the result variables
foreach(currentArg ${ARGN})
list(FIND _optionNames "${currentArg}" optionIndex) # ... then this marks the end of the arguments belonging to this keyword
list(FIND _singleArgNames "${currentArg}" singleArgIndex) # ... then this marks the end of the arguments belonging to this keyword
list(FIND _multiArgNames "${currentArg}" multiArgIndex) # ... then this marks the end of the arguments belonging to this keyword
if(${optionIndex} EQUAL -1 AND ${singleArgIndex} EQUAL -1 AND ${multiArgIndex} EQUAL -1)
if(insideValues)
if("${insideValues}" STREQUAL "SINGLE")
set(${prefix}_${currentArgName} ${currentArg})
set(insideValues FALSE)
elseif("${insideValues}" STREQUAL "MULTI")
list(APPEND ${prefix}_${currentArgName} ${currentArg})
endif()
else()
list(APPEND ${prefix}_UNPARSED_ARGUMENTS ${currentArg})
endif()
else()
if(NOT ${optionIndex} EQUAL -1)
set(${prefix}_${currentArg} TRUE)
set(insideValues FALSE)
elseif(NOT ${singleArgIndex} EQUAL -1)
set(currentArgName ${currentArg})
set(${prefix}_${currentArgName})
set(insideValues "SINGLE")
elseif(NOT ${multiArgIndex} EQUAL -1)
set(currentArgName ${currentArg})
set(${prefix}_${currentArgName})
set(insideValues "MULTI")
endif()
endif()
endforeach()
# propagate the result variables to the caller:
foreach(arg_name ${_singleArgNames} ${_multiArgNames} ${_optionNames})
set(${prefix}_${arg_name} ${${prefix}_${arg_name}} PARENT_SCOPE)
endforeach()
set(${prefix}_UNPARSED_ARGUMENTS ${${prefix}_UNPARSED_ARGUMENTS} PARENT_SCOPE)
endfunction()

0
cmake/EthCompilerSettings.cmake

23
cmake/EthDependencies.cmake

@ -4,7 +4,11 @@
# by defining this variable, cmake will look for dependencies first in our own repository before looking in system paths like /usr/local/ ...
# this must be set to point to the same directory as $ETH_DEPENDENCY_INSTALL_DIR in /extdep directory
string(TOLOWER ${CMAKE_SYSTEM_NAME} _system_name)
set (ETH_DEPENDENCY_INSTALL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/extdep/install/${_system_name}")
if (CMAKE_CL_64)
set (ETH_DEPENDENCY_INSTALL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/extdep/install/${_system_name}/x64")
else ()
set (ETH_DEPENDENCY_INSTALL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/extdep/install/${_system_name}/Win32")
endif()
set (CMAKE_PREFIX_PATH ${ETH_DEPENDENCY_INSTALL_DIR})
# setup directory for cmake generated files and include it globally
@ -59,7 +63,7 @@ if (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
@ -86,7 +90,7 @@ endif()
# 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 header: ${GMP_INCLUDE_DIRS}")
message(" - gmp lib : ${GMP_LIBRARIES}")
endif()
@ -96,6 +100,19 @@ 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}")
message(" - opencl lib : ${OpenCL_LIBRARIES}")
endif()
# find location of jsonrpcstub
find_program(ETH_JSON_RPC_STUB jsonrpcstub)
message(" - jsonrpcstub location : ${ETH_JSON_RPC_STUB}")

21
cmake/EthExecutableHelper.cmake

@ -43,6 +43,22 @@ macro(eth_add_executable EXECUTABLE)
endmacro()
macro(eth_copy_dlls EXECUTABLE DLLS)
# dlls must be unsubstitud list variable (without ${}) in format
# optimized;path_to_dll.dll;debug;path_to_dlld.dll
list(GET ${DLLS} 1 DLL_RELEASE)
list(GET ${DLLS} 3 DLL_DEBUG)
add_custom_command(TARGET ${EXECUTABLE}
POST_BUILD
COMMAND ${CMAKE_COMMAND} ARGS
-DDLL_RELEASE="${DLL_RELEASE}"
-DDLL_DEBUG="${DLL_DEBUG}"
-DCONF="$<CONFIGURATION>"
-DDESTINATION="${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}"
-P "${ETH_SCRIPTS_DIR}/copydlls.cmake"
)
endmacro()
#
# this function requires the following variables to be specified:
# ETH_DEPENDENCY_INSTALL_DIR
@ -107,10 +123,7 @@ macro(eth_install_executable EXECUTABLE)
#copy additional dlls
foreach(dll ${ETH_INSTALL_EXECUTABLE_DLLS})
add_custom_command(TARGET ${EXECUTABLE} POST_BUILD
COMMAND ${CMAKE_COMMAND}
ARGS -E copy ${dll} "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}"
)
eth_copy_dlls(${EXECUTABLE} ${dll})
endforeach(dll)
install( TARGETS ${EXECUTABLE} RUNTIME

1
cmake/FindCURL.cmake

@ -30,6 +30,7 @@ set(CURL_LIBRARIES ${CURL_LIBRARY})
# 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(
CURL_LIBRARY_DEBUG
NAMES curld libcurld

33
cmake/FindCpuid.cmake

@ -0,0 +1,33 @@
# 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)

1
cmake/FindJsoncpp.cmake

@ -30,6 +30,7 @@ set(JSONCPP_LIBRARIES ${JSONCPP_LIBRARY})
# 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(
JSONCPP_LIBRARY_DEBUG
NAMES jsoncppd

1
cmake/FindLevelDB.cmake

@ -29,6 +29,7 @@ set(LEVELDB_LIBRARIES ${LEVELDB_LIBRARY})
# 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

16
cmake/FindMHD.cmake

@ -30,18 +30,20 @@ set(MHD_LIBRARIES ${MHD_LIBRARY})
# official MHD project actually uses _d suffix
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
#TODO: place dlls into CMAKE_CFG_INTDIR subfolders
string(REPLACE ".lib" ".dll" MHD_DLL_RELEASE ${MHD_LIBRARY})
string(REPLACE "/lib/" "/bin/" MHD_DLL_RELEASE ${MHD_DLL_RELEASE})
find_library(
MHD_LIBRARY_DEBUG
NAMES microhttpd_d microhttpd-10_d libmicrohttpd_d libmicrohttpd-dll_d
DOC "mhd debug library"
)
# always use release for now
#string(REPLACE ".lib" ".dll" MHD_DLL_DEBUG ${MHD_LIBRARY_DEBUG})
#set(MHD_LIBRARIES optimized ${MHD_LIBRARIES} debug ${MHD_LIBRARY_DEBUG})
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()

136
cmake/FindOpenCL.cmake

@ -0,0 +1,136 @@
#.rst:
# FindOpenCL
# ----------
#
# Try to find OpenCL
#
# Once done this will define::
#
# OpenCL_FOUND - True if OpenCL was found
# OpenCL_INCLUDE_DIRS - include directories for OpenCL
# OpenCL_LIBRARIES - link against this library to use OpenCL
# OpenCL_VERSION_STRING - Highest supported OpenCL version (eg. 1.2)
# OpenCL_VERSION_MAJOR - The major version of the OpenCL implementation
# OpenCL_VERSION_MINOR - The minor version of the OpenCL implementation
#
# The module will also define two cache variables::
#
# OpenCL_INCLUDE_DIR - the OpenCL include directory
# OpenCL_LIBRARY - the path to the OpenCL library
#
#=============================================================================
# Copyright 2014 Matthaeus G. Chajdas
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
function(_FIND_OPENCL_VERSION)
include(CheckSymbolExists)
include(CMakePushCheckState)
set(CMAKE_REQUIRED_QUIET ${OpenCL_FIND_QUIETLY})
CMAKE_PUSH_CHECK_STATE()
foreach(VERSION "2_0" "1_2" "1_1" "1_0")
set(CMAKE_REQUIRED_INCLUDES "${OpenCL_INCLUDE_DIR}")
if(APPLE)
CHECK_SYMBOL_EXISTS(
CL_VERSION_${VERSION}
"${OpenCL_INCLUDE_DIR}/OpenCL/cl.h"
OPENCL_VERSION_${VERSION})
else()
CHECK_SYMBOL_EXISTS(
CL_VERSION_${VERSION}
"${OpenCL_INCLUDE_DIR}/CL/cl.h"
OPENCL_VERSION_${VERSION})
endif()
if(OPENCL_VERSION_${VERSION})
string(REPLACE "_" "." VERSION "${VERSION}")
set(OpenCL_VERSION_STRING ${VERSION} PARENT_SCOPE)
string(REGEX MATCHALL "[0-9]+" version_components "${VERSION}")
list(GET version_components 0 major_version)
list(GET version_components 1 minor_version)
set(OpenCL_VERSION_MAJOR ${major_version} PARENT_SCOPE)
set(OpenCL_VERSION_MINOR ${minor_version} PARENT_SCOPE)
break()
endif()
endforeach()
CMAKE_POP_CHECK_STATE()
endfunction()
find_path(OpenCL_INCLUDE_DIR
NAMES
CL/cl.h OpenCL/cl.h
PATHS
ENV "PROGRAMFILES(X86)"
ENV AMDAPPSDKROOT
ENV INTELOCLSDKROOT
ENV NVSDKCOMPUTE_ROOT
ENV CUDA_PATH
ENV ATISTREAMSDKROOT
PATH_SUFFIXES
include
OpenCL/common/inc
"AMD APP/include")
_FIND_OPENCL_VERSION()
if(WIN32)
if(CMAKE_SIZEOF_VOID_P EQUAL 4)
find_library(OpenCL_LIBRARY
NAMES OpenCL
PATHS
ENV "PROGRAMFILES(X86)"
ENV AMDAPPSDKROOT
ENV INTELOCLSDKROOT
ENV CUDA_PATH
ENV NVSDKCOMPUTE_ROOT
ENV ATISTREAMSDKROOT
PATH_SUFFIXES
"AMD APP/lib/x86"
lib/x86
lib/Win32
OpenCL/common/lib/Win32)
elseif(CMAKE_SIZEOF_VOID_P EQUAL 8)
find_library(OpenCL_LIBRARY
NAMES OpenCL
PATHS
ENV "PROGRAMFILES(X86)"
ENV AMDAPPSDKROOT
ENV INTELOCLSDKROOT
ENV CUDA_PATH
ENV NVSDKCOMPUTE_ROOT
ENV ATISTREAMSDKROOT
PATH_SUFFIXES
"AMD APP/lib/x86_64"
lib/x86_64
lib/x64
OpenCL/common/lib/x64)
endif()
else()
find_library(OpenCL_LIBRARY
NAMES OpenCL)
endif()
set(OpenCL_LIBRARIES ${OpenCL_LIBRARY})
set(OpenCL_INCLUDE_DIRS ${OpenCL_INCLUDE_DIR})
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(
OpenCL
FOUND_VAR OpenCL_FOUND
REQUIRED_VARS OpenCL_LIBRARY OpenCL_INCLUDE_DIR
VERSION_VAR OpenCL_VERSION_STRING)
mark_as_advanced(
OpenCL_INCLUDE_DIR
OpenCL_LIBRARY)

382
cmake/FindPackageHandleStandardArgs.cmake

@ -0,0 +1,382 @@
#.rst:
# FindPackageHandleStandardArgs
# -----------------------------
#
#
#
# FIND_PACKAGE_HANDLE_STANDARD_ARGS(<name> ... )
#
# This function is intended to be used in FindXXX.cmake modules files.
# It handles the REQUIRED, QUIET and version-related arguments to
# find_package(). It also sets the <packagename>_FOUND variable. The
# package is considered found if all variables <var1>... listed contain
# valid results, e.g. valid filepaths.
#
# There are two modes of this function. The first argument in both
# modes is the name of the Find-module where it is called (in original
# casing).
#
# The first simple mode looks like this:
#
# ::
#
# FIND_PACKAGE_HANDLE_STANDARD_ARGS(<name>
# (DEFAULT_MSG|"Custom failure message") <var1>...<varN> )
#
# If the variables <var1> to <varN> are all valid, then
# <UPPERCASED_NAME>_FOUND will be set to TRUE. If DEFAULT_MSG is given
# as second argument, then the function will generate itself useful
# success and error messages. You can also supply a custom error
# message for the failure case. This is not recommended.
#
# The second mode is more powerful and also supports version checking:
#
# ::
#
# FIND_PACKAGE_HANDLE_STANDARD_ARGS(NAME
# [FOUND_VAR <resultVar>]
# [REQUIRED_VARS <var1>...<varN>]
# [VERSION_VAR <versionvar>]
# [HANDLE_COMPONENTS]
# [CONFIG_MODE]
# [FAIL_MESSAGE "Custom failure message"] )
#
# In this mode, the name of the result-variable can be set either to
# either <UPPERCASED_NAME>_FOUND or <OriginalCase_Name>_FOUND using the
# FOUND_VAR option. Other names for the result-variable are not
# allowed. So for a Find-module named FindFooBar.cmake, the two
# possible names are FooBar_FOUND and FOOBAR_FOUND. It is recommended
# to use the original case version. If the FOUND_VAR option is not
# used, the default is <UPPERCASED_NAME>_FOUND.
#
# As in the simple mode, if <var1> through <varN> are all valid,
# <packagename>_FOUND will be set to TRUE. After REQUIRED_VARS the
# variables which are required for this package are listed. Following
# VERSION_VAR the name of the variable can be specified which holds the
# version of the package which has been found. If this is done, this
# version will be checked against the (potentially) specified required
# version used in the find_package() call. The EXACT keyword is also
# handled. The default messages include information about the required
# version and the version which has been actually found, both if the
# version is ok or not. If the package supports components, use the
# HANDLE_COMPONENTS option to enable handling them. In this case,
# find_package_handle_standard_args() will report which components have
# been found and which are missing, and the <packagename>_FOUND variable
# will be set to FALSE if any of the required components (i.e. not the
# ones listed after OPTIONAL_COMPONENTS) are missing. Use the option
# CONFIG_MODE if your FindXXX.cmake module is a wrapper for a
# find_package(... NO_MODULE) call. In this case VERSION_VAR will be
# set to <NAME>_VERSION and the macro will automatically check whether
# the Config module was found. Via FAIL_MESSAGE a custom failure
# message can be specified, if this is not used, the default message
# will be displayed.
#
# Example for mode 1:
#
# ::
#
# find_package_handle_standard_args(LibXml2 DEFAULT_MSG
# LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR)
#
#
#
# LibXml2 is considered to be found, if both LIBXML2_LIBRARY and
# LIBXML2_INCLUDE_DIR are valid. Then also LIBXML2_FOUND is set to
# TRUE. If it is not found and REQUIRED was used, it fails with
# FATAL_ERROR, independent whether QUIET was used or not. If it is
# found, success will be reported, including the content of <var1>. On
# repeated Cmake runs, the same message won't be printed again.
#
# Example for mode 2:
#
# ::
#
# find_package_handle_standard_args(LibXslt
# FOUND_VAR LibXslt_FOUND
# REQUIRED_VARS LibXslt_LIBRARIES LibXslt_INCLUDE_DIRS
# VERSION_VAR LibXslt_VERSION_STRING)
#
# In this case, LibXslt is considered to be found if the variable(s)
# listed after REQUIRED_VAR are all valid, i.e. LibXslt_LIBRARIES and
# LibXslt_INCLUDE_DIRS in this case. The result will then be stored in
# LibXslt_FOUND . Also the version of LibXslt will be checked by using
# the version contained in LibXslt_VERSION_STRING. Since no
# FAIL_MESSAGE is given, the default messages will be printed.
#
# Another example for mode 2:
#
# ::
#
# find_package(Automoc4 QUIET NO_MODULE HINTS /opt/automoc4)
# find_package_handle_standard_args(Automoc4 CONFIG_MODE)
#
# In this case, FindAutmoc4.cmake wraps a call to find_package(Automoc4
# NO_MODULE) and adds an additional search directory for automoc4. Here
# the result will be stored in AUTOMOC4_FOUND. The following
# FIND_PACKAGE_HANDLE_STANDARD_ARGS() call produces a proper
# success/error message.
#=============================================================================
# Copyright 2007-2009 Kitware, Inc.
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageMessage.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/CMakeParseArguments.cmake)
# internal helper macro
macro(_FPHSA_FAILURE_MESSAGE _msg)
if (${_NAME}_FIND_REQUIRED)
message(FATAL_ERROR "${_msg}")
else ()
if (NOT ${_NAME}_FIND_QUIETLY)
message(STATUS "${_msg}")
endif ()
endif ()
endmacro()
# internal helper macro to generate the failure message when used in CONFIG_MODE:
macro(_FPHSA_HANDLE_FAILURE_CONFIG_MODE)
# <name>_CONFIG is set, but FOUND is false, this means that some other of the REQUIRED_VARS was not found:
if(${_NAME}_CONFIG)
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: missing: ${MISSING_VARS} (found ${${_NAME}_CONFIG} ${VERSION_MSG})")
else()
# If _CONSIDERED_CONFIGS is set, the config-file has been found, but no suitable version.
# List them all in the error message:
if(${_NAME}_CONSIDERED_CONFIGS)
set(configsText "")
list(LENGTH ${_NAME}_CONSIDERED_CONFIGS configsCount)
math(EXPR configsCount "${configsCount} - 1")
foreach(currentConfigIndex RANGE ${configsCount})
list(GET ${_NAME}_CONSIDERED_CONFIGS ${currentConfigIndex} filename)
list(GET ${_NAME}_CONSIDERED_VERSIONS ${currentConfigIndex} version)
set(configsText "${configsText} ${filename} (version ${version})\n")
endforeach()
if (${_NAME}_NOT_FOUND_MESSAGE)
set(configsText "${configsText} Reason given by package: ${${_NAME}_NOT_FOUND_MESSAGE}\n")
endif()
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} ${VERSION_MSG}, checked the following files:\n${configsText}")
else()
# Simple case: No Config-file was found at all:
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: found neither ${_NAME}Config.cmake nor ${_NAME_LOWER}-config.cmake ${VERSION_MSG}")
endif()
endif()
endmacro()
function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
# set up the arguments for CMAKE_PARSE_ARGUMENTS and check whether we are in
# new extended or in the "old" mode:
set(options CONFIG_MODE HANDLE_COMPONENTS)
set(oneValueArgs FAIL_MESSAGE VERSION_VAR FOUND_VAR)
set(multiValueArgs REQUIRED_VARS)
set(_KEYWORDS_FOR_EXTENDED_MODE ${options} ${oneValueArgs} ${multiValueArgs} )
list(FIND _KEYWORDS_FOR_EXTENDED_MODE "${_FIRST_ARG}" INDEX)
if(${INDEX} EQUAL -1)
set(FPHSA_FAIL_MESSAGE ${_FIRST_ARG})
set(FPHSA_REQUIRED_VARS ${ARGN})
set(FPHSA_VERSION_VAR)
else()
CMAKE_PARSE_ARGUMENTS(FPHSA "${options}" "${oneValueArgs}" "${multiValueArgs}" ${_FIRST_ARG} ${ARGN})
if(FPHSA_UNPARSED_ARGUMENTS)
message(FATAL_ERROR "Unknown keywords given to FIND_PACKAGE_HANDLE_STANDARD_ARGS(): \"${FPHSA_UNPARSED_ARGUMENTS}\"")
endif()
if(NOT FPHSA_FAIL_MESSAGE)
set(FPHSA_FAIL_MESSAGE "DEFAULT_MSG")
endif()
endif()
# now that we collected all arguments, process them
if("x${FPHSA_FAIL_MESSAGE}" STREQUAL "xDEFAULT_MSG")
set(FPHSA_FAIL_MESSAGE "Could NOT find ${_NAME}")
endif()
# In config-mode, we rely on the variable <package>_CONFIG, which is set by find_package()
# when it successfully found the config-file, including version checking:
if(FPHSA_CONFIG_MODE)
list(INSERT FPHSA_REQUIRED_VARS 0 ${_NAME}_CONFIG)
list(REMOVE_DUPLICATES FPHSA_REQUIRED_VARS)
set(FPHSA_VERSION_VAR ${_NAME}_VERSION)
endif()
if(NOT FPHSA_REQUIRED_VARS)
message(FATAL_ERROR "No REQUIRED_VARS specified for FIND_PACKAGE_HANDLE_STANDARD_ARGS()")
endif()
list(GET FPHSA_REQUIRED_VARS 0 _FIRST_REQUIRED_VAR)
string(TOUPPER ${_NAME} _NAME_UPPER)
string(TOLOWER ${_NAME} _NAME_LOWER)
if(FPHSA_FOUND_VAR)
if(FPHSA_FOUND_VAR MATCHES "^${_NAME}_FOUND$" OR FPHSA_FOUND_VAR MATCHES "^${_NAME_UPPER}_FOUND$")
set(_FOUND_VAR ${FPHSA_FOUND_VAR})
else()
message(FATAL_ERROR "The argument for FOUND_VAR is \"${FPHSA_FOUND_VAR}\", but only \"${_NAME}_FOUND\" and \"${_NAME_UPPER}_FOUND\" are valid names.")
endif()
else()
set(_FOUND_VAR ${_NAME_UPPER}_FOUND)
endif()
# collect all variables which were not found, so they can be printed, so the
# user knows better what went wrong (#6375)
set(MISSING_VARS "")
set(DETAILS "")
# check if all passed variables are valid
unset(${_FOUND_VAR})
foreach(_CURRENT_VAR ${FPHSA_REQUIRED_VARS})
if(NOT ${_CURRENT_VAR})
set(${_FOUND_VAR} FALSE)
set(MISSING_VARS "${MISSING_VARS} ${_CURRENT_VAR}")
else()
set(DETAILS "${DETAILS}[${${_CURRENT_VAR}}]")
endif()
endforeach()
if(NOT "${${_FOUND_VAR}}" STREQUAL "FALSE")
set(${_FOUND_VAR} TRUE)
endif()
# component handling
unset(FOUND_COMPONENTS_MSG)
unset(MISSING_COMPONENTS_MSG)
if(FPHSA_HANDLE_COMPONENTS)
foreach(comp ${${_NAME}_FIND_COMPONENTS})
if(${_NAME}_${comp}_FOUND)
if(NOT DEFINED FOUND_COMPONENTS_MSG)
set(FOUND_COMPONENTS_MSG "found components: ")
endif()
set(FOUND_COMPONENTS_MSG "${FOUND_COMPONENTS_MSG} ${comp}")
else()
if(NOT DEFINED MISSING_COMPONENTS_MSG)
set(MISSING_COMPONENTS_MSG "missing components: ")
endif()
set(MISSING_COMPONENTS_MSG "${MISSING_COMPONENTS_MSG} ${comp}")
if(${_NAME}_FIND_REQUIRED_${comp})
set(${_FOUND_VAR} FALSE)
set(MISSING_VARS "${MISSING_VARS} ${comp}")
endif()
endif()
endforeach()
set(COMPONENT_MSG "${FOUND_COMPONENTS_MSG} ${MISSING_COMPONENTS_MSG}")
set(DETAILS "${DETAILS}[c${COMPONENT_MSG}]")
endif()
# version handling:
set(VERSION_MSG "")
set(VERSION_OK TRUE)
set(VERSION ${${FPHSA_VERSION_VAR}})
# check with DEFINED here as the requested or found version may be "0"
if (DEFINED ${_NAME}_FIND_VERSION)
if(DEFINED ${FPHSA_VERSION_VAR})
if(${_NAME}_FIND_VERSION_EXACT) # exact version required
# count the dots in the version string
string(REGEX REPLACE "[^.]" "" _VERSION_DOTS "${VERSION}")
# add one dot because there is one dot more than there are components
string(LENGTH "${_VERSION_DOTS}." _VERSION_DOTS)
if (_VERSION_DOTS GREATER ${_NAME}_FIND_VERSION_COUNT)
# Because of the C++ implementation of find_package() ${_NAME}_FIND_VERSION_COUNT
# is at most 4 here. Therefore a simple lookup table is used.
if (${_NAME}_FIND_VERSION_COUNT EQUAL 1)
set(_VERSION_REGEX "[^.]*")
elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 2)
set(_VERSION_REGEX "[^.]*\\.[^.]*")
elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 3)
set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*")
else ()
set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*\\.[^.]*")
endif ()
string(REGEX REPLACE "^(${_VERSION_REGEX})\\..*" "\\1" _VERSION_HEAD "${VERSION}")
unset(_VERSION_REGEX)
if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _VERSION_HEAD)
set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
set(VERSION_OK FALSE)
else ()
set(VERSION_MSG "(found suitable exact version \"${VERSION}\")")
endif ()
unset(_VERSION_HEAD)
else ()
if (NOT "${${_NAME}_FIND_VERSION}" VERSION_EQUAL "${VERSION}")
set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
set(VERSION_OK FALSE)
else ()
set(VERSION_MSG "(found suitable exact version \"${VERSION}\")")
endif ()
endif ()
unset(_VERSION_DOTS)
else() # minimum version specified:
if ("${${_NAME}_FIND_VERSION}" VERSION_GREATER "${VERSION}")
set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is at least \"${${_NAME}_FIND_VERSION}\"")
set(VERSION_OK FALSE)
else ()
set(VERSION_MSG "(found suitable version \"${VERSION}\", minimum required is \"${${_NAME}_FIND_VERSION}\")")
endif ()
endif()
else()
# if the package was not found, but a version was given, add that to the output:
if(${_NAME}_FIND_VERSION_EXACT)
set(VERSION_MSG "(Required is exact version \"${${_NAME}_FIND_VERSION}\")")
else()
set(VERSION_MSG "(Required is at least version \"${${_NAME}_FIND_VERSION}\")")
endif()
endif()
else ()
if(VERSION)
set(VERSION_MSG "(found version \"${VERSION}\")")
endif()
endif ()
if(VERSION_OK)
set(DETAILS "${DETAILS}[v${VERSION}(${${_NAME}_FIND_VERSION})]")
else()
set(${_FOUND_VAR} FALSE)
endif()
# print the result:
if (${_FOUND_VAR})
FIND_PACKAGE_MESSAGE(${_NAME} "Found ${_NAME}: ${${_FIRST_REQUIRED_VAR}} ${VERSION_MSG} ${COMPONENT_MSG}" "${DETAILS}")
else ()
if(FPHSA_CONFIG_MODE)
_FPHSA_HANDLE_FAILURE_CONFIG_MODE()
else()
if(NOT VERSION_OK)
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: ${VERSION_MSG} (found ${${_FIRST_REQUIRED_VAR}})")
else()
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} (missing: ${MISSING_VARS}) ${VERSION_MSG}")
endif()
endif()
endif ()
set(${_FOUND_VAR} ${${_FOUND_VAR}} PARENT_SCOPE)
endfunction()

57
cmake/FindPackageMessage.cmake

@ -0,0 +1,57 @@
#.rst:
# FindPackageMessage
# ------------------
#
#
#
# FIND_PACKAGE_MESSAGE(<name> "message for user" "find result details")
#
# This macro is intended to be used in FindXXX.cmake modules files. It
# will print a message once for each unique find result. This is useful
# for telling the user where a package was found. The first argument
# specifies the name (XXX) of the package. The second argument
# specifies the message to display. The third argument lists details
# about the find result so that if they change the message will be
# displayed again. The macro also obeys the QUIET argument to the
# find_package command.
#
# Example:
#
# ::
#
# if(X11_FOUND)
# FIND_PACKAGE_MESSAGE(X11 "Found X11: ${X11_X11_LIB}"
# "[${X11_X11_LIB}][${X11_INCLUDE_DIR}]")
# else()
# ...
# endif()
#=============================================================================
# Copyright 2008-2009 Kitware, Inc.
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
# License text for the above reference.)
function(FIND_PACKAGE_MESSAGE pkg msg details)
# Avoid printing a message repeatedly for the same find result.
if(NOT ${pkg}_FIND_QUIETLY)
string(REPLACE "\n" "" details "${details}")
set(DETAILS_VAR FIND_PACKAGE_MESSAGE_DETAILS_${pkg})
if(NOT "${details}" STREQUAL "${${DETAILS_VAR}}")
# The message has not yet been printed.
message(STATUS "${msg}")
# Save the find details in the cache to avoid printing the same
# message again.
set("${DETAILS_VAR}" "${details}"
CACHE INTERNAL "Details about finding ${pkg}")
endif()
endif()
endfunction()

1
cmake/Findjson_rpc_cpp.cmake

@ -52,6 +52,7 @@ set (JSON_RPC_CPP_CLIENT_LIBRARIES ${JSON_RPC_CPP_COMMON_LIBRARY} ${JSON_RPC_CPP
# 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(
JSON_RPC_CPP_COMMON_LIBRARY_DEBUG
NAMES jsonrpccpp-commond

18
cmake/scripts/copydlls.cmake

@ -0,0 +1,18 @@
# this module expects
# DLLS
# CONF
# DESTINATION
# example usage:
# cmake -DDLL_DEBUG=xd.dll -DDLL_RELEASE=x.dll -DCONFIGURATION=Release -DDESTINATION=dest -P scripts/copydlls.cmake
# this script is created cause we do not know configuration in multiconfiguration generators at cmake configure phase ;)
if ("${CONF}" STREQUAL "Release")
set(DLL ${DLL_RELEASE})
else () # Debug
set(DLL ${DLL_DEBUG})
endif()
execute_process(COMMAND ${CMAKE_COMMAND} -E copy "${DLL}" "${DESTINATION}")

3
eth/CMakeLists.txt

@ -22,6 +22,7 @@ if (READLINE_FOUND)
endif()
if (JSONRPC)
target_link_libraries(${EXECUTABLE} ${JSON_RPC_CPP_CLIENT_LIBRARIES})
target_link_libraries(${EXECUTABLE} web3jsonrpc)
endif()
@ -29,7 +30,7 @@ target_link_libraries(${EXECUTABLE} webthree)
target_link_libraries(${EXECUTABLE} ethash)
if (DEFINED WIN32 AND NOT DEFINED CMAKE_COMPILER_IS_MINGW)
add_custom_command(TARGET ${EXECUTABLE} POST_BUILD COMMAND ${CMAKE_COMMAND} ARGS -E copy ${MHD_DLL_RELEASE} "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}")
eth_copy_dlls("${EXECUTABLE}" MHD_DLLS)
endif()
install( TARGETS ${EXECUTABLE} DESTINATION bin )

38
eth/Farm.h

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

28
eth/PhoneHome.h

@ -0,0 +1,28 @@
/**
* 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_

4
eth/farm.json

@ -0,0 +1,4 @@
[
{ "name": "eth_getWork", "params": [], "order": [], "returns": []},
{ "name": "eth_submitWork", "params": ["", ""], "order": [], "returns": true}
]

291
eth/main.cpp

@ -38,15 +38,20 @@
#include <libevm/VMFactory.h>
#include <libethereum/All.h>
#include <libwebthree/WebThree.h>
#if ETH_READLINE
#if ETH_READLINE || !ETH_TRUE
#include <readline/readline.h>
#include <readline/history.h>
#endif
#if ETH_JSONRPC
#if ETH_JSONRPC || !ETH_TRUE
#include <libweb3jsonrpc/WebThreeStubServer.h>
#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 "Farm.h"
#endif
using namespace std;
using namespace dev;
using namespace dev::p2p;
@ -89,7 +94,7 @@ void interactiveHelp()
<< " send Execute a given transaction with current secret." << endl
<< " contract Create a new contract with current secret." << endl
<< " peers List the peers that are connected" << endl
#if ETH_FATDB
#if ETH_FATDB || !ETH_TRUE
<< " listaccounts List the accounts on the network." << endl
<< " listcontracts List the contracts on the network." << endl
#endif
@ -111,43 +116,57 @@ void help()
<< " -a,--address <addr> Set the coinbase (mining payout) address to addr (default: auto)." << endl
<< " -b,--bootstrap Connect to the default Ethereum peerserver." << endl
<< " -B,--block-fees <n> Set the block fee profit in the reference unit e.g. ¢ (Default: 15)." << endl
<< " -c,--client-name <name> Add a name to your client's version string (default: blank)." << endl
<< " -C,--check-pow <headerHash> <seedHash> <difficulty> <nonce> Check PoW credentials for validity." << endl
<< " --client-name <name> Add a name to your client's version string (default: blank)." << endl
<< " -C,--cpu When mining, use the CPU." << endl
<< " -d,--db-path <path> Load database from path (default: ~/.ethereum " << endl
<< " <APPDATA>/Etherum or Library/Application Support/Ethereum)." << endl
<< " --benchmark-warmup <seconds> Set the duration of warmup for the benchmark tests (default: 3)." << endl
<< " --benchmark-trial <seconds> Set the duration for each trial for the benchmark tests (default: 3)." << endl
<< " --benchmark-trials <n> Set the duration of warmup for the benchmark tests (default: 5)." << endl
<< " -D,--create-dag <this/next/number> Create the DAG in preparation for mining on given block and exit." << endl
<< " -e,--ether-price <n> Set the ether price in the reference unit e.g. ¢ (Default: 30.679)." << endl
<< " -E,--export <file> Export file as a concatenated series of blocks and exit." << endl
<< " --from <n> Export only from block n; n may be a decimal, a '0x' prefixed hash, or 'latest'." << endl
<< " --to <n> Export only to block n (inclusive); n may be a decimal, a '0x' prefixed hash, or 'latest'." << endl
<< " --only <n> Equivalent to --export-from n --export-to n." << endl
<< " -f,--force-mining Mine even when there are no transaction to mine (Default: off)" << endl
<< " -f,--force-mining Mine even when there are no transactions to mine (Default: off)" << endl
#if ETH_JSONRPC || !ETH_TRUE
<< " -F,--farm <url> Put into mining farm mode with the work server at URL. Use with -G/--opencl." << endl
<< " --farm-recheck <n> Leave n ms between checks for changed work (default: 500)." << endl
#endif
<< " -G,--opencl When mining use the GPU via OpenCL." << endl
<< " -h,--help Show this help message and exit." << endl
<< " -i,--interactive Enter interactive mode (default: non-interactive)." << endl
<< " -I,--import <file> Import file as a concatenated series of blocks and exit." << endl
#if ETH_JSONRPC
#if ETH_JSONRPC || !ETH_TRUE
<< " -j,--json-rpc Enable JSON-RPC server (default: off)." << endl
<< " --json-rpc-port Specify JSON-RPC server port (implies '-j', default: " << SensibleHttpPort << ")." << endl
#endif
#if ETH_EVMJIT
#if ETH_EVMJIT || !ETH_TRUE
<< " -J,--jit Enable EVM JIT (default: off)." << endl
#endif
<< " -K,--kill First kill the blockchain." << endl
<< " --listen-ip <port> Listen on the given port for incoming connections (default: 30303)." << endl
<< " -l,--listen <ip> Listen on the given IP for incoming connections (default: 0.0.0.0)." << endl
<< " -u,--public-ip <ip> Force public ip to given (default: auto)." << endl
<< " --listen <port> Listen on the given port for incoming connections (default: 30303)." << endl
<< " --listen-ip <ip>(:<port>) Listen on the given IP for incoming connections (default: 0.0.0.0)." << endl
<< " --public-ip <ip> Force public ip to given (default: auto)." << endl
<< " -m,--mining <on/off/number> Enable mining, optionally for a specified number of blocks (Default: off)" << endl
<< " -n,-u,--upnp <on/off> Use upnp for NAT (default: on)." << endl
<< " -M,--benchmark Benchmark for mining and exit; use with --cpu and --opencl." << endl
<< " -o,--mode <full/peer> Start a full node or a peer node (Default: full)." << endl
<< " -p,--port <port> Connect to remote port (default: 30303)." << endl
<< " --opencl-device <n> When mining using -G/--opencl use OpenCL device n (default: 0)." << endl
<< " --port <port> Connect to remote port (default: 30303)." << endl
<< " -P,--priority <0 - 100> Default % priority of a transaction (default: 50)." << endl
#if ETH_JSONRPC || !ETH_TRUE
<< " --phone-home <on/off> When benchmarking, publish results (Default: on)" << endl
#endif
<< " -R,--rebuild First rebuild the blockchain from the existing database." << endl
<< " -r,--remote <host> Connect to remote host (default: none)." << endl
<< " -r,--remote <host>(:<port>) Connect to remote host (default: none)." << endl
<< " -s,--secret <secretkeyhex> Set the secret key for use with send command (default: auto)." << endl
<< " -S,--temporary-secret <secretkeyhex> Set the secret key for use with send command, for this session only." << endl
<< " -S,--session-secret <secretkeyhex> Set the secret key for use with send command, for this session only." << endl
<< " --upnp <on/off> Use upnp for NAT (default: on)." << endl
<< " -v,--verbosity <0 - 9> Set the log verbosity from 0 to 9 (Default: 8)." << endl
<< " -x,--peers <number> Attempt to connect to given number of peers (Default: 5)." << endl
<< " -V,--version Show the version and exit." << endl
<< " -w,--check-pow <headerHash> <seedHash> <difficulty> <nonce> Check PoW credentials for validity." << endl
<< " -x,--peers <number> Attempt to connect to given number of peers (Default: 5)." << endl
;
exit(0);
}
@ -221,7 +240,9 @@ enum class OperationMode
Node,
Import,
Export,
DAGInit
DAGInit,
Benchmark,
Farm
};
enum class Format
@ -231,6 +252,128 @@ enum class Format
Human
};
enum class MinerType
{
CPU,
GPU
};
void doBenchmark(MinerType _m, bool _phoneHome, unsigned _warmupDuration = 15, unsigned _trialDuration = 3, unsigned _trials = 5)
{
BlockInfo genesis = CanonBlockChain::genesis();
genesis.difficulty = 1 << 18;
cdebug << genesis.boundary();
GenericFarm<Ethash> f;
f.onSolutionFound([&](ProofOfWork::Solution) { return false; });
string platformInfo = _m == MinerType::CPU ? ProofOfWork::CPUMiner::platformInfo() : _m == MinerType::GPU ? ProofOfWork::GPUMiner::platformInfo() : "";
cout << "Benchmarking on platform: " << platformInfo << endl;
cout << "Preparing DAG..." << endl;
Ethash::prep(genesis);
genesis.difficulty = u256(1) << 63;
genesis.noteDirty();
f.setWork(genesis);
if (_m == MinerType::CPU)
f.startCPU();
else if (_m == MinerType::GPU)
f.startGPU();
map<uint64_t, MiningProgress> results;
uint64_t mean = 0;
uint64_t innerMean = 0;
for (unsigned i = 0; i <= _trials; ++i)
{
if (!i)
cout << "Warming up..." << endl;
else
cout << "Trial " << i << "... " << flush;
this_thread::sleep_for(chrono::seconds(i ? _trialDuration : _warmupDuration));
auto mp = f.miningProgress();
f.resetMiningProgress();
if (!i)
continue;
auto rate = mp.rate();
cout << rate << endl;
results[rate] = mp;
mean += rate;
if (i > 1 && i < 5)
innerMean += rate;
}
f.stop();
cout << "min/mean/max: " << results.begin()->second.rate() << "/" << (mean / _trials) << "/" << results.rbegin()->second.rate() << " H/s" << endl;
cout << "inner mean: " << (innerMean / (_trials - 2)) << " H/s" << endl;
(void)_phoneHome;
#if ETH_JSONRPC || !ETH_TRUE
if (_phoneHome)
{
cout << "Phoning home to find world ranking..." << endl;
jsonrpc::HttpClient client("http://192.168.33.39:3000/benchmark");
PhoneHome rpc(client);
try
{
unsigned ranking = rpc.report_benchmark(platformInfo, innerMean);
cout << "Ranked: " << ranking << " of all benchmarks." << endl;
}
catch (...)
{
cout << "Error phoning home. ET is sad." << endl;
}
}
#endif
exit(0);
}
void doFarm(MinerType _m, string const& _remote, unsigned _recheckPeriod)
{
(void)_m;
(void)_remote;
(void)_recheckPeriod;
#if ETH_JSONRPC || !ETH_TRUE
jsonrpc::HttpClient client(_remote);
Farm rpc(client);
GenericFarm<Ethash> f;
if (_m == MinerType::CPU)
f.startCPU();
else if (_m == MinerType::GPU)
f.startGPU();
ProofOfWork::WorkPackage current;
while (true)
{
bool completed = false;
ProofOfWork::Solution solution;
f.onSolutionFound([&](ProofOfWork::Solution sol)
{
solution = sol;
return completed = true;
});
for (unsigned i = 0; !completed; ++i)
{
Json::Value v = rpc.eth_getWork();
h256 hh(v[0].asString());
if (hh != current.headerHash)
{
current.headerHash = hh;
current.seedHash = h256(v[1].asString());
current.boundary = h256(v[2].asString());
f.setWork(current);
}
this_thread::sleep_for(chrono::milliseconds(_recheckPeriod));
}
rpc.eth_submitWork("0x" + toString(solution.nonce), "0x" + toString(solution.mixHash));
}
#endif
exit(0);
}
int main(int argc, char** argv)
{
// Init defaults
@ -240,6 +383,10 @@ int main(int argc, char** argv)
OperationMode mode = OperationMode::Node;
string dbPath;
/// Mining options
MinerType minerType = MinerType::CPU;
unsigned openclDevice = 0;
/// File name for import/export.
string filename;
@ -287,6 +434,16 @@ int main(int argc, char** argv)
double etherPrice = 30.679;
double blockFees = 15.0;
/// Benchmarking params
bool phoneHome = true;
unsigned benchmarkWarmup = 3;
unsigned benchmarkTrial = 3;
unsigned benchmarkTrials = 5;
/// Farm params
string farmURL = "http://127.0.0.1:8080";
unsigned farmRecheckPeriod = 500;
string configFile = getDataDir() + "/config.rlp";
bytes b = contents(configFile);
if (b.size())
@ -302,13 +459,25 @@ int main(int argc, char** argv)
if (arg == "--listen-ip" && i + 1 < argc)
listenIP = argv[++i];
else if ((arg == "-l" || arg == "--listen" || arg == "--listen-port") && i + 1 < argc)
{
if (arg == "-l")
cerr << "-l is DEPRECATED. It will be removed for the Frontier. Use --listen-port instead." << endl;
listenPort = (short)atoi(argv[++i]);
}
else if ((arg == "-u" || arg == "--public-ip" || arg == "--public") && i + 1 < argc)
{
if (arg == "-u")
cerr << "-u is DEPRECATED. It will be removed for the Frontier. Use --public-ip instead." << endl;
publicIP = argv[++i];
}
else if ((arg == "-r" || arg == "--remote") && i + 1 < argc)
remoteHost = argv[++i];
else if ((arg == "-p" || arg == "--port") && i + 1 < argc)
{
if (arg == "-p")
cerr << "-p is DEPRECATED. It will be removed for the Frontier. Use --port instead (or place directly as host:port)." << endl;
remotePort = (short)atoi(argv[++i]);
}
else if ((arg == "-I" || arg == "--import") && i + 1 < argc)
{
mode = OperationMode::Import;
@ -319,6 +488,42 @@ int main(int argc, char** argv)
mode = OperationMode::Export;
filename = argv[++i];
}
else if ((arg == "-F" || arg == "--farm") && i + 1 < argc)
{
mode = OperationMode::Farm;
farmURL = argv[++i];
}
else if (arg == "--farm-recheck" && i + 1 < argc)
try {
farmRecheckPeriod = stol(argv[++i]);
}
catch (...)
{
cerr << "Bad " << arg << " option: " << argv[i] << endl;
return -1;
}
else if (arg == "--opencl-device" && i + 1 < argc)
try {
openclDevice = stol(argv[++i]);
}
catch (...)
{
cerr << "Bad " << arg << " option: " << argv[i] << endl;
return -1;
}
else if (arg == "--phone-home" && i + 1 < argc)
{
string m = argv[++i];
if (isTrue(m))
phoneHome = true;
else if (isFalse(m))
phoneHome = false;
else
{
cerr << "Bad " << arg << " option: " << m << endl;
return -1;
}
}
else if (arg == "--format" && i + 1 < argc)
{
string m = argv[++i];
@ -342,6 +547,8 @@ int main(int argc, char** argv)
exportTo = exportFrom = argv[++i];
else if ((arg == "-n" || arg == "-u" || arg == "--upnp") && i + 1 < argc)
{
if (arg == "-n")
cerr << "-n is DEPRECATED. It will be removed for the Frontier. Use --upnp instead." << endl;
string m = argv[++i];
if (isTrue(m))
upnp = true;
@ -353,15 +560,45 @@ int main(int argc, char** argv)
return -1;
}
}
else if (arg == "--benchmark-warmup" && i + 1 < argc)
try {
benchmarkWarmup = stol(argv[++i]);
}
catch (...)
{
cerr << "Bad " << arg << " option: " << argv[i] << endl;
return -1;
}
else if (arg == "--benchmark-trial" && i + 1 < argc)
try {
benchmarkTrial = stol(argv[++i]);
}
catch (...)
{
cerr << "Bad " << arg << " option: " << argv[i] << endl;
return -1;
}
else if (arg == "--benchmark-trials" && i + 1 < argc)
try {
benchmarkTrials = stol(argv[++i]);
}
catch (...)
{
cerr << "Bad " << arg << " option: " << argv[i] << endl;
return -1;
}
else if (arg == "-K" || arg == "--kill-blockchain" || arg == "--kill")
killChain = WithExisting::Kill;
else if (arg == "-B" || arg == "--rebuild")
killChain = WithExisting::Verify;
else if ((arg == "-c" || arg == "--client-name") && i + 1 < argc)
{
if (arg == "-c")
cerr << "-c is DEPRECATED. It will be removed for the Frontier. Use --client-name instead." << endl;
clientName = argv[++i];
}
else if ((arg == "-a" || arg == "--address" || arg == "--coinbase-address") && i + 1 < argc)
try
{
try {
coinbase = h160(fromHex(argv[++i], WhenError::Throw));
}
catch (BadHexCharacter&)
@ -374,6 +611,10 @@ int main(int argc, char** argv)
cerr << "Bad " << arg << " option: " << argv[i] << endl;
return -1;
}
else if (arg == "-C" || arg == "--cpu")
minerType = MinerType::CPU;
else if (arg == "-G" || arg == "--opencl")
minerType = MinerType::GPU;
else if ((arg == "-s" || arg == "--secret") && i + 1 < argc)
sigKey = KeyPair(h256(fromHex(argv[++i])));
else if ((arg == "-S" || arg == "--session-secret") && i + 1 < argc)
@ -403,7 +644,7 @@ int main(int argc, char** argv)
return -1;
}
}
else if ((arg == "-C" || arg == "--check-pow") && i + 4 < argc)
else if ((arg == "-w" || arg == "--check-pow") && i + 4 < argc)
{
string m;
try
@ -440,6 +681,8 @@ int main(int argc, char** argv)
return -1;
}
}
else if (arg == "-M" || arg == "--benchmark")
mode = OperationMode::Benchmark;
else if ((arg == "-B" || arg == "--block-fees") && i + 1 < argc)
{
try
@ -557,11 +800,19 @@ int main(int argc, char** argv)
if (sessionSecret)
sigKey = KeyPair(sessionSecret);
ProofOfWork::GPUMiner::setDefaultDevice(openclDevice);
// Two codepaths is necessary since named block require database, but numbered
// blocks are superuseful to have when database is already open in another process.
if (mode == OperationMode::DAGInit && !(initDAG == LatestBlock || initDAG == PendingBlock))
doInitDAG(initDAG);
if (mode == OperationMode::Benchmark)
doBenchmark(minerType, phoneHome, benchmarkWarmup, benchmarkTrial, benchmarkTrials);
if (mode == OperationMode::Farm)
doFarm(minerType, farmURL, farmRecheckPeriod);
if (!clientName.empty())
clientName += "/";

3
eth/phonehome.json

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

2
ethrpctest/CMakeLists.txt

@ -28,7 +28,7 @@ target_link_libraries(${EXECUTABLE} testutils)
target_link_libraries(${EXECUTABLE} web3jsonrpc)
if (DEFINED WIN32 AND NOT DEFINED CMAKE_COMPILER_IS_MINGW)
add_custom_command(TARGET ${EXECUTABLE} POST_BUILD COMMAND ${CMAKE_COMMAND} ARGS -E copy ${MHD_DLL_RELEASE} "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}")
eth_copy_dlls("${EXECUTABLE}" MHD_DLLS)
endif()
install( TARGETS ${EXECUTABLE} DESTINATION bin )

25
extdep/CMakeLists.txt

@ -34,23 +34,14 @@ if (ETH_COMPILE)
# boost
include(compile/boost.cmake)
else()
eth_download(jsoncpp)
eth_download(microhttpd)
eth_download(json-rpc-cpp
VERSION 4.2
OSX_SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/scripts/json-rpc-cpp_osx.sh
)
if (APPLE)
eth_download(snappy OSX_SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/scripts/snappy_osx.sh)
endif()
eth_download(leveldb OSX_SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/scripts/leveldb_osx.sh)
eth_download(qt VERSION 5.4)
eth_download(cryptopp)
eth_download(boost)
eth_download(curl)
eth_download(boost VERSION 1.55.0)
eth_download(cryptopp VERSION 5.6.2)
eth_download(curl VERSION 7.4.2)
eth_download(jsoncpp VERSION 1.6.2)
eth_download(json-rpc-cpp VERSION 0.5.0)
eth_download(leveldb VERSION 1.2)
eth_download(microhttpd VERSION 0.9.2)
eth_download(qt VERSION 5.4.1)
endif()
# will be re-eanbled later

32
extdep/getstuff.bat

@ -0,0 +1,32 @@
REM get stuff!
if not exist download mkdir download
if not exist install mkdir install
if not exist install\windows mkdir install\windows
set eth_server=https://build.ethdev.com/builds/windows-precompiled
call :download boost 1.55.0
call :download cryptopp 5.6.2
call :download curl 7.4.2
call :download jsoncpp 1.6.2
call :download json-rpc-cpp 0.5.0
call :download leveldb 1.2
call :download microhttpd 0.9.2
call :download qt 5.4.1
goto :EOF
:download
set eth_name=%1
set eth_version=%2
cd download
if not exist %eth_name%-%eth_version%.tar.gz curl -o %eth_name%-%eth_version%.tar.gz %eth_server%/%eth_name%-%eth_version%.tar.gz
if not exist %eth_name%-%eth_version% tar -zxvf %eth_name%-%eth_version%.tar.gz
cmake -E copy_directory %eth_name%-%eth_version% ..\install\windows
cd ..\download
goto :EOF

2
libdevcore/Common.cpp

@ -27,7 +27,7 @@ using namespace dev;
namespace dev
{
char const* Version = "0.9.8";
char const* Version = "0.9.9";
}

52
libethash-cl/CMakeLists.txt

@ -1,47 +1,19 @@
cmake_minimum_required(VERSION 2.8)
set(LIBRARY ethash-cl)
#set(CMAKE_BUILD_TYPE Release)
set(EXECUTABLE ethash-cl)
include(bin2h.cmake)
bin2h(SOURCE_FILE ethash_cl_miner_kernel.cl
VARIABLE_NAME ethash_cl_miner_kernel
HEADER_FILE ${CMAKE_CURRENT_BINARY_DIR}/ethash_cl_miner_kernel.h)
if (NOT MSVC)
# Initialize CXXFLAGS for c++11
set(CMAKE_CXX_FLAGS "-Wall -std=c++11")
set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g")
set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG")
set(CMAKE_CXX_FLAGS_RELEASE "-O4 -DNDEBUG")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
VARIABLE_NAME ethash_cl_miner_kernel
HEADER_FILE ${CMAKE_CURRENT_BINARY_DIR}/ethash_cl_miner_kernel.h)
# Compiler-specific C++11 activation.
if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU")
execute_process(
COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION)
if (NOT (GCC_VERSION VERSION_GREATER 4.7 OR GCC_VERSION VERSION_EQUAL 4.7))
message(FATAL_ERROR "${PROJECT_NAME} requires g++ 4.7 or greater.")
endif ()
elseif ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
else ()
message(FATAL_ERROR "Your C++ compiler does not support C++11.")
endif ()
endif()
aux_source_directory(. SRC_LIST)
file(GLOB HEADERS "*.h")
set(OpenCL_FOUND TRUE)
set(OpenCL_INCLUDE_DIRS /usr/include/CL)
set(OpenCL_LIBRARIES -lOpenCL)
include_directories(${CMAKE_CURRENT_BINARY_DIR})
include_directories(${OpenCL_INCLUDE_DIRS})
include_directories(..)
add_library(${EXECUTABLE} ${SRC_LIST} ${HEADERS})
TARGET_LINK_LIBRARIES(${EXECUTABLE} ${OpenCL_LIBRARIES} ethash)
if (NOT OpenCL_FOUND)
find_package(OpenCL)
endif()
install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )
if (OpenCL_FOUND)
set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -Werror -pedantic -fPIC ${CMAKE_CXX_FLAGS}")
include_directories(${OpenCL_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR})
include_directories(..)
add_library(${LIBRARY} ethash_cl_miner.cpp ethash_cl_miner.h cl.hpp)
TARGET_LINK_LIBRARIES(${LIBRARY} ${OpenCL_LIBRARIES} ethash)
endif()

38
libethash-cl/ethash_cl_miner.cpp

@ -57,6 +57,33 @@ ethash_cl_miner::ethash_cl_miner()
{
}
std::string ethash_cl_miner::platform_info()
{
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
if (platforms.empty())
{
debugf("No OpenCL platforms found.\n");
return std::string();
}
// get GPU device of the default platform
std::vector<cl::Device> devices;
platforms[0].getDevices(CL_DEVICE_TYPE_ALL, &devices);
if (devices.empty())
{
debugf("No OpenCL devices found.\n");
return std::string();
}
// use default device
unsigned device_num = 0;
cl::Device& device = devices[device_num];
std::string device_version = device.getInfo<CL_DEVICE_VERSION>();
return "{ \"platform\": \"" + platforms[0].getInfo<CL_PLATFORM_NAME>() + "\", \"device\": \"" + device.getInfo<CL_DEVICE_NAME>() + "\", \"version\": \"" + device_version + "\" }";
}
void ethash_cl_miner::finish()
{
if (m_queue())
@ -65,7 +92,7 @@ void ethash_cl_miner::finish()
}
}
bool ethash_cl_miner::init(ethash_params const& params, std::function<void(void*)> _fillDAG, unsigned workgroup_size)
bool ethash_cl_miner::init(ethash_params const& params, std::function<void(void*)> _fillDAG, unsigned workgroup_size, unsigned _deviceId)
{
// store params
m_params = params;
@ -92,8 +119,13 @@ bool ethash_cl_miner::init(ethash_params const& params, std::function<void(void*
}
// use default device
unsigned device_num = 0;
cl::Device& device = devices[device_num];
cl::Device& device = devices[std::min<unsigned>(_deviceId, devices.size() - 1)];
for (unsigned n = 0; n < devices.size(); ++n)
{
auto version = devices[n].getInfo<CL_DEVICE_VERSION>();
auto name = devices[n].getInfo<CL_DEVICE_NAME>();
fprintf(stderr, "%s %d: %s (%s)\n", n == _deviceId ? "USING " : " ", n, name.c_str(), version.c_str());
}
std::string device_version = device.getInfo<CL_DEVICE_VERSION>();
fprintf(stderr, "Using device: %s (%s)\n", device.getInfo<CL_DEVICE_NAME>().c_str(),device_version.c_str());

12
libethash-cl/ethash_cl_miner.h

@ -2,7 +2,16 @@
#define __CL_ENABLE_EXCEPTIONS
#define CL_USE_DEPRECATED_OPENCL_2_0_APIS
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#include "cl.hpp"
#pragma clang diagnostic pop
#else
#include "cl.hpp"
#endif
#include <time.h>
#include <functional>
#include <libethash/ethash.h>
@ -22,7 +31,8 @@ public:
public:
ethash_cl_miner();
bool init(ethash_params const& params, std::function<void(void*)> _fillDAG, unsigned workgroup_size = 64);
bool init(ethash_params const& params, std::function<void(void*)> _fillDAG, unsigned workgroup_size = 64, unsigned _deviceId = 0);
static std::string platform_info();
void finish();
void hash(uint8_t* ret, uint8_t const* header, uint64_t nonce, unsigned count);

16
libethcore/CMakeLists.txt

@ -12,6 +12,14 @@ aux_source_directory(. SRC_LIST)
include_directories(BEFORE ..)
include_directories(${Boost_INCLUDE_DIRS})
if (ETHASHCL)
include_directories(${OpenCL_INCLUDE_DIRS})
endif ()
if (CPUID_FOUND)
include_directories(${Cpuid_INCLUDE_DIRS})
endif ()
set(EXECUTABLE ethcore)
file(GLOB HEADERS "*.h")
@ -26,6 +34,14 @@ target_link_libraries(${EXECUTABLE} ethash)
target_link_libraries(${EXECUTABLE} devcrypto)
target_link_libraries(${EXECUTABLE} devcore)
if (ETHASHCL)
target_link_libraries(${EXECUTABLE} ethash-cl)
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} )

11
libethcore/Common.h

@ -93,6 +93,17 @@ enum class ImportResult
BadChain
};
struct ImportRequirements
{
using value = unsigned;
enum
{
ValidNonce = 1, ///< Validate Nonce
DontHave = 2, ///< Avoid old blocks
Default = ValidNonce | DontHave
};
};
/// Super-duper signal mechanism. TODO: replace with somthing a bit heavier weight.
class Signal
{

66
libethcore/Ethash.cpp

@ -23,6 +23,7 @@
#include <boost/detail/endian.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <chrono>
#include <array>
#include <thread>
@ -38,6 +39,10 @@
#if ETH_ETHASHCL || !ETH_TRUE
#include <libethash-cl/ethash_cl_miner.h>
#endif
#if ETH_CPUID || !ETH_TRUE
#define HAVE_STDINT_H
#include <libcpuid/libcpuid.h>
#endif
#include "BlockInfo.h"
#include "EthashAux.h"
using namespace std;
@ -142,6 +147,58 @@ void Ethash::CPUMiner::workLoop()
}
}
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 + "}";
}
std::string Ethash::CPUMiner::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
}
#if ETH_ETHASHCL || !ETH_TRUE
class EthashCLHook: public ethash_cl_miner::search_hook
@ -204,6 +261,8 @@ private:
Ethash::GPUMiner* m_owner = nullptr;
};
unsigned Ethash::GPUMiner::s_deviceId = 0;
Ethash::GPUMiner::GPUMiner(ConstructionInfo const& _ci):
Miner(_ci),
m_hook(new EthashCLHook(this))
@ -245,7 +304,7 @@ void Ethash::GPUMiner::workLoop()
auto p = EthashAux::params(m_minerSeed);
auto cb = [&](void* d) { EthashAux::full(m_minerSeed, bytesRef((byte*)d, p.full_size)); };
m_miner->init(p, cb, 32);
m_miner->init(p, cb, 32, s_deviceId);
}
uint64_t upper64OfBoundary = (uint64_t)(u64)((u256)w.boundary >> 192);
@ -258,6 +317,11 @@ void Ethash::GPUMiner::pause()
stopWorking();
}
std::string Ethash::GPUMiner::platformInfo()
{
return ethash_cl_miner::platform_info();
}
#endif
}

6
libethcore/Ethash.h

@ -85,6 +85,8 @@ public:
CPUMiner(ConstructionInfo const& _ci): Miner(_ci), Worker("miner" + toString(index())) {}
static unsigned instances() { return std::thread::hardware_concurrency(); }
static std::string platformInfo();
static void setDefaultDevice(unsigned) {}
protected:
void kickOff() override
@ -97,6 +99,7 @@ public:
private:
void workLoop() override;
static unsigned s_deviceId;
};
#if ETH_ETHASHCL || !ETH_TRUE
@ -109,6 +112,8 @@ public:
~GPUMiner();
static unsigned instances() { return 1; }
static std::string platformInfo();
static void setDefaultDevice(unsigned _id) { s_deviceId = _id; }
protected:
void kickOff() override;
@ -124,6 +129,7 @@ public:
ethash_cl_miner* m_miner = nullptr;
h256 m_minerSeed; ///< Last seed in m_miner
static unsigned s_deviceId;
};
#else
using GPUMiner = CPUMiner;

7
libethcore/Miner.h

@ -42,13 +42,14 @@ struct MiningProgress
// MiningProgress& operator+=(MiningProgress const& _mp) { hashes += _mp.hashes; ms = std::max(ms, _mp.ms); return *this; }
uint64_t hashes = 0; ///< Total number of hashes computed.
uint64_t ms = 0; ///< Total number of milliseconds of mining thus far.
uint64_t rate() const { return hashes * 1000 / ms; }
};
struct MineInfo: public MiningProgress {};
inline std::ostream& operator<<(std::ostream& _out, MiningProgress _p)
{
_out << (_p.hashes * 1000 / _p.ms) << "H/s = " << _p.hashes << " hashes / " << (double(_p.ms) / 1000) << "s";
_out << _p.rate() << " H/s = " << _p.hashes << " hashes / " << (double(_p.ms) / 1000) << " s";
return _out;
}
@ -112,7 +113,9 @@ public:
m_hashCount = 0;
}
uint64_t hashCount() { return m_hashCount; }
uint64_t hashCount() const { return m_hashCount; }
void resetHashCount() { m_hashCount = 0; }
unsigned index() const { return m_index; }

12
libethereum/BlockChain.cpp

@ -238,7 +238,7 @@ void BlockChain::rebuild(std::string const& _path, std::function<void(unsigned,
return;
}
lastHash = bi.hash();
import(b, s.db(), Aversion::ImportOldBlocks);
import(b, s.db(), ImportRequirements::Default);
}
catch (...)
{
@ -326,11 +326,11 @@ tuple<h256s, h256s, bool> BlockChain::sync(BlockQueue& _bq, OverlayDB const& _st
return make_tuple(fresh, dead, _bq.doneDrain(badBlocks));
}
ImportRoute BlockChain::attemptImport(bytes const& _block, OverlayDB const& _stateDB, Aversion _force) noexcept
ImportRoute BlockChain::attemptImport(bytes const& _block, OverlayDB const& _stateDB, ImportRequirements::value _ir) noexcept
{
try
{
return import(_block, _stateDB, _force);
return import(_block, _stateDB, _ir);
}
catch (...)
{
@ -339,7 +339,7 @@ ImportRoute BlockChain::attemptImport(bytes const& _block, OverlayDB const& _sta
}
}
ImportRoute BlockChain::import(bytes const& _block, OverlayDB const& _db, Aversion _force)
ImportRoute BlockChain::import(bytes const& _block, OverlayDB const& _db, ImportRequirements::value _ir)
{
//@tidy This is a behemoth of a method - could do to be split into a few smaller ones.
@ -378,7 +378,7 @@ ImportRoute BlockChain::import(bytes const& _block, OverlayDB const& _db, Aversi
#endif
// Check block doesn't already exist first!
if (isKnown(bi.hash()) && _force == Aversion::AvoidOldBlocks)
if (isKnown(bi.hash()) && (_ir & ImportRequirements::DontHave))
{
clog(BlockChainNote) << bi.hash() << ": Not new.";
BOOST_THROW_EXCEPTION(AlreadyHaveBlock());
@ -424,7 +424,7 @@ ImportRoute BlockChain::import(bytes const& _block, OverlayDB const& _db, Aversi
// Check transactions are valid and that they result in a state equivalent to our state_root.
// Get total difficulty increase and update state, checking it.
State s(_db); //, bi.coinbaseAddress
auto tdIncrease = s.enactOn(&_block, bi, *this);
auto tdIncrease = s.enactOn(&_block, bi, *this, _ir);
BlockLogBlooms blb;
BlockReceipts br;

10
libethereum/BlockChain.h

@ -81,12 +81,6 @@ enum {
using ProgressCallback = std::function<void(unsigned, unsigned)>;
enum class Aversion
{
AvoidOldBlocks,
ImportOldBlocks
};
/**
* @brief Implements the blockchain database. All data this gives is disk-backed.
* @threadsafe
@ -109,11 +103,11 @@ public:
/// Attempt to import the given block directly into the CanonBlockChain and sync with the state DB.
/// @returns the block hashes of any blocks that came into/went out of the canonical block chain.
ImportRoute attemptImport(bytes const& _block, OverlayDB const& _stateDB, Aversion _force = Aversion::AvoidOldBlocks) noexcept;
ImportRoute attemptImport(bytes const& _block, OverlayDB const& _stateDB, ImportRequirements::value _ir = ImportRequirements::Default) noexcept;
/// Import block into disk-backed DB
/// @returns the block hashes of any blocks that came into/went out of the canonical block chain.
ImportRoute import(bytes const& _block, OverlayDB const& _stateDB, Aversion _force = Aversion::AvoidOldBlocks);
ImportRoute import(bytes const& _block, OverlayDB const& _stateDB, ImportRequirements::value _ir = ImportRequirements::Default);
/// Returns true if the given block is known (though not necessarily a part of the canon chain).
bool isKnown(h256 const& _hash) const;

4
libethereum/CMakeLists.txt

@ -34,10 +34,6 @@ target_link_libraries(${EXECUTABLE} ethcore)
target_link_libraries(${EXECUTABLE} ${LEVELDB_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${Boost_REGEX_LIBRARIES})
target_link_libraries(${EXECUTABLE} secp256k1)
if (ETHASHCL)
target_link_libraries(${EXECUTABLE} ethash-cl)
target_link_libraries(${EXECUTABLE} OpenCL)
endif ()
if (CMAKE_COMPILER_IS_MINGW)
target_link_libraries(${EXECUTABLE} ssp shlwapi)

11
libethereum/ClientBase.cpp

@ -323,6 +323,11 @@ Transaction ClientBase::transaction(h256 _blockHash, unsigned _i) const
return Transaction();
}
pair<h256, unsigned> ClientBase::transactionLocation(h256 const& _transactionHash) const
{
return bc().transactionLocation(_transactionHash);
}
Transactions ClientBase::transactions(h256 _blockHash) const
{
auto bl = bc().block(_blockHash);
@ -421,3 +426,9 @@ h256 ClientBase::hashFromNumber(BlockNumber _number) const
return bc().currentHash();
return bc().numberHash(_number);
}
BlockNumber ClientBase::numberFromHash(h256 _blockHash) const
{
return bc().number(_blockHash);
}

2
libethereum/ClientBase.h

@ -111,10 +111,12 @@ public:
virtual LocalisedLogEntries checkWatch(unsigned _watchId) override;
virtual h256 hashFromNumber(BlockNumber _number) const override;
virtual BlockNumber numberFromHash(h256 _blockHash) const override;
virtual BlockInfo blockInfo(h256 _hash) const override;
virtual BlockDetails blockDetails(h256 _hash) const override;
virtual Transaction transaction(h256 _transactionHash) const override;
virtual Transaction transaction(h256 _blockHash, unsigned _i) const override;
virtual std::pair<h256, unsigned> transactionLocation(h256 const& _transactionHash) const override;
virtual Transactions transactions(h256 _blockHash) const override;
virtual TransactionHashes transactionHashes(h256 _blockHash) const override;
virtual BlockInfo uncle(h256 _blockHash, unsigned _i) const override;

9
libethereum/DownloadMan.h

@ -134,6 +134,15 @@ public:
return m_blocksGot.full();
}
h256s remaining() const
{
h256s ret;
ReadGuard l(m_lock);
for (auto i: m_blocksGot.inverted())
ret.push_back(m_chain[i]);
return ret;
}
h256s chain() const { ReadGuard l(m_lock); return m_chain; }
void foreachSub(std::function<void(DownloadSub const&)> const& _f) const { ReadGuard l(x_subs); for(auto i: m_subs) _f(*i); }
unsigned subCount() const { ReadGuard l(x_subs); return m_subs.size(); }

9
libethereum/EthereumHost.cpp

@ -132,10 +132,11 @@ void EthereumHost::noteDoneBlocks(EthereumPeer* _who, bool _clemency)
else
{
// Done our chain-get.
clog(NetNote) << "Chain download failed. Peer with blocks didn't have them all. This peer is bad and should be punished.";
m_banned.insert(_who->session()->id()); // We know who you are!
_who->disable("Peer sent hashes but was unable to provide the blocks.");
clog(NetWarn) << "Chain download failed. Peer with blocks didn't have them all. This peer is bad and should be punished.";
clog(NetWarn) << m_man.remaining();
clog(NetWarn) << "WOULD BAN.";
// m_banned.insert(_who->session()->id()); // We know who you are!
// _who->disable("Peer sent hashes but was unable to provide the blocks.");
}
m_man.reset();
}

26
libethereum/Farm.h

@ -59,14 +59,18 @@ public:
* @brief Sets the current mining mission.
* @param _bi The block (header) we wish to be mining.
*/
void setWork(BlockInfo const& _bi)
void setWork(BlockInfo const& _bi) { setWork(PoW::package(_bi)); }
/**
* @brief Sets the current mining mission.
* @param _wp The work package we wish to be mining.
*/
void setWork(WorkPackage const& _wp)
{
WriteGuard l(x_minerWork);
m_header = _bi;
auto p = PoW::package(m_header);
if (p.headerHash == m_work.headerHash)
if (_wp.headerHash == m_work.headerHash)
return;
m_work = p;
m_work = _wp;
for (auto const& m: m_miners)
m->setWork(m_work);
resetTimer();
@ -118,6 +122,17 @@ public:
return m_progress;
}
/**
* @brief Reset the mining progess counter.
*/
void resetMiningProgress()
{
ETH_READ_GUARDED(x_minerWork)
for (auto const& i: m_miners)
i->resetHashCount();
resetTimer();
}
using SolutionFound = std::function<bool(Solution const&)>;
/**
@ -179,7 +194,6 @@ private:
mutable SharedMutex x_minerWork;
std::vector<std::shared_ptr<Miner>> m_miners;
WorkPackage m_work;
BlockInfo m_header;
std::atomic<bool> m_isMining = {false};

2
libethereum/Interface.h

@ -119,7 +119,9 @@ public:
// [BLOCK QUERY API]
virtual Transaction transaction(h256 _transactionHash) const = 0;
virtual std::pair<h256, unsigned> transactionLocation(h256 const& _transactionHash) const = 0;
virtual h256 hashFromNumber(BlockNumber _number) const = 0;
virtual BlockNumber numberFromHash(h256 _blockHash) const = 0;
virtual BlockInfo blockInfo(h256 _hash) const = 0;
virtual BlockDetails blockDetails(h256 _hash) const = 0;

14
libethereum/State.cpp

@ -274,7 +274,7 @@ bool State::sync(BlockChain const& _bc)
return sync(_bc, _bc.currentHash());
}
bool State::sync(BlockChain const& _bc, h256 _block, BlockInfo const& _bi)
bool State::sync(BlockChain const& _bc, h256 _block, BlockInfo const& _bi, ImportRequirements::value _ir)
{
bool ret = false;
// BLOCK
@ -337,7 +337,7 @@ bool State::sync(BlockChain const& _bc, h256 _block, BlockInfo const& _bi)
for (auto it = chain.rbegin(); it != chain.rend(); ++it)
{
auto b = _bc.block(*it);
enact(&b, _bc);
enact(&b, _bc, _ir);
cleanup(true);
}
}
@ -355,7 +355,7 @@ bool State::sync(BlockChain const& _bc, h256 _block, BlockInfo const& _bi)
return ret;
}
u256 State::enactOn(bytesConstRef _block, BlockInfo const& _bi, BlockChain const& _bc)
u256 State::enactOn(bytesConstRef _block, BlockInfo const& _bi, BlockChain const& _bc, ImportRequirements::value _ir)
{
#if ETH_TIMED_ENACTMENTS
boost::timer t;
@ -383,7 +383,7 @@ u256 State::enactOn(bytesConstRef _block, BlockInfo const& _bi, BlockChain const
t.restart();
#endif
sync(_bc, _bi.parentHash);
sync(_bc, _bi.parentHash, BlockInfo(), _ir);
resetCurrent();
#if ETH_TIMED_ENACTMENTS
@ -392,7 +392,7 @@ u256 State::enactOn(bytesConstRef _block, BlockInfo const& _bi, BlockChain const
#endif
m_previousBlock = biParent;
auto ret = enact(_block, _bc);
auto ret = enact(_block, _bc, _ir);
#if ETH_TIMED_ENACTMENTS
enactment = t.elapsed();
@ -538,11 +538,11 @@ TransactionReceipts State::sync(BlockChain const& _bc, TransactionQueue& _tq, Ga
return ret;
}
u256 State::enact(bytesConstRef _block, BlockChain const& _bc, bool _checkNonce)
u256 State::enact(bytesConstRef _block, BlockChain const& _bc, ImportRequirements::value _ir)
{
// m_currentBlock is assumed to be prepopulated and reset.
BlockInfo bi(_block, _checkNonce ? CheckEverything : IgnoreNonce);
BlockInfo bi(_block, (_ir & ImportRequirements::ValidNonce) ? CheckEverything : IgnoreNonce);
#if !ETH_RELEASE
assert(m_previousBlock.hash() == bi.parentHash);

6
libethereum/State.h

@ -314,11 +314,11 @@ public:
bool sync(BlockChain const& _bc);
/// Sync with the block chain, but rather than synching to the latest block, instead sync to the given block.
bool sync(BlockChain const& _bc, h256 _blockHash, BlockInfo const& _bi = BlockInfo());
bool sync(BlockChain const& _bc, h256 _blockHash, BlockInfo const& _bi = BlockInfo(), ImportRequirements::value _ir = ImportRequirements::Default);
/// Execute all transactions within a given block.
/// @returns the additional total difficulty.
u256 enactOn(bytesConstRef _block, BlockInfo const& _bi, BlockChain const& _bc);
u256 enactOn(bytesConstRef _block, BlockInfo const& _bi, BlockChain const& _bc, ImportRequirements::value _ir = ImportRequirements::Default);
/// Returns back to a pristine state after having done a playback.
/// @arg _fullCommit if true flush everything out to disk. If false, this effectively only validates
@ -346,7 +346,7 @@ private:
/// Execute the given block, assuming it corresponds to m_currentBlock.
/// Throws on failure.
u256 enact(bytesConstRef _block, BlockChain const& _bc, bool _checkNonce = true);
u256 enact(bytesConstRef _block, BlockChain const& _bc, ImportRequirements::value _ir = ImportRequirements::Default);
/// Finalise the block, applying the earned rewards.
void applyRewards(std::vector<BlockInfo> const& _uncleBlockHeaders);

12
libjsqrc/ethereumjs/README.md

@ -17,7 +17,7 @@ You need to run a local ethrereum node to use this library.
### Node.js
$ npm install ethereum.js
$ npm install web3
### Meteor.js
@ -26,20 +26,24 @@ You need to run a local ethrereum node to use this library.
### As Browser module
Bower
$ bower install ethereum.js
$ bower install web3
Component
$ component install ethereum/ethereum.js
$ component install ethereum/web3.js
* Include `ethereum.min.js` in your html file. (not required for the meteor package)
* Include [bignumber.js](https://github.com/MikeMcl/bignumber.js/) (not required for the meteor package)
## Usage
Require the library (not required for the meteor package):
You can require the library (not required for the meteor package):
var web3 = require('ethereum.js');
Or use it directly from global namespace:
console.log(web3); // {eth: .., shh: ...} // it's here!
Set a provider (QtSyncProvider, HttpProvider)
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

12
libjsqrc/ethereumjs/bower.json

@ -1,22 +1,22 @@
{
"name": "web3",
"namespace": "ethereum",
"version": "0.2.5",
"version": "0.2.6",
"description": "Ethereum Compatible JavaScript API",
"main": [
"./dist/ethereum.js",
"./dist/ethereum.min.js"
"./dist/web3.js",
"./dist/web3.min.js"
],
"dependencies": {
"bignumber.js": ">=2.0.0"
},
"repository": {
"type": "git",
"url": "https://github.com/ethereum/ethereum.js.git"
"url": "https://github.com/ethereum/web3.js.git"
},
"homepage": "https://github.com/ethereum/ethereum.js",
"homepage": "https://github.com/ethereum/web3.js",
"bugs": {
"url": "https://github.com/ethereum/ethereum.js/issues"
"url": "https://github.com/ethereum/web3.js/issues"
},
"keywords": [
"ethereum",

242
libjsqrc/ethereumjs/dist/web3-light.js

@ -15,10 +15,10 @@ require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof requ
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file abi.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* Gav Wood <g@ethdev.com>
/**
* @file abi.js
* @author Marek Kotewicz <marek@ethdev.com>
* @author Gav Wood <g@ethdev.com>
* @date 2014
*/
@ -26,6 +26,7 @@ var utils = require('../utils/utils');
var c = require('../utils/config');
var types = require('./types');
var f = require('./formatters');
var solUtils = require('./utils');
/**
* throw incorrect type error
@ -238,14 +239,26 @@ var outputParser = function (json) {
return parser;
};
var formatConstructorParams = function (abi, params) {
var constructor = solUtils.getConstructor(abi, params.length);
if (!constructor) {
if (params.length > 0) {
console.warn("didn't found matching constructor, using default one");
}
return '';
}
return formatInput(constructor.inputs, params);
};
module.exports = {
inputParser: inputParser,
outputParser: outputParser,
formatInput: formatInput,
formatOutput: formatOutput
formatOutput: formatOutput,
formatConstructorParams: formatConstructorParams
};
},{"../utils/config":5,"../utils/utils":6,"./formatters":2,"./types":3}],2:[function(require,module,exports){
},{"../utils/config":6,"../utils/utils":7,"./formatters":2,"./types":3,"./utils":4}],2:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -445,7 +458,7 @@ module.exports = {
};
},{"../utils/config":5,"../utils/utils":6,"bignumber.js":"bignumber.js"}],3:[function(require,module,exports){
},{"../utils/config":6,"../utils/utils":7,"bignumber.js":"bignumber.js"}],3:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -525,6 +538,76 @@ module.exports = {
},{"./formatters":2}],4:[function(require,module,exports){
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file utils.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
/**
* Returns the contstructor with matching number of arguments
*
* @method getConstructor
* @param {Array} abi
* @param {Number} numberOfArgs
* @returns {Object} constructor function abi
*/
var getConstructor = function (abi, numberOfArgs) {
return abi.filter(function (f) {
return f.type === 'constructor' && f.inputs.length === numberOfArgs;
})[0];
};
/**
* Filters all functions from input abi
*
* @method filterFunctions
* @param {Array} abi
* @returns {Array} abi array with filtered objects of type 'function'
*/
var filterFunctions = function (json) {
return json.filter(function (current) {
return current.type === 'function';
});
};
/**
* Filters all events from input abi
*
* @method filterEvents
* @param {Array} abi
* @returns {Array} abi array with filtered objects of type 'event'
*/
var filterEvents = function (json) {
return json.filter(function (current) {
return current.type === 'event';
});
};
module.exports = {
getConstructor: getConstructor,
filterFunctions: filterFunctions,
filterEvents: filterEvents
};
},{}],5:[function(require,module,exports){
'use strict';
// go env doesn't have and need XMLHttpRequest
@ -535,7 +618,7 @@ if (typeof XMLHttpRequest === 'undefined') {
}
},{}],5:[function(require,module,exports){
},{}],6:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -606,7 +689,7 @@ module.exports = {
};
},{"bignumber.js":"bignumber.js"}],6:[function(require,module,exports){
},{"bignumber.js":"bignumber.js"}],7:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -770,32 +853,6 @@ var extractTypeName = function (name) {
return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : "";
};
/**
* Filters all functions from input abi
*
* @method filterFunctions
* @param {Array} abi
* @returns {Array} abi array with filtered objects of type 'function'
*/
var filterFunctions = function (json) {
return json.filter(function (current) {
return current.type === 'function';
});
};
/**
* Filters all events from input abi
*
* @method filterEvents
* @param {Array} abi
* @returns {Array} abi array with filtered objects of type 'event'
*/
var filterEvents = function (json) {
return json.filter(function (current) {
return current.type === 'event';
});
};
/**
* Converts value to it's decimal representation in string
*
@ -958,14 +1015,25 @@ var toTwosComplement = function (number) {
};
/**
* Checks if the given string has proper length
* Checks if the given string is strictly an address
*
* @method isStrictAddress
* @param {String} address the given HEX adress
* @return {Boolean}
*/
var isStrictAddress = function (address) {
return /^0x[0-9a-f]{40}$/.test(address);
};
/**
* Checks if the given string is an address
*
* @method isAddress
* @param {String} address the given HEX adress
* @return {Boolean}
*/
var isAddress = function (address) {
return /^0x[0-9a-f]{40}$/.test(address);
return /^(0x)?[0-9a-f]{40}$/.test(address);
};
/**
@ -976,7 +1044,7 @@ var isAddress = function (address) {
* @return {String} formatted address
*/
var toAddress = function (address) {
if (isAddress(address)) {
if (isStrictAddress(address)) {
return address;
}
@ -1080,14 +1148,13 @@ module.exports = {
fromAscii: fromAscii,
extractDisplayName: extractDisplayName,
extractTypeName: extractTypeName,
filterFunctions: filterFunctions,
filterEvents: filterEvents,
toWei: toWei,
fromWei: fromWei,
toBigNumber: toBigNumber,
toTwosComplement: toTwosComplement,
toAddress: toAddress,
isBigNumber: isBigNumber,
isStrictAddress: isStrictAddress,
isAddress: isAddress,
isFunction: isFunction,
isString: isString,
@ -1098,12 +1165,12 @@ module.exports = {
};
},{"bignumber.js":"bignumber.js"}],7:[function(require,module,exports){
},{"bignumber.js":"bignumber.js"}],8:[function(require,module,exports){
module.exports={
"version": "0.2.5"
"version": "0.2.6"
}
},{}],8:[function(require,module,exports){
},{}],9:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -1164,7 +1231,7 @@ var web3Properties = [
}),
new Property({
name: 'version.ethereum',
getter: 'eth_version',
getter: 'eth_protocolVersion',
inputFormatter: utils.toDecimal
}),
new Property({
@ -1259,7 +1326,7 @@ setupMethods(web3.shh, shh.methods);
module.exports = web3;
},{"./utils/config":5,"./utils/utils":6,"./version.json":7,"./web3/db":10,"./web3/eth":12,"./web3/filter":14,"./web3/formatters":15,"./web3/method":18,"./web3/net":19,"./web3/property":20,"./web3/requestmanager":22,"./web3/shh":23,"./web3/watches":25}],9:[function(require,module,exports){
},{"./utils/config":6,"./utils/utils":7,"./version.json":8,"./web3/db":11,"./web3/eth":13,"./web3/filter":15,"./web3/formatters":16,"./web3/method":19,"./web3/net":20,"./web3/property":21,"./web3/requestmanager":23,"./web3/shh":24,"./web3/watches":26}],10:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -1283,8 +1350,9 @@ module.exports = web3;
*/
var web3 = require('../web3');
var abi = require('../solidity/abi');
var solAbi = require('../solidity/abi');
var utils = require('../utils/utils');
var solUtils = require('../solidity/utils');
var eventImpl = require('./event');
var signature = require('./signature');
@ -1304,11 +1372,11 @@ var addFunctionRelatedPropertiesToContract = function (contract) {
};
var addFunctionsToContract = function (contract, desc, address) {
var inputParser = abi.inputParser(desc);
var outputParser = abi.outputParser(desc);
var inputParser = solAbi.inputParser(desc);
var outputParser = solAbi.outputParser(desc);
// create contract functions
utils.filterFunctions(desc).forEach(function (method) {
solUtils.filterFunctions(desc).forEach(function (method) {
var displayName = utils.extractDisplayName(method.name);
var typeName = utils.extractTypeName(method.name);
@ -1360,14 +1428,14 @@ var addFunctionsToContract = function (contract, desc, address) {
var addEventRelatedPropertiesToContract = function (contract, desc, address) {
contract.address = address;
contract._onWatchEventResult = function (data) {
var matchingEvent = event.getMatchingEvent(utils.filterEvents(desc));
var matchingEvent = event.getMatchingEvent(solUtils.filterEvents(desc));
var parser = eventImpl.outputParser(matchingEvent);
return parser(data);
};
Object.defineProperty(contract, 'topics', {
get: function() {
return utils.filterEvents(desc).map(function (e) {
return solUtils.filterEvents(desc).map(function (e) {
return signature.eventSignatureFromAscii(e.name);
});
}
@ -1377,7 +1445,7 @@ var addEventRelatedPropertiesToContract = function (contract, desc, address) {
var addEventsToContract = function (contract, desc, address) {
// create contract events
utils.filterEvents(desc).forEach(function (e) {
solUtils.filterEvents(desc).forEach(function (e) {
var impl = function () {
var params = Array.prototype.slice.call(arguments);
@ -1435,7 +1503,7 @@ var contract = function (abi) {
return Contract.bind(null, abi);
};
function Contract(abi, address) {
function Contract(abi, options) {
// workaround for invalid assumption that method.name is the full anonymous prototype of the method.
// it's not. it's just the name. the rest of the code assumes it's actually the anonymous
@ -1449,6 +1517,17 @@ function Contract(abi, address) {
}
});
var address = '';
if (utils.isAddress(options)) {
address = options;
} else { // is a source code!
// TODO, parse the rest of the args
var code = options;
var args = Array.prototype.slice.call(arguments, 2);
var bytes = solAbi.formatConstructorParams(abi, args);
address = web3.eth.sendTransaction({data: code + bytes});
}
var result = {};
addFunctionRelatedPropertiesToContract(result);
addFunctionsToContract(result, abi, address);
@ -1461,7 +1540,7 @@ function Contract(abi, address) {
module.exports = contract;
},{"../solidity/abi":1,"../utils/utils":6,"../web3":8,"./event":13,"./signature":24}],10:[function(require,module,exports){
},{"../solidity/abi":1,"../solidity/utils":4,"../utils/utils":7,"../web3":9,"./event":14,"./signature":25}],11:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -1519,7 +1598,7 @@ module.exports = {
methods: methods
};
},{"./method":18}],11:[function(require,module,exports){
},{"./method":19}],12:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -1559,7 +1638,7 @@ module.exports = {
};
},{"../utils/utils":6}],12:[function(require,module,exports){
},{"../utils/utils":7}],13:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -1664,15 +1743,15 @@ var getBlock = new Method({
name: 'getBlock',
call: blockCall,
params: 2,
inputFormatter: [formatters.inputBlockNumberFormatter, function (val) { return !!val; }],
inputFormatter: [utils.toHex, function (val) { return !!val; }],
outputFormatter: formatters.outputBlockFormatter
});
var getUncle = new Method({
name: 'getUncle',
call: uncleCall,
params: 3,
inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex, function (val) { return !!val; }],
params: 2,
inputFormatter: [utils.toHex, utils.toHex],
outputFormatter: formatters.outputBlockFormatter,
});
@ -1796,7 +1875,7 @@ var properties = [
new Property({
name: 'gasPrice',
getter: 'eth_gasPrice',
outputFormatter: formatters.inputNumberFormatter
outputFormatter: formatters.outputBigNumberFormatter
}),
new Property({
name: 'accounts',
@ -1815,7 +1894,7 @@ module.exports = {
};
},{"../utils/utils":6,"./formatters":15,"./method":18,"./property":20}],13:[function(require,module,exports){
},{"../utils/utils":7,"./formatters":16,"./method":19,"./property":21}],14:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -1955,7 +2034,7 @@ module.exports = {
};
},{"../solidity/abi":1,"../utils/utils":6,"./signature":24}],14:[function(require,module,exports){
},{"../solidity/abi":1,"../utils/utils":7,"./signature":25}],15:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -2067,7 +2146,7 @@ Filter.prototype.get = function () {
module.exports = Filter;
},{"../utils/utils":6,"./formatters":15,"./requestmanager":22}],15:[function(require,module,exports){
},{"../utils/utils":7,"./formatters":16,"./requestmanager":23}],16:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -2280,7 +2359,7 @@ module.exports = {
};
},{"../utils/config":5,"../utils/utils":6}],16:[function(require,module,exports){
},{"../utils/config":6,"../utils/utils":7}],17:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -2343,7 +2422,7 @@ HttpProvider.prototype.sendAsync = function (payload, callback) {
module.exports = HttpProvider;
},{"xmlhttprequest":4}],17:[function(require,module,exports){
},{"xmlhttprequest":5}],18:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -2436,7 +2515,7 @@ Jsonrpc.prototype.toBatchPayload = function (messages) {
module.exports = Jsonrpc;
},{}],18:[function(require,module,exports){
},{}],19:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -2597,7 +2676,7 @@ Method.prototype.send = function () {
module.exports = Method;
},{"../utils/utils":6,"./errors":11,"./requestmanager":22}],19:[function(require,module,exports){
},{"../utils/utils":7,"./errors":12,"./requestmanager":23}],20:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -2647,7 +2726,7 @@ module.exports = {
};
},{"../utils/utils":6,"./property":20}],20:[function(require,module,exports){
},{"../utils/utils":7,"./property":21}],21:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -2753,7 +2832,7 @@ Property.prototype.set = function (value) {
module.exports = Property;
},{"./requestmanager":22}],21:[function(require,module,exports){
},{"./requestmanager":23}],22:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -2788,7 +2867,7 @@ QtSyncProvider.prototype.send = function (payload) {
module.exports = QtSyncProvider;
},{}],22:[function(require,module,exports){
},{}],23:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -3009,7 +3088,7 @@ RequestManager.prototype.poll = function () {
module.exports = RequestManager;
},{"../utils/config":5,"../utils/utils":6,"./errors":11,"./jsonrpc":17}],23:[function(require,module,exports){
},{"../utils/config":6,"../utils/utils":7,"./errors":12,"./jsonrpc":18}],24:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -3079,7 +3158,7 @@ module.exports = {
};
},{"./formatters":15,"./method":18}],24:[function(require,module,exports){
},{"./formatters":16,"./method":19}],25:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -3123,7 +3202,7 @@ module.exports = {
};
},{"../utils/config":5,"../web3":8}],25:[function(require,module,exports){
},{"../utils/config":6,"../web3":9}],26:[function(require,module,exports){
/*
This file is part of ethereum.js.
@ -3226,7 +3305,7 @@ module.exports = {
};
},{"./method":18}],26:[function(require,module,exports){
},{"./method":19}],27:[function(require,module,exports){
},{}],"bignumber.js":[function(require,module,exports){
'use strict';
@ -3235,22 +3314,21 @@ module.exports = BigNumber; // jshint ignore:line
},{}],"web3":[function(require,module,exports){
// dont override global variable
if (typeof web3 !== 'undefined') {
var web3;
}
web3 = require('./lib/web3');
var web3 = require('./lib/web3');
web3.providers.HttpProvider = require('./lib/web3/httpprovider');
web3.providers.QtSyncProvider = require('./lib/web3/qtsync');
web3.eth.contract = require('./lib/web3/contract');
web3.abi = require('./lib/solidity/abi');
// dont override global variable
if (typeof window !== 'undefined' && typeof window.web3 === 'undefined') {
window.web3 = web3;
}
module.exports = web3;
},{"./lib/solidity/abi":1,"./lib/web3":8,"./lib/web3/contract":9,"./lib/web3/httpprovider":16,"./lib/web3/qtsync":21}]},{},["web3"])
},{"./lib/solidity/abi":1,"./lib/web3":9,"./lib/web3/contract":10,"./lib/web3/httpprovider":17,"./lib/web3/qtsync":22}]},{},["web3"])
//# sourceMappingURL=web3-light.js.map

18
libjsqrc/ethereumjs/dist/web3-light.js.map

File diff suppressed because one or more lines are too long

2
libjsqrc/ethereumjs/dist/web3-light.min.js

File diff suppressed because one or more lines are too long

4095
libjsqrc/ethereumjs/dist/web3.js

File diff suppressed because it is too large

24
libjsqrc/ethereumjs/dist/web3.js.map

File diff suppressed because one or more lines are too long

4
libjsqrc/ethereumjs/dist/web3.min.js

File diff suppressed because one or more lines are too long

13
libjsqrc/ethereumjs/index.js

@ -1,14 +1,13 @@
// dont override global variable
if (typeof web3 !== 'undefined') {
var web3;
}
web3 = require('./lib/web3');
var web3 = require('./lib/web3');
web3.providers.HttpProvider = require('./lib/web3/httpprovider');
web3.providers.QtSyncProvider = require('./lib/web3/qtsync');
web3.eth.contract = require('./lib/web3/contract');
web3.abi = require('./lib/solidity/abi');
// dont override global variable
if (typeof window !== 'undefined' && typeof window.web3 === 'undefined') {
window.web3 = web3;
}
module.exports = web3;

23
libjsqrc/ethereumjs/lib/solidity/abi.js

@ -14,10 +14,10 @@
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file abi.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* Gav Wood <g@ethdev.com>
/**
* @file abi.js
* @author Marek Kotewicz <marek@ethdev.com>
* @author Gav Wood <g@ethdev.com>
* @date 2014
*/
@ -25,6 +25,7 @@ var utils = require('../utils/utils');
var c = require('../utils/config');
var types = require('./types');
var f = require('./formatters');
var solUtils = require('./utils');
/**
* throw incorrect type error
@ -237,9 +238,21 @@ var outputParser = function (json) {
return parser;
};
var formatConstructorParams = function (abi, params) {
var constructor = solUtils.getConstructor(abi, params.length);
if (!constructor) {
if (params.length > 0) {
console.warn("didn't found matching constructor, using default one");
}
return '';
}
return formatInput(constructor.inputs, params);
};
module.exports = {
inputParser: inputParser,
outputParser: outputParser,
formatInput: formatInput,
formatOutput: formatOutput
formatOutput: formatOutput,
formatConstructorParams: formatConstructorParams
};

68
libjsqrc/ethereumjs/lib/solidity/utils.js

@ -0,0 +1,68 @@
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file utils.js
* @author Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
/**
* Returns the contstructor with matching number of arguments
*
* @method getConstructor
* @param {Array} abi
* @param {Number} numberOfArgs
* @returns {Object} constructor function abi
*/
var getConstructor = function (abi, numberOfArgs) {
return abi.filter(function (f) {
return f.type === 'constructor' && f.inputs.length === numberOfArgs;
})[0];
};
/**
* Filters all functions from input abi
*
* @method filterFunctions
* @param {Array} abi
* @returns {Array} abi array with filtered objects of type 'function'
*/
var filterFunctions = function (json) {
return json.filter(function (current) {
return current.type === 'function';
});
};
/**
* Filters all events from input abi
*
* @method filterEvents
* @param {Array} abi
* @returns {Array} abi array with filtered objects of type 'event'
*/
var filterEvents = function (json) {
return json.filter(function (current) {
return current.type === 'event';
});
};
module.exports = {
getConstructor: getConstructor,
filterFunctions: filterFunctions,
filterEvents: filterEvents
};

46
libjsqrc/ethereumjs/lib/utils/utils.js

@ -161,32 +161,6 @@ var extractTypeName = function (name) {
return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : "";
};
/**
* Filters all functions from input abi
*
* @method filterFunctions
* @param {Array} abi
* @returns {Array} abi array with filtered objects of type 'function'
*/
var filterFunctions = function (json) {
return json.filter(function (current) {
return current.type === 'function';
});
};
/**
* Filters all events from input abi
*
* @method filterEvents
* @param {Array} abi
* @returns {Array} abi array with filtered objects of type 'event'
*/
var filterEvents = function (json) {
return json.filter(function (current) {
return current.type === 'event';
});
};
/**
* Converts value to it's decimal representation in string
*
@ -349,14 +323,25 @@ var toTwosComplement = function (number) {
};
/**
* Checks if the given string has proper length
* Checks if the given string is strictly an address
*
* @method isStrictAddress
* @param {String} address the given HEX adress
* @return {Boolean}
*/
var isStrictAddress = function (address) {
return /^0x[0-9a-f]{40}$/.test(address);
};
/**
* Checks if the given string is an address
*
* @method isAddress
* @param {String} address the given HEX adress
* @return {Boolean}
*/
var isAddress = function (address) {
return /^0x[0-9a-f]{40}$/.test(address);
return /^(0x)?[0-9a-f]{40}$/.test(address);
};
/**
@ -367,7 +352,7 @@ var isAddress = function (address) {
* @return {String} formatted address
*/
var toAddress = function (address) {
if (isAddress(address)) {
if (isStrictAddress(address)) {
return address;
}
@ -471,14 +456,13 @@ module.exports = {
fromAscii: fromAscii,
extractDisplayName: extractDisplayName,
extractTypeName: extractTypeName,
filterFunctions: filterFunctions,
filterEvents: filterEvents,
toWei: toWei,
fromWei: fromWei,
toBigNumber: toBigNumber,
toTwosComplement: toTwosComplement,
toAddress: toAddress,
isBigNumber: isBigNumber,
isStrictAddress: isStrictAddress,
isAddress: isAddress,
isFunction: isFunction,
isString: isString,

2
libjsqrc/ethereumjs/lib/version.json

@ -1,3 +1,3 @@
{
"version": "0.2.5"
"version": "0.2.6"
}

2
libjsqrc/ethereumjs/lib/web3.js

@ -58,7 +58,7 @@ var web3Properties = [
}),
new Property({
name: 'version.ethereum',
getter: 'eth_version',
getter: 'eth_protocolVersion',
inputFormatter: utils.toDecimal
}),
new Property({

28
libjsqrc/ethereumjs/lib/web3/contract.js

@ -21,8 +21,9 @@
*/
var web3 = require('../web3');
var abi = require('../solidity/abi');
var solAbi = require('../solidity/abi');
var utils = require('../utils/utils');
var solUtils = require('../solidity/utils');
var eventImpl = require('./event');
var signature = require('./signature');
@ -42,11 +43,11 @@ var addFunctionRelatedPropertiesToContract = function (contract) {
};
var addFunctionsToContract = function (contract, desc, address) {
var inputParser = abi.inputParser(desc);
var outputParser = abi.outputParser(desc);
var inputParser = solAbi.inputParser(desc);
var outputParser = solAbi.outputParser(desc);
// create contract functions
utils.filterFunctions(desc).forEach(function (method) {
solUtils.filterFunctions(desc).forEach(function (method) {
var displayName = utils.extractDisplayName(method.name);
var typeName = utils.extractTypeName(method.name);
@ -98,14 +99,14 @@ var addFunctionsToContract = function (contract, desc, address) {
var addEventRelatedPropertiesToContract = function (contract, desc, address) {
contract.address = address;
contract._onWatchEventResult = function (data) {
var matchingEvent = event.getMatchingEvent(utils.filterEvents(desc));
var matchingEvent = event.getMatchingEvent(solUtils.filterEvents(desc));
var parser = eventImpl.outputParser(matchingEvent);
return parser(data);
};
Object.defineProperty(contract, 'topics', {
get: function() {
return utils.filterEvents(desc).map(function (e) {
return solUtils.filterEvents(desc).map(function (e) {
return signature.eventSignatureFromAscii(e.name);
});
}
@ -115,7 +116,7 @@ var addEventRelatedPropertiesToContract = function (contract, desc, address) {
var addEventsToContract = function (contract, desc, address) {
// create contract events
utils.filterEvents(desc).forEach(function (e) {
solUtils.filterEvents(desc).forEach(function (e) {
var impl = function () {
var params = Array.prototype.slice.call(arguments);
@ -173,7 +174,7 @@ var contract = function (abi) {
return Contract.bind(null, abi);
};
function Contract(abi, address) {
function Contract(abi, options) {
// workaround for invalid assumption that method.name is the full anonymous prototype of the method.
// it's not. it's just the name. the rest of the code assumes it's actually the anonymous
@ -187,6 +188,17 @@ function Contract(abi, address) {
}
});
var address = '';
if (utils.isAddress(options)) {
address = options;
} else { // is a source code!
// TODO, parse the rest of the args
var code = options;
var args = Array.prototype.slice.call(arguments, 2);
var bytes = solAbi.formatConstructorParams(abi, args);
address = web3.eth.sendTransaction({data: code + bytes});
}
var result = {};
addFunctionRelatedPropertiesToContract(result);
addFunctionsToContract(result, abi, address);

8
libjsqrc/ethereumjs/lib/web3/eth.js

@ -102,15 +102,15 @@ var getBlock = new Method({
name: 'getBlock',
call: blockCall,
params: 2,
inputFormatter: [formatters.inputBlockNumberFormatter, function (val) { return !!val; }],
inputFormatter: [utils.toHex, function (val) { return !!val; }],
outputFormatter: formatters.outputBlockFormatter
});
var getUncle = new Method({
name: 'getUncle',
call: uncleCall,
params: 3,
inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex, function (val) { return !!val; }],
params: 2,
inputFormatter: [utils.toHex, utils.toHex],
outputFormatter: formatters.outputBlockFormatter,
});
@ -234,7 +234,7 @@ var properties = [
new Property({
name: 'gasPrice',
getter: 'eth_gasPrice',
outputFormatter: formatters.inputNumberFormatter
outputFormatter: formatters.outputBigNumberFormatter
}),
new Property({
name: 'accounts',

2
libjsqrc/ethereumjs/package.js

@ -1,7 +1,7 @@
/* jshint ignore:start */
Package.describe({
name: 'ethereum:js',
version: '0.2.5',
version: '0.2.6',
summary: 'Ethereum JavaScript API, middleware to talk to a ethreum node over RPC',
git: 'https://github.com/ethereum/ethereum.js',
// By default, Meteor will default to using README.md for documentation.

8
libjsqrc/ethereumjs/package.json

@ -1,7 +1,7 @@
{
"name": "web3",
"namespace": "ethereum",
"version": "0.2.5",
"version": "0.2.6",
"description": "Ethereum JavaScript API, middleware to talk to a ethereum node over RPC",
"main": "./index.js",
"directories": {
@ -49,11 +49,11 @@
},
"repository": {
"type": "git",
"url": "https://github.com/ethereum/ethereum.js.git"
"url": "https://github.com/ethereum/web3.js.git"
},
"homepage": "https://github.com/ethereum/ethereum.js",
"homepage": "https://github.com/ethereum/web3.js",
"bugs": {
"url": "https://github.com/ethereum/ethereum.js/issues"
"url": "https://github.com/ethereum/web3.js/issues"
},
"keywords": [
"ethereum",

106
libjsqrc/ethereumjs/test/abi.formatConstructorParams.js

@ -0,0 +1,106 @@
var chai = require('chai');
var assert = require('assert');
var abi = require('../lib/solidity/abi');
describe('lib/solidity/abi', function () {
describe('formatConstructorParams', function () {
it('should format uint256 properly', function () {
// given
var description = [{
"name": "test",
"type": "constructor",
"inputs": [{
"name": "a",
"type": "uint256"
}
]
}];
// when
var bytes = abi.formatConstructorParams(description, [2]);
// then
assert.equal(bytes, '0000000000000000000000000000000000000000000000000000000000000002');
});
it('should not find matching constructor', function () {
// given
var description = [{
"name": "test",
"type": "constructor",
"inputs": [{
"name": "a",
"type": "uint256"
}
]
}];
// when
var bytes = abi.formatConstructorParams(description, []);
// then
assert.equal(bytes, '');
});
it('should not find matching constructor2', function () {
// given
var description = [{
"name": "test",
"type": "constructor",
"inputs": [{
"name": "a",
"type": "uint256"
}
]
}];
// when
var bytes = abi.formatConstructorParams(description, [1,2]);
// then
assert.equal(bytes, '');
});
it('should not find matching constructor3', function () {
// given
var description = [{
"name": "test",
"type": "function",
"inputs": [{
"name": "a",
"type": "uint256"
}
]
}];
// when
var bytes = abi.formatConstructorParams(description, [2]);
// then
assert.equal(bytes, '');
});
it('should find matching constructor with multiple args', function () {
// given
var description = [{
"name": "test",
"type": "constructor",
"inputs": [{
"name": "a",
"type": "uint256"
}, {
"name": "b",
"type": "uint256"
}]
}];
// when
var bytes = abi.formatConstructorParams(description, ['1', '5']);
// then
assert.equal(bytes, '00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000005');
});
});
});

11
libjsqrc/ethereumjs/test/abi.inputParser.js

@ -1,6 +1,7 @@
var assert = require('assert');
var chai = require('chai');
var assert = chai.assert;
var BigNumber = require('bignumber.js');
var abi = require('../lib/solidity/abi.js');
var abi = require('../lib/solidity/abi');
var clone = function (object) { return JSON.parse(JSON.stringify(object)); };
var description = [{
@ -19,9 +20,9 @@ var description = [{
]
}];
describe('lib/solidity/abi', function() {
describe('inputParser', function() {
it('should parse input uint', function() {
describe('lib/solidity/abi', function () {
describe('inputParser', function () {
it('should parse input uint', function () {
// given
var d = clone(description);

2
libjsqrc/ethereumjs/test/utils.filters.js

@ -1,5 +1,5 @@
var assert = require('assert');
var utils = require('../lib/utils/utils.js');
var utils = require('../lib/solidity/utils');
describe('lib/utils/utils', function() {
it('should filter functions and events from input array properly', function () {

2
libjsqrc/ethereumjs/test/utils.isAddress.js

@ -8,7 +8,7 @@ var tests = [
{ value: 'function', is: false},
{ value: {}, is: false},
{ value: '0xc6d9d2cd449a754c494264e1809c50e34d64562b', is: true },
{ value: 'c6d9d2cd449a754c494264e1809c50e34d64562b', is: false }
{ value: 'c6d9d2cd449a754c494264e1809c50e34d64562b', is: true }
];
describe('lib/utils/utils', function () {

23
libjsqrc/ethereumjs/test/utils.isStrictAddress.js

@ -0,0 +1,23 @@
var chai = require('chai');
var utils = require('../lib/utils/utils.js');
var assert = chai.assert;
var tests = [
{ value: function () {}, is: false},
{ value: new Function(), is: false},
{ value: 'function', is: false},
{ value: {}, is: false},
{ value: '0xc6d9d2cd449a754c494264e1809c50e34d64562b', is: true },
{ value: 'c6d9d2cd449a754c494264e1809c50e34d64562b', is: false }
];
describe('lib/utils/utils', function () {
describe('isStrictAddress', function () {
tests.forEach(function (test) {
it('shoud test if value ' + test.value + ' is address: ' + test.is, function () {
assert.equal(utils.isStrictAddress(test.value), test.is);
});
});
});
});

49
libjsqrc/ethereumjs/test/web3.eth.contract.js

@ -1,5 +1,7 @@
var assert = require('assert');
var contract = require('../lib/web3/contract.js');
var FakeHttpProvider = require('./helpers/FakeHttpProvider');
var web3 = require('../index');
describe('web3.eth.contract', function() {
it('should create simple contract with one method from abi with explicit type name', function () {
@ -20,10 +22,11 @@ describe('web3.eth.contract', function() {
}
]
}];
var address = '0x1234567890123456789012345678901234567890';
// when
var Con = contract(description);
var myCon = new Con(null);
var myCon = new Con(address);
// then
assert.equal('function', typeof myCon.test);
@ -48,10 +51,11 @@ describe('web3.eth.contract', function() {
}
]
}];
var address = '0x1234567890123456789012345678901234567890';
// when
var Con = contract(description);
var myCon = new Con(null);
var myCon = new Con(address);
// then
assert.equal('function', typeof myCon.test);
@ -90,10 +94,11 @@ describe('web3.eth.contract', function() {
}
]
}];
var address = '0x1234567890123456789012345678901234567890';
// when
var Con = contract(description);
var myCon = new Con(null);
var myCon = new Con(address);
// then
assert.equal('function', typeof myCon.test);
@ -134,10 +139,11 @@ describe('web3.eth.contract', function() {
}
]
}];
var address = '0x1234567890123456789012345678901234567890';
// when
var Con = contract(description);
var myCon = new Con(null);
var myCon = new Con(address);
// then
assert.equal('function', typeof myCon.test);
@ -162,11 +168,11 @@ describe('web3.eth.contract', function() {
}
]
}];
var address = '0x1234567890123456789012345678901234567890';
// when
var Con = contract(description);
var myCon = new Con(null);
var myCon = new Con(address);
// then
assert.equal('undefined', typeof myCon.test);
@ -191,11 +197,11 @@ describe('web3.eth.contract', function() {
}
]
}];
var address = '0x1234567890123456789012345678901234567890';
// when
var Con = contract(description);
var myCon = new Con(null);
var myCon = new Con(address);
// then
assert.equal('function', typeof myCon.test);
@ -203,5 +209,32 @@ describe('web3.eth.contract', function() {
});
it('should create contract with nondefault constructor', function (done) {
var provider = new FakeHttpProvider();
web3.setProvider(provider);
web3.reset(); // reset different polls
var address = '0x1234567890123456789012345678901234567890';
var code = '0x31241231231123123123123121cf121212i123123123123123512312412512111111';
var description = [{
"name": "test",
"type": "constructor",
"inputs": [{
"name": "a",
"type": "uint256"
}
]
}];
provider.injectResult(address);
provider.injectValidation(function (payload) {
assert.equal(payload.jsonrpc, '2.0');
assert.equal(payload.method, 'eth_sendTransaction');
assert.equal(payload.params[0].data, code + '0000000000000000000000000000000000000000000000000000000000000002');
done();
});
var Con = contract(description);
var myCon = new Con(code, 2);
});
});

39
libjsqrc/ethereumjs/test/web3.eth.gasPrice.js

@ -0,0 +1,39 @@
var chai = require('chai');
var assert = chai.assert;
var web3 = require('../index');
var BigNumber = require('bignumber.js');
var FakeHttpProvider = require('./helpers/FakeHttpProvider');
var method = 'gasPrice';
var tests = [{
result: '0x15f90',
formattedResult: new BigNumber(90000),
call: 'eth_'+ method
}];
describe('web3.eth', function () {
describe(method, function () {
tests.forEach(function (test, index) {
it('property test: ' + index, function () {
// given
var provider = new FakeHttpProvider();
web3.setProvider(provider);
provider.injectResult(test.result);
provider.injectValidation(function (payload) {
assert.equal(payload.jsonrpc, '2.0');
assert.equal(payload.method, test.call);
assert.deepEqual(payload.params, []);
});
// when
var result = web3.eth[method];
// then
assert.deepEqual(test.formattedResult, result);
});
});
});
});

6
libjsqrc/ethereumjs/test/web3.eth.getUncle.js

@ -118,19 +118,19 @@ var formattedBlockResultWithTx = {
var tests = [{
args: ['0x47d33b27bb249a2dbab4c0612bf9caf4c1950855', 2],
formattedArgs: ['0x47d33b27bb249a2dbab4c0612bf9caf4c1950855', '0x2', false],
formattedArgs: ['0x47d33b27bb249a2dbab4c0612bf9caf4c1950855', '0x2'],
result: blockResult,
formattedResult: formattedBlockResult,
call: 'eth_getUncleByBlockHashAndIndex'
},{
args: [436, 1],
formattedArgs: ['0x1b4', '0x1', false],
formattedArgs: ['0x1b4', '0x1'],
result: blockResult,
formattedResult: formattedBlockResult,
call: 'eth_getUncleByBlockNumberAndIndex'
},{
args: [436, 1, true],
formattedArgs: ['0x1b4', '0x1', true],
formattedArgs: ['0x1b4', '0x1'],
result: blockResultWithTx,
formattedResult: formattedBlockResultWithTx,
call: 'eth_getUncleByBlockNumberAndIndex'

2
libp2p/Common.h

@ -145,7 +145,7 @@ struct PeerSessionInfo
unsigned short port;
std::chrono::steady_clock::duration lastPing;
std::set<CapDesc> caps;
unsigned socket;
unsigned socketId;
std::map<std::string, std::string> notes;
};

2
libp2p/Network.cpp

@ -84,7 +84,7 @@ std::set<bi::address> Network::getInterfaceAddresses()
for (auto ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{
if (!ifa->ifa_addr || string(ifa->ifa_name) == "lo0")
if (!ifa->ifa_addr || string(ifa->ifa_name) == "lo0" || !(ifa->ifa_flags & IFF_UP))
continue;
if (ifa->ifa_addr->sa_family == AF_INET)

11
libp2p/NodeTable.cpp

@ -178,7 +178,7 @@ void NodeTable::discover(NodeId _node, unsigned _round, shared_ptr<set<shared_pt
tried.push_back(r);
FindNode p(r->endpoint.udp, _node);
p.sign(m_secret);
m_findNodeTimeout.push_back(make_pair(_node, chrono::steady_clock::now()));
m_findNodeTimeout.push_back(make_pair(r->id, chrono::steady_clock::now()));
m_socketPointer->send(p);
}
@ -459,11 +459,14 @@ void NodeTable::onReceived(UDPSocketFace*, bi::udp::endpoint const& _from, bytes
case Neighbours::type:
{
bool expected = false;
auto now = chrono::steady_clock::now();
m_findNodeTimeout.remove_if([&](NodeIdTimePoint const& t)
{
if (t.first == nodeid && chrono::steady_clock::now() - t.second < c_reqTimeout)
if (t.first == nodeid && now - t.second < c_reqTimeout)
expected = true;
return t.first == nodeid;
else if (t.first == nodeid)
return true;
return false;
});
if (!expected)
@ -483,7 +486,7 @@ void NodeTable::onReceived(UDPSocketFace*, bi::udp::endpoint const& _from, bytes
FindNode in = FindNode::fromBytesConstRef(_from, rlpBytes);
vector<shared_ptr<NodeEntry>> nearest = nearestNodeEntries(in.target);
static unsigned const nlimit = (m_socketPointer->maxDatagramSize - 13) / 87;
static unsigned const nlimit = (m_socketPointer->maxDatagramSize - 111) / 87;
for (unsigned offset = 0; offset < nearest.size(); offset += nlimit)
{
Neighbours out(_from, nearest, offset, nlimit);

1
libp2p/Session.cpp

@ -48,6 +48,7 @@ Session::Session(Host* _s, RLPXFrameIO* _io, std::shared_ptr<Peer> const& _n, Pe
{
m_peer->m_lastDisconnect = NoDisconnect;
m_lastReceived = m_connect = chrono::steady_clock::now();
m_info.socketId = _io->socket().native_handle();
}
Session::~Session()

2
libp2p/Session.h

@ -65,7 +65,7 @@ public:
bool isConnected() const { return m_socket.is_open(); }
NodeId id() const;
unsigned socketId() const { return m_info.socket; }
unsigned socketId() const { return m_info.socketId; }
template <class PeerCap>
std::shared_ptr<PeerCap> cap() const { try { return std::static_pointer_cast<PeerCap>(m_capabilities.at(std::make_pair(PeerCap::name(), PeerCap::version()))); } catch (...) { return nullptr; } }

23
libweb3jsonrpc/WebThreeStubServerBase.cpp

@ -79,7 +79,7 @@ static Json::Value toJson(dev::eth::BlockInfo const& _bi)
return res;
}
static Json::Value toJson(dev::eth::Transaction const& _t)
static Json::Value toJson(dev::eth::Transaction const& _t, std::pair<h256, unsigned> _location, BlockNumber _blockNumber)
{
Json::Value res;
if (_t)
@ -92,6 +92,9 @@ static Json::Value toJson(dev::eth::Transaction const& _t)
res["gasPrice"] = toJS(_t.gasPrice());
res["nonce"] = toJS(_t.nonce());
res["value"] = toJS(_t.value());
res["blockHash"] = toJS(_location.first);
res["transactionIndex"] = toJS(_location.second);
res["blockNumber"] = toJS(_blockNumber);
}
return res;
}
@ -105,8 +108,8 @@ static Json::Value toJson(dev::eth::BlockInfo const& _bi, UncleHashes const& _us
for (h256 h: _us)
res["uncles"].append(toJS(h));
res["transactions"] = Json::Value(Json::arrayValue);
for (Transaction const& t: _ts)
res["transactions"].append(toJson(t));
for (unsigned i = 0; i < _ts.size(); i++)
res["transactions"].append(toJson(_ts[i], std::make_pair(_bi.hash(), i), (BlockNumber)_bi.number));
}
return res;
}
@ -547,7 +550,9 @@ Json::Value WebThreeStubServerBase::eth_getTransactionByHash(string const& _tran
{
try
{
return toJson(client()->transaction(jsToFixed<32>(_transactionHash)));
h256 h = jsToFixed<32>(_transactionHash);
auto l = client()->transactionLocation(h);
return toJson(client()->transaction(h), l, client()->numberFromHash(l.first));
}
catch (...)
{
@ -559,7 +564,10 @@ Json::Value WebThreeStubServerBase::eth_getTransactionByBlockHashAndIndex(string
{
try
{
return toJson(client()->transaction(jsToFixed<32>(_blockHash), jsToInt(_transactionIndex)));
h256 bh = jsToFixed<32>(_blockHash);
unsigned ti = jsToInt(_transactionIndex);
Transaction t = client()->transaction(bh, ti);
return toJson(t, make_pair(bh, ti), client()->numberFromHash(bh));
}
catch (...)
{
@ -571,7 +579,10 @@ Json::Value WebThreeStubServerBase::eth_getTransactionByBlockNumberAndIndex(stri
{
try
{
return toJson(client()->transaction(jsToBlockNumber(_blockNumber), jsToInt(_transactionIndex)));
BlockNumber bn = jsToBlockNumber(_blockNumber);
unsigned ti = jsToInt(_transactionIndex);
Transaction t = client()->transaction(bn, ti);
return toJson(t, make_pair(client()->hashFromNumber(bn), ti), bn);
}
catch (...)
{

6
mix/MixClient.cpp

@ -55,7 +55,7 @@ bytes MixBlockChain::createGenesisBlock(h256 _stateRoot)
}
MixClient::MixClient(std::string const& _dbPath):
m_dbPath(_dbPath), m_miningThreads(0)
m_dbPath(_dbPath)
{
std::map<Secret, u256> account;
account.insert(std::make_pair(c_defaultUserAccountSecret, 1000000 * ether));
@ -249,6 +249,9 @@ void MixClient::mine()
{
WriteGuard l(x_state);
m_state.commitToMine(bc());
m_state.completeMine();
bc().import(m_state.blockData(), m_stateDB, ImportRequirements::Default & ~ImportRequirements::ValidNonce);
/*
GenericFarm<ProofOfWork> f;
bool completed = false;
f.onSolutionFound([&](ProofOfWork::Solution sol)
@ -261,6 +264,7 @@ void MixClient::mine()
this_thread::sleep_for(chrono::milliseconds(20));
bc().import(m_state.blockData(), m_stateDB);
*/
m_state.sync(bc());
m_startState = m_state;
h256Set changed { dev::eth::PendingChangedFilter, dev::eth::ChainChangedFilter };

1
mix/MixClient.h

@ -101,7 +101,6 @@ private:
mutable boost::shared_mutex x_executions;
ExecutionResults m_executions;
std::string m_dbPath;
unsigned m_miningThreads;
};
}

27
test/net.cpp

@ -223,6 +223,33 @@ BOOST_AUTO_TEST_CASE(v2PingNodePacket)
BOOST_REQUIRE(p.version == 2);
}
BOOST_AUTO_TEST_CASE(neighboursPacketLength)
{
KeyPair k = KeyPair::create();
std::vector<std::pair<KeyPair,unsigned>> testNodes(TestNodeTable::createTestNodes(16));
bi::udp::endpoint to(boost::asio::ip::address::from_string("127.0.0.1"), 30000);
// hash(32), signature(65), overhead: packet(2), type(1), nodeList(2), ts(9),
static unsigned const nlimit = (1280 - 111) / 87;
for (unsigned offset = 0; offset < testNodes.size(); offset += nlimit)
{
Neighbours out(to);
auto limit = nlimit ? std::min(testNodes.size(), (size_t)(offset + nlimit)) : testNodes.size();
for (auto i = offset; i < limit; i++)
{
Neighbours::Node node;
node.ipAddress = boost::asio::ip::address::from_string("200.200.200.200").to_string();
node.port = testNodes[i].second;
node.node = testNodes[i].first.pub();
out.nodes.push_back(node);
}
out.sign(k.sec());
BOOST_REQUIRE_LE(out.data.size(), 1280);
}
}
BOOST_AUTO_TEST_CASE(test_neighbours_packet)
{
KeyPair k = KeyPair::create();

2
third/CMakeLists.txt

@ -52,5 +52,5 @@ target_link_libraries(${EXECUTABLE} web3jsonrpc)
target_link_libraries(${EXECUTABLE} jsqrc)
# eth_install_executable is defined in cmake/EthExecutableHelper.cmake
eth_install_executable(${EXECUTABLE} DLLS ${MHD_DLL_RELEASE})
eth_install_executable(${EXECUTABLE} DLLS MHD_DLLS)

Loading…
Cancel
Save