Browse Source

Merge branch 'develop' into ide_m25

Conflicts:
	libethereum/Executive.h
	mix/AssemblyDebuggerCtrl.cpp
	mix/AssemblyDebuggerModel.cpp
	mix/AssemblyDebuggerModel.h
	mix/DebuggingStateWrapper.cpp
	mix/qml.qrc
	mix/qml/main.qml
cl-refactor
yann300 10 years ago
parent
commit
566e24a794
  1. 2
      .gitignore
  2. 120
      CMakeLists.txt
  3. 0
      EthereumMacOSXBundleInfo.plist.in
  4. 2
      README.md
  5. 129
      alethzero/CMakeLists.txt
  6. 99
      alethzero/MainWin.cpp
  7. 4
      alethzero/MainWin.h
  8. 4
      alethzero/OurWebThreeStubServer.cpp
  9. 4
      alethzero/OurWebThreeStubServer.h
  10. 27
      build.py
  11. 66
      cmake/EthCompilerSettings.cmake
  12. 148
      cmake/EthDependencies.cmake
  13. 210
      cmake/EthDependenciesDeprecated.cmake
  14. 118
      cmake/EthExecutableHelper.cmake
  15. 108
      cmake/FindCryptoPP.cmake
  16. 34
      cmake/FindGmp.cmake
  17. 52
      cmake/FindJsonRpcCpp.cmake
  18. 48
      cmake/FindJsoncpp.cmake
  19. 48
      cmake/FindLevelDB.cmake
  20. 34
      cmake/FindMiniupnpc.cmake
  21. 34
      cmake/FindReadline.cmake
  22. 47
      eth/CMakeLists.txt
  23. 35
      eth/main.cpp
  24. 30
      exp/CMakeLists.txt
  25. 90
      exp/main.cpp
  26. 55
      extdep/CMakeLists.txt
  27. 16
      extdep/Readme.md
  28. 9
      extdep/cmake/FindCURL.cmake
  29. 13
      extdep/compile/argtable2.cmake
  30. 19
      extdep/compile/boost.cmake
  31. 33
      extdep/compile/cryptopp.cmake
  32. 29
      extdep/compile/curl.cmake
  33. 17
      extdep/compile/icu.cmake
  34. 16
      extdep/compile/jom.cmake
  35. 40
      extdep/compile/json-rpc-cpp.cmake
  36. 16
      extdep/compile/jsoncpp.cmake
  37. 23
      extdep/compile/leveldb.cmake
  38. 18
      extdep/compile/leveldb_osx.patch
  39. 32
      extdep/compile/qt.cmake
  40. 111
      extdep/compile/qt_configure.bat
  41. 11
      extdep/compile/qt_osx.patch
  42. 2
      extdep/compile/qt_tools.bat
  43. 14
      extdep/compile/snappy.cmake
  44. 74
      extdep/eth_download.cmake
  45. 11
      extdep/miniupnpc.cmake
  46. 29
      extdep/scripts/json-rpc-cpp_osx.sh
  47. 12
      extdep/scripts/leveldb_osx.sh
  48. 8
      extdep/scripts/snappy_osx.sh
  49. 117
      iethxi/CMakeLists.txt
  50. 38
      iethxi/EthereumMacOSXBundleInfo.plist.in
  51. 168
      iethxi/Main.ui
  52. 59
      iethxi/MainWin.cpp
  53. 18
      iethxi/MainWin.h
  54. 5
      iethxi/Resources.qrc
  55. 9
      iethxi/Simple.qml
  56. 9
      iethxi/main.cpp
  57. 8
      libdevcore/All.h
  58. 41
      libdevcore/CMakeLists.txt
  59. 21
      libdevcore/CommonData.cpp
  60. 2
      libdevcore/CommonData.h
  61. 7
      libdevcore/CommonJS.cpp
  62. 2
      libdevcore/CommonJS.h
  63. 8
      libdevcore/RLP.h
  64. 2
      libdevcore/RangeMask.h
  65. 13
      libdevcore/_libdevcore.cpp
  66. 1
      libdevcore/vector_ref.h
  67. 8
      libdevcrypto/All.h
  68. 51
      libdevcrypto/CMakeLists.txt
  69. 5
      libdevcrypto/Common.h
  70. 6
      libdevcrypto/CryptoPP.cpp
  71. 26
      libdevcrypto/CryptoPP.h
  72. 2
      libdevcrypto/OverlayDB.cpp
  73. 2
      libdevcrypto/OverlayDB.h
  74. 2
      libdevcrypto/SHA3.cpp
  75. 2
      libdevcrypto/SHA3.h
  76. 4
      libdevcrypto/TrieDB.cpp
  77. 7
      libethcore/All.h
  78. 37
      libethcore/BlockInfo.cpp
  79. 18
      libethcore/BlockInfo.h
  80. 47
      libethcore/CMakeLists.txt
  81. 3
      libethcore/CommonEth.cpp
  82. 3
      libethcore/CommonEth.h
  83. 3
      libethcore/ProofOfWork.cpp
  84. 7
      libethcore/_libethcore.cpp
  85. 5
      libethereum/BlockChain.cpp
  86. 3
      libethereum/BlockDetails.cpp
  87. 4
      libethereum/BlockDetails.h
  88. 55
      libethereum/CMakeLists.txt
  89. 101
      libethereum/CachedAddressState.cpp
  90. 60
      libethereum/CachedAddressState.h
  91. 2
      libethereum/Client.cpp
  92. 5
      libethereum/Client.h
  93. 2
      libethereum/CommonNet.cpp
  94. 2
      libethereum/CommonNet.h
  95. 171
      libethereum/Executive.cpp
  96. 99
      libethereum/Executive.h
  97. 36
      libethereum/ExtVM.cpp
  98. 32
      libethereum/ExtVM.h
  99. 7
      libethereum/Interface.h
  100. 81
      libethereum/LogFilter.cpp

2
.gitignore

@ -29,7 +29,9 @@ build_xc
*.user.* *.user.*
*~ *~
# build system
build.*/ build.*/
extdep/install
*.pyc *.pyc

120
CMakeLists.txt

@ -1,5 +1,8 @@
# cmake global # cmake global
cmake_minimum_required(VERSION 2.8.9) cmake_minimum_required(VERSION 2.8.12)
# let cmake autolink dependencies on windows
# it's specified globally, cause qt libraries requires that on windows and they are also found globally
cmake_policy(SET CMP0020 NEW)
project(ethereum) project(ethereum)
@ -12,18 +15,14 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
# Normally, set(...CACHE...) creates cache variables, but does not modify them. # Normally, set(...CACHE...) creates cache variables, but does not modify them.
function(createDefaultCacheConfig) function(createDefaultCacheConfig)
set(HEADLESS OFF CACHE BOOL "Do not compile GUI (AlethZero)") set(HEADLESS OFF CACHE BOOL "Do not compile GUI (AlethZero)")
set(LANGUAGES OFF CACHE BOOL "Limit build to Serpent/LLL tools")
set(VMTRACE OFF CACHE BOOL "VM tracing and run-time checks (useful for cross-implementation VM debugging)") set(VMTRACE OFF CACHE BOOL "VM tracing and run-time checks (useful for cross-implementation VM debugging)")
set(PARANOIA OFF CACHE BOOL "Additional run-time checks") set(PARANOIA OFF CACHE BOOL "Additional run-time checks")
set(JSONRPC ON CACHE BOOL "Build with jsonprc. default on")
endfunction() endfunction()
# propagates CMake configuration options to the compiler # propagates CMake configuration options to the compiler
function(configureProject) function(configureProject)
if (LANGUAGES)
add_definitions(-DETH_LANGUAGES)
endif ()
if (PARANOIA) if (PARANOIA)
if ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") if ("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
add_definitions(-DETH_PARANOIA) add_definitions(-DETH_PARANOIA)
@ -42,6 +41,7 @@ function(configureProject)
endfunction() endfunction()
function(createBuildInfo) function(createBuildInfo)
# Set build platform; to be written to BuildInfo.h # Set build platform; to be written to BuildInfo.h
if (CMAKE_COMPILER_IS_MINGW) if (CMAKE_COMPILER_IS_MINGW)
@ -50,7 +50,7 @@ function(createBuildInfo)
set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/msys") set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/msys")
elseif (CMAKE_COMPILER_IS_GNUCXX) elseif (CMAKE_COMPILER_IS_GNUCXX)
set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/g++") set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/g++")
elseif (CMAKE_COMPILER_IS_MSVC) elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/msvc") set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/msvc")
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/clang") set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/clang")
@ -58,14 +58,23 @@ function(createBuildInfo)
set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/unknown") set(ETH_BUILD_PLATFORM "${ETH_BUILD_PLATFORM}/unknown")
endif () endif ()
#cmake build type may be not specified when using msvc
if (${CMAKE_BUILD_TYPE})
set(_cmake_build_type ${CMAKE_BUILD_TYPE})
else()
set(_cmake_build_type "undefined")
endif()
# Generate header file containing useful build information # Generate header file containing useful build information
add_custom_target(BuildInfo.h ALL COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/BuildInfo.sh ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_BUILD_TYPE} ${ETH_BUILD_PLATFORM}) add_custom_target(BuildInfo.h ALL COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/BuildInfo.sh ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${_cmake_build_type} ${ETH_BUILD_PLATFORM})
include_directories(${CMAKE_CURRENT_BINARY_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR})
set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(SRC_LIST BuildInfo.h) set(SRC_LIST BuildInfo.h)
endfunction() endfunction()
###################################################################################################### ######################################################################################################
@ -75,7 +84,7 @@ cmake_policy(SET CMP0015 NEW)
createDefaultCacheConfig() createDefaultCacheConfig()
configureProject() configureProject()
message("-- LANGUAGES: ${LANGUAGES}; VMTRACE: ${VMTRACE}; PARANOIA: ${PARANOIA}; HEADLESS: ${HEADLESS}") message("-- VMTRACE: ${VMTRACE}; PARANOIA: ${PARANOIA}; HEADLESS: ${HEADLESS}; JSONRPC: ${JSONRPC}")
# Default TARGET_PLATFORM to "linux". # Default TARGET_PLATFORM to "linux".
@ -88,20 +97,13 @@ if ("${TARGET_PLATFORM}" STREQUAL "linux")
set(CMAKE_THREAD_LIBS_INIT pthread) set(CMAKE_THREAD_LIBS_INIT pthread)
endif () endif ()
# Set default build type to Release w/debug info
# if(NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE)
# set(CMAKE_BUILD_TYPE RelWithDebInfo)
# endif()
include(EthCompilerSettings) include(EthCompilerSettings)
message("-- CXXFLAGS: ${CMAKE_CXX_FLAGS}") message("-- CXXFLAGS: ${CMAKE_CXX_FLAGS}")
#add_definitions("-DETH_BUILD_TYPE=${ETH_BUILD_TYPE}")
#add_definitions("-DETH_BUILD_PLATFORM=${ETH_BUILD_PLATFORM}")
include(EthDependenciesDeprecated) # this must be an include, as a function it would messs up with variable scope!
include(EthDependencies)
include(EthExecutableHelper)
createBuildInfo() createBuildInfo()
@ -110,62 +112,44 @@ add_subdirectory(libevmcore)
add_subdirectory(liblll) add_subdirectory(liblll)
add_subdirectory(libserpent) add_subdirectory(libserpent)
add_subdirectory(libsolidity) add_subdirectory(libsolidity)
if(NOT APPLE)
if(PYTHON_LS)
add_subdirectory(libpyserpent)
endif()
endif()
add_subdirectory(lllc) add_subdirectory(lllc)
add_subdirectory(solc) add_subdirectory(solc)
add_subdirectory(sc) add_subdirectory(sc)
if (JSONRPC_LS)
if (JSONRPC)
add_subdirectory(libweb3jsonrpc) add_subdirectory(libweb3jsonrpc)
endif() endif()
if (NOT LANGUAGES)
add_subdirectory(secp256k1)
add_subdirectory(libp2p)
add_subdirectory(libdevcrypto)
add_subdirectory(libwhisper)
add_subdirectory(libethcore)
add_subdirectory(libevm)
add_subdirectory(libethereum)
# add_subdirectory(libethereumx) # TODO remove
add_subdirectory(libwebthree)
add_subdirectory(test)
add_subdirectory(eth)
if("x${CMAKE_BUILD_TYPE}" STREQUAL "xDebug")
add_subdirectory(exp)
endif ()
if(NOT ("${TARGET_PLATFORM}" STREQUAL "w64"))
add_subdirectory(neth)
endif ()
if(QTQML)
add_definitions(-DETH_QTQML)
endif()
if(NOT HEADLESS) add_subdirectory(secp256k1)
if ("${TARGET_PLATFORM}" STREQUAL "w64") add_subdirectory(libp2p)
cmake_policy(SET CMP0020 NEW) add_subdirectory(libdevcrypto)
endif () add_subdirectory(libwhisper)
if (NOT JSONRPC_LS)
message(FATAL_ERROR "Alethzero requires jsonrpc.")
endif()
add_subdirectory(libjsqrc)
add_subdirectory(libqethereum)
add_subdirectory(alethzero)
add_subdirectory(third)
add_subdirectory(mix)
if(QTQML)
#add_subdirectory(iethxi)
#add_subdirectory(walleth) // resurect once we want to submit ourselves to QML.
endif()
endif()
endif()
add_subdirectory(libethcore)
add_subdirectory(libevm)
add_subdirectory(libethereum)
add_subdirectory(libwebthree)
add_subdirectory(test)
add_subdirectory(eth)
if("x${CMAKE_BUILD_TYPE}" STREQUAL "xDebug")
add_subdirectory(exp)
endif ()
# TODO check msvc
if(NOT ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC"))
add_subdirectory(neth)
endif ()
if (NOT HEADLESS)
add_subdirectory(libjsqrc)
add_subdirectory(libqethereum)
add_subdirectory(alethzero)
add_subdirectory(third)
add_subdirectory(mix)
endif()
enable_testing() enable_testing()
add_test(NAME alltests WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/test COMMAND testeth) add_test(NAME alltests WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/test COMMAND testeth)

0
alethzero/EthereumMacOSXBundleInfo.plist.in → EthereumMacOSXBundleInfo.plist.in

2
README.md

@ -36,5 +36,5 @@ Please read [CodingStandards.txt](CodingStandards.txt) thoroughly before making
libweb3jsonrpc/abstractwebthreestubserver.h is autogenerated from the jsonrpcstub executable that comes with the libjsonrpc library (json-rpc-cpp project). It shouldn't be maually altered. libweb3jsonrpc/abstractwebthreestubserver.h is autogenerated from the jsonrpcstub executable that comes with the libjsonrpc library (json-rpc-cpp project). It shouldn't be maually altered.
```bash ```bash
jsonrpcstub -s -c spec.json WebThreeStub jsonrpcstub spec.json --cpp-server=AbstractWebThreeStubServer
``` ```

129
alethzero/CMakeLists.txt

@ -1,101 +1,52 @@
cmake_policy(SET CMP0015 NEW)
# let cmake autolink dependencies on windows
cmake_policy(SET CMP0020 NEW)
# this policy was introduced in cmake 3.0
# remove if, once 3.0 will be used on unix
if (${CMAKE_MAJOR_VERSION} GREATER 2)
cmake_policy(SET CMP0043 OLD)
endif()
set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_INCLUDE_CURRENT_DIR ON)
aux_source_directory(. SRC_LIST) aux_source_directory(. SRC_LIST)
include_directories(..)
if (APPLE) include_directories(${JSON_RPC_CPP_INCLUDE_DIRS})
# Add homebrew path for qt5 include_directories(..)
set(CMAKE_PREFIX_PATH /usr/local/opt/qt5)
include_directories(/usr/local/opt/qt5/include /usr/local/include)
elseif ("${TARGET_PLATFORM}" STREQUAL "w64")
set(SRC_LIST ${SRC_LIST} ../windows/qt_plugin_import.cpp)
include_directories(/usr/x86_64-w64-mingw32/include /usr/x86_64-w64-mingw32/include/QtCore /usr/x86_64-w64-mingw32/include/QtGui /usr/x86_64-w64-mingw32/include/QtQuick /usr/x86_64-w64-mingw32/include/QtQml /usr/x86_64-w64-mingw32/include/QtNetwork /usr/x86_64-w64-mingw32/include/QtWidgets /usr/x86_64-w64-mingw32/include/QtWebKit /usr/x86_64-w64-mingw32/include/QtWebKitWidgets)
elseif (UNIX)
set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ";$ENV{QTDIR}/lib/cmake")
endif ()
find_package(Qt5Core REQUIRED)
find_package(Qt5Gui REQUIRED)
find_package(Qt5Quick REQUIRED)
find_package(Qt5Qml REQUIRED)
find_package(Qt5Network REQUIRED)
find_package(Qt5Widgets REQUIRED)
find_package(Qt5WebKit REQUIRED)
find_package(Qt5WebKitWidgets REQUIRED)
qt5_wrap_ui(ui_Main.h Main.ui) qt5_wrap_ui(ui_Main.h Main.ui)
# Set name of binary and add_executable()
file(GLOB HEADERS "*.h") file(GLOB HEADERS "*.h")
if (APPLE)
set(EXECUTEABLE AlethZero)
set(BIN_INSTALL_DIR ".")
set(DOC_INSTALL_DIR ".")
set(PROJECT_VERSION "${ETH_VERSION}")
set(MACOSX_BUNDLE_INFO_STRING "${PROJECT_NAME} ${PROJECT_VERSION}")
set(MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_NAME} ${PROJECT_VERSION}")
set(MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_NAME} ${PROJECT_VERSION}")
set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}")
set(MACOSX_BUNDLE_COPYRIGHT "${PROJECT_COPYRIGHT_YEAR} ${PROJECT_VENDOR}")
set(MACOSX_BUNDLE_GUI_IDENTIFIER "${PROJECT_DOMAIN_SECOND}.${PROJECT_DOMAIN_FIRST}")
set(MACOSX_BUNDLE_BUNDLE_NAME ${EXECUTEABLE})
set(MACOSX_BUNDLE_ICON_FILE alethzero)
include(BundleUtilities)
add_executable(${EXECUTEABLE} MACOSX_BUNDLE alethzero.icns Main.ui ${SRC_LIST} ${HEADERS})
set_target_properties(${EXECUTEABLE} PROPERTIES MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/EthereumMacOSXBundleInfo.plist.in")
SET_SOURCE_FILES_PROPERTIES(${EXECUTEABLE} PROPERTIES MACOSX_PACKAGE_LOCATION MacOS)
SET_SOURCE_FILES_PROPERTIES(${MACOSX_BUNDLE_ICON_FILE}.icns PROPERTIES MACOSX_PACKAGE_LOCATION "Resources")
else ()
set(EXECUTEABLE alethzero)
add_executable(${EXECUTEABLE} Main.ui ${SRC_LIST} ${HEADERS})
endif ()
qt5_use_modules(${EXECUTEABLE} Core)# Gui Widgets Network WebKit WebKitWidgets)
target_link_libraries(${EXECUTEABLE} webthree qethereum ethereum evm ethcore devcrypto secp256k1 gmp ${CRYPTOPP_LS} serpent lll solidity evmcore devcore web3jsonrpc jsqrc)
if (APPLE) if (APPLE)
# First have qt5 install plugins and frameworks set(EXECUTABLE AlethZero)
add_custom_command(TARGET ${EXECUTEABLE} POST_BUILD
COMMAND /usr/local/opt/qt5/bin/macdeployqt ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${EXECUTEABLE}.app
WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY})
# This tool and next will inspect linked libraries in order to determine which dependencies are required
if (${CMAKE_CFG_INTDIR} STREQUAL ".")
set(APP_BUNDLE_PATH "${CMAKE_CURRENT_BINARY_DIR}/${EXECUTEABLE}.app")
else ()
set(APP_BUNDLE_PATH "${CMAKE_CURRENT_BINARY_DIR}/\$ENV{CONFIGURATION}/${EXECUTEABLE}.app")
endif ()
install(CODE "
include(BundleUtilities)
set(BU_CHMOD_BUNDLE_ITEMS 1)
fixup_bundle(\"${APP_BUNDLE_PATH}\" \"${BUNDLELIBS}\" \"../libqethereum ../libethereum ../secp256k1\")
" COMPONENT RUNTIME )
# Cleanup duplicate libs from macdeployqt
install(CODE "
file(GLOB LINGER_RM \"${APP_BUNDLE_PATH}/Contents/Frameworks/*.dylib\")
if (LINGER_RM)
file(REMOVE \${LINGER_RM})
endif ()
")
elseif ("${TARGET_PLATFORM}" STREQUAL "w64")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-keep-inline-dllexport -static-libgcc -static-libstdc++ -static")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-s -Wl,-subsystem,windows -mthreads -L/usr/x86_64-w64-mingw32/plugins/platforms")
target_link_libraries(${EXECUTEABLE} gcc)
target_link_libraries(${EXECUTEABLE} mingw32 qtmain mswsock iphlpapi qwindows shlwapi Qt5PlatformSupport opengl32 gdi32 comdlg32 oleaut32 imm32 winmm ole32 uuid ws2_32)
target_link_libraries(${EXECUTEABLE} boost_system-mt-s)
target_link_libraries(${EXECUTEABLE} boost_filesystem-mt-s)
target_link_libraries(${EXECUTEABLE} boost_thread_win32-mt-s)
target_link_libraries(${EXECUTEABLE} crypt32)
target_link_libraries(${EXECUTEABLE} Qt5PlatformSupport)
set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS)
elseif (UNIX)
else () else ()
target_link_libraries(${EXECUTEABLE} boost_system) set(EXECUTABLE alethzero)
target_link_libraries(${EXECUTEABLE} boost_filesystem)
find_package(Threads REQUIRED)
target_link_libraries(${EXECUTEABLE} ${CMAKE_THREAD_LIBS_INIT})
install( TARGETS ${EXECUTEABLE} RUNTIME DESTINATION bin )
endif () endif ()
# eth_add_executable is defined in cmake/EthExecutableHelper.cmake
eth_add_executable(${EXECUTABLE}
ICON alethzero
UI_RESOURCES alethzero.icns Main.ui
)
add_dependencies(${EXECUTABLE} BuildInfo.h)
target_link_libraries(${EXECUTABLE} Qt5::Core)
target_link_libraries(${EXECUTABLE} webthree)
target_link_libraries(${EXECUTABLE} qethereum)
target_link_libraries(${EXECUTABLE} ethereum)
target_link_libraries(${EXECUTABLE} evm)
target_link_libraries(${EXECUTABLE} ethcore)
target_link_libraries(${EXECUTABLE} devcrypto)
target_link_libraries(${EXECUTABLE} secp256k1)
target_link_libraries(${EXECUTABLE} serpent)
target_link_libraries(${EXECUTABLE} lll)
target_link_libraries(${EXECUTABLE} solidity)
target_link_libraries(${EXECUTABLE} evmcore)
target_link_libraries(${EXECUTABLE} devcore)
target_link_libraries(${EXECUTABLE} web3jsonrpc)
target_link_libraries(${EXECUTABLE} jsqrc)
# eth_install_executable is defined in cmake/EthExecutableHelper.cmake
eth_install_executable(${EXECUTABLE})

99
alethzero/MainWin.cpp

@ -43,6 +43,7 @@
#include <libethereum/BlockChain.h> #include <libethereum/BlockChain.h>
#include <libethereum/ExtVM.h> #include <libethereum/ExtVM.h>
#include <libethereum/Client.h> #include <libethereum/Client.h>
#include <libethereum/Utility.h>
#include <libethereum/EthereumHost.h> #include <libethereum/EthereumHost.h>
#include <libethereum/DownloadMan.h> #include <libethereum/DownloadMan.h>
#include <libweb3jsonrpc/WebThreeStubServer.h> #include <libweb3jsonrpc/WebThreeStubServer.h>
@ -153,9 +154,8 @@ Main::Main(QWidget *parent) :
m_webThree.reset(new WebThreeDirect(string("AlethZero/v") + dev::Version + "/" DEV_QUOTED(ETH_BUILD_TYPE) "/" DEV_QUOTED(ETH_BUILD_PLATFORM), getDataDir() + "/AlethZero", false, {"eth", "shh"})); m_webThree.reset(new WebThreeDirect(string("AlethZero/v") + dev::Version + "/" DEV_QUOTED(ETH_BUILD_TYPE) "/" DEV_QUOTED(ETH_BUILD_PLATFORM), getDataDir() + "/AlethZero", false, {"eth", "shh"}));
// w3stubserver, on dealloc, deletes m_qwebConnector m_qwebConnector.reset(new QWebThreeConnector());
m_qwebConnector = new QWebThreeConnector(); // owned by WebThreeStubServer m_server.reset(new OurWebThreeStubServer(*m_qwebConnector, *web3(), keysAsVector(m_myKeys)));
m_server.reset(new OurWebThreeStubServer(m_qwebConnector, *web3(), keysAsVector(m_myKeys)));
connect(&*m_server, SIGNAL(onNewId(QString)), SLOT(addNewId(QString))); connect(&*m_server, SIGNAL(onNewId(QString)), SLOT(addNewId(QString)));
m_server->setIdentities(keysAsVector(owned())); m_server->setIdentities(keysAsVector(owned()));
m_server->StartListening(); m_server->StartListening();
@ -1261,9 +1261,12 @@ void Main::on_blocks_currentItemChanged()
s << "<br/>Gas used/limit: <b>" << info.gasUsed << "</b>/<b>" << info.gasLimit << "</b>"; s << "<br/>Gas used/limit: <b>" << info.gasUsed << "</b>/<b>" << info.gasLimit << "</b>";
s << "<br/>Coinbase: <b>" << pretty(info.coinbaseAddress).toHtmlEscaped().toStdString() << "</b> " << info.coinbaseAddress; s << "<br/>Coinbase: <b>" << pretty(info.coinbaseAddress).toHtmlEscaped().toStdString() << "</b> " << info.coinbaseAddress;
s << "<br/>Nonce: <b>" << info.nonce << "</b>"; s << "<br/>Nonce: <b>" << info.nonce << "</b>";
s << "<br/>Hash w/o nonce: <b>" << info.headerHashWithoutNonce() << "</b>"; s << "<br/>Hash w/o nonce: <b>" << info.headerHash(WithoutNonce) << "</b>";
s << "<br/>Difficulty: <b>" << info.difficulty << "</b>"; s << "<br/>Difficulty: <b>" << info.difficulty << "</b>";
s << "<br/>Proof-of-Work: <b>" << ProofOfWork::eval(info.headerHashWithoutNonce(), info.nonce) << " &lt;= " << (h256)u256((bigint(1) << 256) / info.difficulty) << "</b>"; if (info.number)
s << "<br/>Proof-of-Work: <b>" << ProofOfWork::eval(info.headerHash(WithoutNonce), info.nonce) << " &lt;= " << (h256)u256((bigint(1) << 256) / info.difficulty) << "</b>";
else
s << "<br/>Proof-of-Work: <i>Phil has nothing to prove</i>";
s << "<br/>Parent: <b>" << info.parentHash << "</b>"; s << "<br/>Parent: <b>" << info.parentHash << "</b>";
// s << "<br/>Bloom: <b>" << details.bloom << "</b>"; // s << "<br/>Bloom: <b>" << details.bloom << "</b>";
s << "<br/>Log Bloom: <b>" << info.logBloom << "</b>"; s << "<br/>Log Bloom: <b>" << info.logBloom << "</b>";
@ -1280,11 +1283,12 @@ void Main::on_blocks_currentItemChanged()
if (info.parentHash) if (info.parentHash)
s << "<br/>Pre: <b>" << BlockInfo(ethereum()->blockChain().block(info.parentHash)).stateRoot << "</b>"; s << "<br/>Pre: <b>" << BlockInfo(ethereum()->blockChain().block(info.parentHash)).stateRoot << "</b>";
else else
s << "<br/>Pre: <i>Nothing is before the Gensesis</i>"; s << "<br/>Pre: <i>Nothing is before Phil</i>";
for (auto const& i: block[1]) for (auto const& i: block[1])
s << "<br/>" << sha3(i.data()).abridged();// << ": <b>" << i[1].toHash<h256>() << "</b> [<b>" << i[2].toInt<u256>() << "</b> used]"; s << "<br/>" << sha3(i.data()).abridged();// << ": <b>" << i[1].toHash<h256>() << "</b> [<b>" << i[2].toInt<u256>() << "</b> used]";
s << "<br/>Post: <b>" << info.stateRoot << "</b>"; s << "<br/>Post: <b>" << info.stateRoot << "</b>";
s << "<br/>Dump: <span style=\"font-family: Monospace,Lucida Console,Courier,Courier New,sans-serif; font-size: small\">" << toHex(block[0].data()) << "</span>"; s << "<br/>Dump: <span style=\"font-family: Monospace,Lucida Console,Courier,Courier New,sans-serif; font-size: small\">" << toHex(block[0].data()) << "</span>";
s << "<div>Receipts-Hex: <span style=\"font-family: Monospace,Lucida Console,Courier,Courier New,sans-serif; font-size: small\">" << toHex(ethereum()->blockChain().receipts(h).rlp()) << "</span></div>";
} }
else else
{ {
@ -1346,7 +1350,7 @@ void Main::on_debugCurrent_triggered()
{ {
unsigned txi = item->data(Qt::UserRole + 1).toInt(); unsigned txi = item->data(Qt::UserRole + 1).toInt();
m_executiveState = ethereum()->state(txi + 1, h); m_executiveState = ethereum()->state(txi + 1, h);
m_currentExecution = unique_ptr<Executive>(new Executive(m_executiveState)); m_currentExecution = unique_ptr<Executive>(new Executive(m_executiveState, 0));
Transaction t = m_executiveState.pending()[txi]; Transaction t = m_executiveState.pending()[txi];
m_executiveState = m_executiveState.fromPending(txi); m_executiveState = m_executiveState.fromPending(txi);
auto r = t.rlp(); auto r = t.rlp();
@ -1394,10 +1398,10 @@ void Main::populateDebugger(dev::bytesConstRef _r)
bytesConstRef lastData; bytesConstRef lastData;
h256 lastHash; h256 lastHash;
h256 lastDataHash; h256 lastDataHash;
auto onOp = [&](uint64_t steps, Instruction inst, dev::bigint newMemSize, dev::bigint gasCost, void* voidVM, void const* voidExt) auto onOp = [&](uint64_t steps, Instruction inst, dev::bigint newMemSize, dev::bigint gasCost, dev::eth::VM* voidVM, dev::eth::ExtVMFace const* voidExt)
{ {
dev::eth::VM& vm = *(dev::eth::VM*)voidVM; dev::eth::VM& vm = *voidVM;
dev::eth::ExtVM const& ext = *(dev::eth::ExtVM const*)voidExt; dev::eth::ExtVM const& ext = *static_cast<dev::eth::ExtVM const*>(voidExt);
if (ext.code != lastExtCode) if (ext.code != lastExtCode)
{ {
lastExtCode = ext.code; lastExtCode = ext.code;
@ -1496,58 +1500,6 @@ void Main::on_destination_currentTextChanged()
// updateFee(); // updateFee();
} }
static bytes dataFromText(QString _s)
{
bytes ret;
while (_s.size())
{
QRegExp r("(@|\\$)?\"([^\"]*)\"(\\s.*)?");
QRegExp d("(@|\\$)?([0-9]+)(\\s*(ether)|(finney)|(szabo))?(\\s.*)?");
QRegExp h("(@|\\$)?(0x)?(([a-fA-F0-9])+)(\\s.*)?");
if (r.exactMatch(_s))
{
for (auto i: r.cap(2))
ret.push_back((byte)i.toLatin1());
if (r.cap(1) != "$")
for (int i = r.cap(2).size(); i < 32; ++i)
ret.push_back(0);
else
ret.push_back(0);
_s = r.cap(3);
}
else if (d.exactMatch(_s))
{
u256 v(d.cap(2).toStdString());
if (d.cap(6) == "szabo")
v *= dev::eth::szabo;
else if (d.cap(5) == "finney")
v *= dev::eth::finney;
else if (d.cap(4) == "ether")
v *= dev::eth::ether;
bytes bs = dev::toCompactBigEndian(v);
if (d.cap(1) != "$")
for (auto i = bs.size(); i < 32; ++i)
ret.push_back(0);
for (auto b: bs)
ret.push_back(b);
_s = d.cap(7);
}
else if (h.exactMatch(_s))
{
bytes bs = fromHex((((h.cap(3).size() & 1) ? "0" : "") + h.cap(3)).toStdString());
if (h.cap(1) != "$")
for (auto i = bs.size(); i < 32; ++i)
ret.push_back(0);
for (auto b: bs)
ret.push_back(b);
_s = h.cap(5);
}
else
_s = _s.mid(1);
}
return ret;
}
static shh::Topic topicFromText(QString _s) static shh::Topic topicFromText(QString _s)
{ {
shh::BuildTopic ret; shh::BuildTopic ret;
@ -1625,7 +1577,7 @@ void Main::on_data_textChanged()
catch (dev::Exception const& exception) catch (dev::Exception const& exception)
{ {
ostringstream error; ostringstream error;
solidity::SourceReferenceFormatter::printExceptionInformation(error, exception, "Error", compiler.getScanner()); solidity::SourceReferenceFormatter::printExceptionInformation(error, exception, "Error", compiler);
solidity = "<h4>Solidity</h4><pre>" + QString::fromStdString(error.str()).toHtmlEscaped() + "</pre>"; solidity = "<h4>Solidity</h4><pre>" + QString::fromStdString(error.str()).toHtmlEscaped() + "</pre>";
} }
catch (...) catch (...)
@ -1675,7 +1627,7 @@ void Main::on_data_textChanged()
} }
else else
{ {
m_data = dataFromText(ui->data->toPlainText()); m_data = parseData(ui->data->toPlainText().toStdString());
ui->code->setHtml(QString::fromStdString(dev::memDump(m_data, 8, true))); ui->code->setHtml(QString::fromStdString(dev::memDump(m_data, 8, true)));
if (ethereum()->codeAt(fromString(ui->destination->currentText()), 0).size()) if (ethereum()->codeAt(fromString(ui->destination->currentText()), 0).size())
{ {
@ -1851,7 +1803,7 @@ void Main::on_debug_clicked()
{ {
Secret s = i.secret(); Secret s = i.secret();
m_executiveState = ethereum()->postState(); m_executiveState = ethereum()->postState();
m_currentExecution = unique_ptr<Executive>(new Executive(m_executiveState)); m_currentExecution = unique_ptr<Executive>(new Executive(m_executiveState, 0));
Transaction t = isCreation() ? Transaction t = isCreation() ?
Transaction(value(), gasPrice(), ui->gas->value(), m_data, m_executiveState.transactionsFrom(dev::toAddress(s)), s) : Transaction(value(), gasPrice(), ui->gas->value(), m_data, m_executiveState.transactionsFrom(dev::toAddress(s)), s) :
Transaction(value(), gasPrice(), ui->gas->value(), fromString(ui->destination->currentText()), m_data, m_executiveState.transactionsFrom(dev::toAddress(s)), s); Transaction(value(), gasPrice(), ui->gas->value(), fromString(ui->destination->currentText()), m_data, m_executiveState.transactionsFrom(dev::toAddress(s)), s);
@ -2203,7 +2155,7 @@ void Main::on_post_clicked()
{ {
shh::Message m; shh::Message m;
m.setTo(stringToPublic(ui->shhTo->currentText())); m.setTo(stringToPublic(ui->shhTo->currentText()));
m.setPayload(dataFromText(ui->shhData->toPlainText())); m.setPayload(parseData(ui->shhData->toPlainText().toStdString()));
Public f = stringToPublic(ui->shhFrom->currentText()); Public f = stringToPublic(ui->shhFrom->currentText());
Secret from; Secret from;
if (m_server->ids().count(f)) if (m_server->ids().count(f))
@ -2239,18 +2191,3 @@ void Main::refreshWhispers()
ui->whispers->addItem(item); ui->whispers->addItem(item);
} }
} }
// extra bits needed to link on VS
#ifdef _MSC_VER
// include moc file, ofuscated to hide from automoc
#include\
"moc_MainWin.cpp"
#include\
"moc_MiningView.cpp"
#include\
"moc_DownloadView.cpp"
#endif

4
alethzero/MainWin.h

@ -33,6 +33,7 @@
#include <libdevcore/RLP.h> #include <libdevcore/RLP.h>
#include <libethcore/CommonEth.h> #include <libethcore/CommonEth.h>
#include <libethereum/State.h> #include <libethereum/State.h>
#include <libethereum/Executive.h>
#include <libqethereum/QEthereum.h> #include <libqethereum/QEthereum.h>
#include <libwebthree/WebThree.h> #include <libwebthree/WebThree.h>
@ -43,7 +44,6 @@ class Main;
namespace dev { namespace eth { namespace dev { namespace eth {
class Client; class Client;
class State; class State;
class MessageFilter;
}} }}
class QQuickView; class QQuickView;
@ -256,7 +256,7 @@ private:
QString m_logHistory; QString m_logHistory;
bool m_logChanged = true; bool m_logChanged = true;
QWebThreeConnector* m_qwebConnector; std::unique_ptr<QWebThreeConnector> m_qwebConnector;
std::unique_ptr<OurWebThreeStubServer> m_server; std::unique_ptr<OurWebThreeStubServer> m_server;
QWebThree* m_qweb = nullptr; QWebThree* m_qweb = nullptr;

4
alethzero/OurWebThreeStubServer.cpp

@ -14,7 +14,7 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file OurWebThreeStubServer.h /** @file OurWebThreeStubServer.cpp
* @author Gav Wood <i@gavwood.com> * @author Gav Wood <i@gavwood.com>
* @date 2014 * @date 2014
*/ */
@ -24,7 +24,7 @@ using namespace std;
using namespace dev; using namespace dev;
using namespace dev::eth; using namespace dev::eth;
OurWebThreeStubServer::OurWebThreeStubServer(jsonrpc::AbstractServerConnector* _conn, dev::WebThreeDirect& _web3, std::vector<dev::KeyPair> const& _accounts): OurWebThreeStubServer::OurWebThreeStubServer(jsonrpc::AbstractServerConnector& _conn, dev::WebThreeDirect& _web3, std::vector<dev::KeyPair> const& _accounts):
WebThreeStubServer(_conn, _web3, _accounts) WebThreeStubServer(_conn, _web3, _accounts)
{} {}

4
alethzero/OurWebThreeStubServer.h

@ -14,7 +14,7 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file OurWebThreeStubServer.cpp /** @file OurWebThreeStubServer.h
* @author Gav Wood <i@gavwood.com> * @author Gav Wood <i@gavwood.com>
* @date 2014 * @date 2014
*/ */
@ -29,7 +29,7 @@ class OurWebThreeStubServer: public QObject, public WebThreeStubServer
Q_OBJECT Q_OBJECT
public: public:
OurWebThreeStubServer(jsonrpc::AbstractServerConnector* _conn, dev::WebThreeDirect& _web3, std::vector<dev::KeyPair> const& _accounts); OurWebThreeStubServer(jsonrpc::AbstractServerConnector& _conn, dev::WebThreeDirect& _web3, std::vector<dev::KeyPair> const& _accounts);
virtual std::string shh_newIdentity() override; virtual std::string shh_newIdentity() override;

27
build.py

@ -0,0 +1,27 @@
#!/usr/bin/python
# cpp-ethereum build script
# to be used from CI server, or to build locally
# uses python instead of bash script for better cross-platform support
# TODO Initial version. Needs much more improvements
import argparse
import os
import subprocess
def build_dependencies():
if os.path.exists("extdep"):
os.chdir("extdep")
if not os.path.exists("build"):
os.makedirs("build")
os.chdir("build")
subprocess.check_call(["cmake", ".."])
subprocess.check_call("make")
parser = argparse.ArgumentParser()
parser.add_argument("cmd", help="what to build")
args = parser.parse_args()
if args.cmd == "dep":
build_dependencies()

66
cmake/EthCompilerSettings.cmake

@ -1,59 +1,39 @@
# Set necessary compile and link flags # Set necessary compile and link flags
# C++11 check and activation # C++11 check and activation
if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU")
set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -DSHAREDLIB -fPIC")
set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DETH_DEBUG")
set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG -DETH_RELEASE")
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG -DETH_RELEASE")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g -DETH_DEBUG")
set(ETH_SHARED 1)
execute_process( execute_process(
COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION) COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION)
if (NOT (GCC_VERSION VERSION_GREATER 4.7 OR GCC_VERSION VERSION_EQUAL 4.7)) 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.") message(FATAL_ERROR "${PROJECT_NAME} requires g++ 4.7 or greater.")
endif () 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 ()
# Initialize CXXFLAGS
set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -DSHAREDLIB")
set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DETH_DEBUG")
set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG -DETH_RELEASE")
set(CMAKE_CXX_FLAGS_RELEASE "-O4 -DNDEBUG -DETH_RELEASE")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g -DETH_DEBUG")
# Windows elseif ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
if ("${TARGET_PLATFORM}" STREQUAL "w64")
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_CXX_LIBRARY_ARCHITECTURE x86_64-w64-mingw32)
set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc)
set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-g++)
set(CMAKE_RC_COMPILER x86_64-w64-mingw32-windres)
set(CMAKE_AR x86_64-w64-mingw32-ar)
set(CMAKE_RANLIB x86_64-w64-mingw32-ranlib)
set(CMAKE_EXECUTABLE_SUFFIX .exe)
set(CMAKE_FIND_ROOT_PATH
/usr/x86_64-w64-mingw32
)
include_directories(/usr/x86_64-w64-mingw32/include/cryptopp) set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -DSHAREDLIB -fPIC")
set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DETH_DEBUG")
set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG -DETH_RELEASE")
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG -DETH_RELEASE")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g -DETH_DEBUG")
set(ETH_SHARED 1)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_INSTALL_PREFIX /usr/x86_64-w64-mingw32) # specify Exception Handling Model in msvc
set(ETH_BUILD_PLATFORM "windows") set(CMAKE_C_FLAGS "/EHsc")
set(CMAKE_CXX_FLAGS "/EHsc")
# windows likes static
set(ETH_STATIC 1) set(ETH_STATIC 1)
else ()
set(ETH_BUILD_PLATFORM ${CMAKE_SYSTEM_NAME})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
set(ETH_SHARED 1)
endif()
else ()
message(WARNING "Your compiler is not tested, if you run into any issues, we'd welcome any patches.")
endif ()

148
cmake/EthDependencies.cmake

@ -0,0 +1,148 @@
# all dependencies that are not directly included in the cpp-ethereum distribution are defined here
# for this to work, download the dependency via the cmake script in extdep or install them manually!
# 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}")
set (CMAKE_PREFIX_PATH ${ETH_DEPENDENCY_INSTALL_DIR})
# Qt5 requires opengl
# TODO use proper version of windows SDK (32 vs 64)
# TODO make it possible to use older versions of windows SDK (7.0+ should also work)
# TODO it windows SDK is NOT FOUND, throw ERROR
if (WIN32)
set (CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} "C:/Program Files/Windows Kits/8.1/Lib/winv6.3/um/x86")
message(" - Found windows 8.1 SDK")
#set (CMAKE_PREFIX_PATH "C:/Program Files/Windows Kits/8.1/Lib/winv6.3/um/x64")
endif()
# homebrew installs qts in opt
if (APPLE)
set (CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} "/usr/local/opt/qt5")
endif()
# Dependencies must have a version number, to ensure reproducible build. The version provided here is the one that is in the extdep repository. If you use system libraries, version numbers may be different.
find_package (CryptoPP 5.6.2 EXACT REQUIRED)
message(" - CryptoPP header: ${CRYPTOPP_INCLUDE_DIRS}")
message(" - CryptoPP lib : ${CRYPTOPP_LIBRARIES}")
find_package (LevelDB REQUIRED)
message(" - LevelDB header: ${LEVELDB_INCLUDE_DIRS}")
message(" - LevelDB lib: ${LEVELDB_LIBRARIES}")
# TODO the Jsoncpp package does not yet check for correct version number
find_package (Jsoncpp 0.60 REQUIRED)
message(" - Jsoncpp header: ${JSONCPP_INCLUDE_DIRS}")
message(" - Jsoncpp lib : ${JSONCPP_LIBRARIES}")
# TODO the JsonRpcCpp package does not yet check for correct version number
# json-rpc-cpp support is currently not mandatory
# TODO make headless client optional
# TODO get rid of -DETH_JSONRPC
if (JSONRPC)
find_package (JsonRpcCpp 0.3.2)
if (NOT JSON_RPC_CPP_FOUND)
message (FATAL_ERROR "JSONRPC 0.3.2. not found")
endif()
message (" - json-rpc-cpp header: ${JSON_RPC_CPP_INCLUDE_DIRS}")
message (" - json-rpc-cpp lib : ${JSON_RPC_CPP_LIBRARIES}")
add_definitions(-DETH_JSONRPC)
endif() #JSONRPC
# TODO readline package does not yet check for correct version number
# TODO make readline package dependent on cmake options
# TODO get rid of -DETH_READLINE
find_package (Readline 6.3.8)
if (READLINE_FOUND)
message (" - readline header: ${READLINE_INCLUDE_DIRS}")
message (" - readline lib : ${READLINE_LIBRARIES}")
add_definitions(-DETH_READLINE)
endif ()
# TODO miniupnpc package does not yet check for correct version number
# TODO make miniupnpc package dependent on cmake options
# TODO get rid of -DMINIUPNPC
find_package (Miniupnpc 1.8.2013)
if (MINIUPNPC_FOUND)
message (" - miniupnpc header: ${MINIUPNPC_INCLUDE_DIRS}")
message (" - miniupnpc lib : ${MINIUPNPC_LIBRARIES}")
add_definitions(-DETH_MINIUPNPC)
endif()
# TODO gmp package does not yet check for correct version number
# TODO it is also not required in msvc build
find_package (Gmp 6.0.0)
if (GMP_FOUND)
message(" - gmp Header: ${GMP_INCLUDE_DIRS}")
message(" - gmp lib : ${GMP_LIBRARIES}")
endif()
# curl is only requried for tests
# TODO specify min curl version, on windows we are currenly using 7.29
find_package (CURL)
message(" - curl header: ${CURL_INCLUDE_DIRS}")
message(" - curl lib : ${CURL_LIBRARIES}")
# do not compile GUI
if (NOT HEADLESS)
# we need json rpc to build alethzero
if (NOT JSON_RPC_CPP_FOUND)
message (FATAL_ERROR "JSONRPC is required for GUI client")
endif()
# find all of the Qt packages
# remember to use 'Qt' instead of 'QT', cause unix is case sensitive
# TODO make headless client optional
find_package (Qt5Core REQUIRED)
find_package (Qt5Gui REQUIRED)
find_package (Qt5Quick REQUIRED)
find_package (Qt5Qml REQUIRED)
find_package (Qt5Network REQUIRED)
find_package (Qt5Widgets REQUIRED)
find_package (Qt5WebKit REQUIRED)
find_package (Qt5WebKitWidgets REQUIRED)
# we need to find path to macdeployqt on mac
if (APPLE)
set (MACDEPLOYQT_APP ${Qt5Core_DIR}/../../../bin/macdeployqt)
message(" - macdeployqt path: ${MACDEPLOYQT_APP}")
endif()
endif() #HEADLESS
# use multithreaded boost libraries, with -mt suffix
set(Boost_USE_MULTITHREADED ON)
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
# TODO hanlde other msvc versions or it will fail find them
set(Boost_COMPILER -vc120)
# use static boost libraries *.lib
set(Boost_USE_STATIC_LIBS ON)
elseif (APPLE)
# use static boost libraries *.a
set(Boost_USE_STATIC_LIBS ON)
elseif (UNIX)
# use dynamic boost libraries .dll
set(Boost_USE_STATIC_LIBS OFF)
endif()
find_package(Boost 1.54.0 REQUIRED COMPONENTS thread date_time system regex chrono filesystem unit_test_framework program_options)
message(" - boost header: ${Boost_INCLUDE_DIRS}")
message(" - boost lib : ${Boost_LIBRARIES}")
if (APPLE)
link_directories(/usr/local/lib)
include_directories(/usr/local/include)
endif()

210
cmake/EthDependenciesDeprecated.cmake

@ -1,210 +0,0 @@
# search for and configure dependencies
# deprecated. TODO will rewrite to proper CMake packages
if("${TARGET_PLATFORM}" STREQUAL "w64")
# set(MINIUPNPC_LS /usr/x86_64-w64-mingw32/lib/libminiupnpc.a)
set(LEVELDB_LS leveldb)
set(CRYPTOPP_LS cryptopp)
set(CRYPTOPP_ID /usr/x86_64-w64-mingw32/include/cryptopp)
else()
# Look for available Crypto++ version and if it is >= 5.6.2
find_path(ID cryptlib.h
../cryptopp/src
../../cryptopp/src
/usr/include/cryptopp
/usr/include/crypto++
/usr/local/include/cryptopp
/usr/local/include/crypto++
/opt/local/include/cryptopp
/opt/local/include/crypto++
)
find_library(LS NAMES cryptoppeth cryptopp
../cryptopp/src/../target/build/release
../../cryptopp/src/../target/build/release
PATHS
/usr/lib
/usr/local/lib
/opt/local/lib
)
if (ID AND LS)
message(STATUS "Found Crypto++: ${ID}, ${LS}")
set(_CRYPTOPP_VERSION_HEADER ${ID}/config.h)
if(EXISTS ${_CRYPTOPP_VERSION_HEADER})
file(STRINGS ${_CRYPTOPP_VERSION_HEADER} _CRYPTOPP_VERSION REGEX "^#define CRYPTOPP_VERSION[ \t]+[0-9]+$")
string(REGEX REPLACE "^#define CRYPTOPP_VERSION[ \t]+([0-9]+)" "\\1" _CRYPTOPP_VERSION ${_CRYPTOPP_VERSION})
if(${_CRYPTOPP_VERSION} LESS 562)
message(FATAL_ERROR "Crypto++ version found is smaller than 5.6.2.")
else()
set(CRYPTOPP_ID ${ID} CACHE FILEPATH "")
set(CRYPTOPP_LS ${LS} CACHE FILEPATH "")
message(STATUS "Crypto++ found and version greater or equal to 5.6.2")
endif()
endif()
else()
message(STATUS "Crypto++ Not Found: ${CRYPTOPP_ID}, ${CRYPTOPP_LS}")
endif()
find_path( LEVELDB_ID leveldb/db.h
/usr/include
/usr/local/include
)
if ( LEVELDB_ID STREQUAL "LEVELDB_ID-NOTFOUND" )
message(FATAL_ERROR "Failed to find the LevelDB headers")
else ()
message(STATUS "Found LevelDB Headers")
# Check for accessory dev libraries leveldb and miniupnpc
find_library( LEVELDB_LS NAMES leveldb
PATHS
/usr/lib
/usr/local/lib
/opt/local/lib
/usr/lib/*/
)
if ( LEVELDB_LS STREQUAL "LEVELDB_LS-NOTFOUND" )
message(FATAL_ERROR "Failed to find the LevelDB Library!")
else ()
message(STATUS "Found LevelDB Library: ${LEVELDB_LS}")
add_definitions(-DETH_LEVELDB)
endif ()
endif ()
find_path( PYTHON_ID pyconfig.h
${PYTHON_INCLUDE_DIR}
/usr/include/python2.7
/usr/local/include/python2.7
)
if ( PYTHON_ID STREQUAL "PYTHON_ID-NOTFOUND" )
message(STATUS "Failed to find the Python-2.7 headers")
else ()
message(STATUS "Found Python-2.7 Headers: ${PYTHON_ID}")
# Check for accessory dev libraries leveldb and miniupnpc
find_library( PYTHON_LS NAMES python2.7
PATHS
/usr/lib
/usr/local/lib
/opt/local/lib
/usr/lib/*/
)
if ( PYTHON_LS STREQUAL "PYTHON_LS-NOTFOUND" )
message(STATUS "Failed to find the Python-2.7 Library!")
set(PYTHON_ID)
set(PYTHON_LS)
else ()
message(STATUS "Found Python-2.7 Library: ${PYTHON_LS}")
add_definitions(-DETH_PYTHON)
endif ()
endif ()
find_path( MINIUPNPC_ID miniupnpc/miniwget.h
/usr/include
/usr/local/include
)
if ( MINIUPNPC_ID )
message(STATUS "Found miniupnpc headers")
find_library( MINIUPNPC_LS NAMES miniupnpc
PATHS
/usr/lib
/usr/local/lib
/opt/local/lib
/usr/lib/*/
)
if ( MINIUPNPC_LS )
message(STATUS "Found miniupnpc library: ${MINIUPNPC_LS}")
add_definitions(-DETH_MINIUPNPC)
else ()
message(STATUS "Failed to find the miniupnpc library!")
endif ()
else ()
message(STATUS "Failed to find the miniupnpc headers!")
endif ()
find_path( JSONRPC_ID jsonrpc/rpc.h
/usr/include
/usr/local/include
../libjson-rpc-cpp/src
)
if ( JSONRPC_ID )
message(STATUS "Found jsonrpc headers")
find_library( JSONRPC_LS NAMES jsonrpc
PATHS
/usr/lib
/usr/local/lib
/opt/local/lib
/usr/lib/*/
../libjson-rpc-cpp/build/out
)
if ( JSONRPC_LS )
message(STATUS "Found jsonrpc library: ${JSONRPC_LS}")
add_definitions(-DETH_JSONRPC)
else ()
message(STATUS "Failed to find the jsonrpc library!")
endif ()
else ()
message(STATUS "Failed to find the jsonrpc headers!")
endif ()
find_path( READLINE_ID readline/readline.h
/usr/include
/usr/local/include
)
if ( READLINE_ID )
message(STATUS "Found readline headers")
find_library( READLINE_LS NAMES readline
PATHS
/usr/lib
/usr/local/lib
/opt/local/lib
/usr/lib/*/
)
if ( READLINE_LS )
message(STATUS "Found readline library: ${READLINE_LS}")
add_definitions(-DETH_READLINE)
else ()
message(STATUS "Failed to find the readline library!")
endif ()
else ()
message(STATUS "Failed to find the readline headers!")
endif ()
if (LANGUAGES)
find_package(Boost 1.53 REQUIRED COMPONENTS thread date_time)
else()
find_package(Boost 1.53 REQUIRED COMPONENTS thread date_time system regex)
endif()
set(QTQML 1)
endif()
if(CRYPTOPP_ID)
include_directories(${CRYPTOPP_ID})
endif()
if(PYTHON_ID)
include_directories(${PYTHON_ID})
endif()
if(MINIUPNPC_ID)
include_directories(${MINIUPNPC_ID})
endif()
if(LEVELDB_ID)
include_directories(${LEVELDB_ID})
endif()
if(READLINE_ID)
include_directories(${READLINE_ID})
endif()
if(JSONRPC_ID)
include_directories(${JSONRPC_ID})
endif()
if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
link_directories(/usr/local/lib)
include_directories(/usr/local/include)
endif()

118
cmake/EthExecutableHelper.cmake

@ -0,0 +1,118 @@
#
# this function requires the following variables to be specified:
# ETH_VERSION
# PROJECT_NAME
# PROJECT_VERSION
# PROJECT_COPYRIGHT_YEAR
# PROJECT_VENDOR
# PROJECT_DOMAIN_SECOND
# PROJECT_DOMAIN_FIRST
# SRC_LIST
# HEADERS
#
# params:
# ICON
#
macro(eth_add_executable EXECUTABLE)
set (extra_macro_args ${ARGN})
set (options)
set (one_value_args ICON)
set (multi_value_args UI_RESOURCES)
cmake_parse_arguments (ETH_ADD_EXECUTABLE "${options}" "${one_value_args}" "${multi_value_args}" "${extra_macro_args}")
if (APPLE)
add_executable(${EXECUTABLE} MACOSX_BUNDLE ${SRC_LIST} ${HEADERS} ${ETH_ADD_EXECUTABLE_UI_RESOURCES})
set(PROJECT_VERSION "${ETH_VERSION}")
set(MACOSX_BUNDLE_INFO_STRING "${PROJECT_NAME} ${PROJECT_VERSION}")
set(MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_NAME} ${PROJECT_VERSION}")
set(MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_NAME} ${PROJECT_VERSION}")
set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}")
set(MACOSX_BUNDLE_COPYRIGHT "${PROJECT_COPYRIGHT_YEAR} ${PROJECT_VENDOR}")
set(MACOSX_BUNDLE_GUI_IDENTIFIER "${PROJECT_DOMAIN_SECOND}.${PROJECT_DOMAIN_FIRST}")
set(MACOSX_BUNDLE_BUNDLE_NAME ${EXECUTABLE})
set(MACOSX_BUNDLE_ICON_FILE ${ETH_ADD_EXECUTABLE_ICON})
set_target_properties(${EXECUTABLE} PROPERTIES MACOSX_BUNDLE_INFO_PLIST "${CMAKE_SOURCE_DIR}/EthereumMacOSXBundleInfo.plist.in")
set_source_files_properties(${EXECUTABLE} PROPERTIES MACOSX_PACKAGE_LOCATION MacOS)
set_source_files_properties(${MACOSX_BUNDLE_ICON_FILE}.icns PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
else ()
add_executable(${EXECUTABLE} ${ETH_ADD_EXECUTABLE_UI_RESOURCES} ${SRC_LIST} ${HEADERS})
endif()
endmacro()
#
# this function requires the following variables to be specified:
# ETH_DEPENDENCY_INSTALL_DIR
#
# params:
# QMLDIR
#
macro(eth_install_executable EXECUTABLE)
set (extra_macro_args ${ARGN})
set (options)
set (one_value_args QMLDIR)
set (multi_value_args)
cmake_parse_arguments (ETH_INSTALL_EXECUTABLE "${options}" "${one_value_args}" "${multi_value_args}" "${extra_macro_args}")
if (ETH_INSTALL_EXECUTABLE_QMLDIR)
set(eth_qml_dir "-qmldir=${ETH_INSTALL_EXECUTABLE_QMLDIR}")
endif()
if (APPLE)
# First have qt5 install plugins and frameworks
add_custom_command(TARGET ${EXECUTABLE} POST_BUILD
COMMAND ${MACDEPLOYQT_APP} ${eth_qml_dir} ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${EXECUTABLE}.app
WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY})
# This tool and next will inspect linked libraries in order to determine which dependencies are required
if (${CMAKE_CFG_INTDIR} STREQUAL ".")
set(APP_BUNDLE_PATH "${CMAKE_CURRENT_BINARY_DIR}/${EXECUTABLE}.app")
else ()
set(APP_BUNDLE_PATH "${CMAKE_CURRENT_BINARY_DIR}/\$ENV{CONFIGURATION}/${EXECUTABLE}.app")
endif ()
# TODO check, how fixup_bundle works and if it is required
install(CODE "
include(BundleUtilities)
set(BU_CHMOD_BUNDLE_ITEMS 1)
fixup_bundle(\"${APP_BUNDLE_PATH}\" \"${BUNDLELIBS}\" \"../libqethereum ../libethereum ../secp256k1\")
" COMPONENT RUNTIME )
# Cleanup duplicate libs from macdeployqt
install(CODE "
file(GLOB LINGER_RM \"${APP_BUNDLE_PATH}/Contents/Frameworks/*.dylib\")
if (LINGER_RM)
file(REMOVE \${LINGER_RM})
endif ()
")
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
# copy all dlls to executable directory
# TODO improve that by copying only required dlls
file (GLOB DLLS ${ETH_DEPENDENCY_INSTALL_DIR}/bin/*.dll)
foreach(DLL ${DLLS})
add_custom_command(TARGET ${EXECUTABLE} POST_BUILD
COMMAND cmake -E copy "${DLL}" "$<TARGET_FILE_DIR:${EXECUTABLE}>"
)
endforeach()
add_custom_command(TARGET ${EXECUTABLE} POST_BUILD
COMMAND cmake -E copy_directory
"${ETH_DEPENDENCY_INSTALL_DIR}/plugins/platforms"
$<TARGET_FILE_DIR:${EXECUTABLE}>/platforms
)
install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin)
else()
install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin)
endif ()
endmacro()

108
cmake/FindCryptoPP.cmake

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

34
cmake/FindGmp.cmake

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

52
cmake/FindJsonRpcCpp.cmake

@ -0,0 +1,52 @@
# Find json-rcp-cpp
#
# Find the json-rpc-cpp includes and library
#
# if you nee to add a custom library search path, do it via via CMAKE_PREFIX_PATH
#
# This module defines
# JSON_RCP_CPP_INCLUDE_DIRS, where to find header, etc.
# JSON_RCP_CPP_LIBRARIES, the libraries needed to use json-rpc-cpp.
# JSON_RPC_CPP_SERVER_LIBRARIES, the libraries needed to use json-rpc-cpp-server
# JSON_RPC_CPP_CLIENT_LIBRARIES, the libraries needed to use json-rpc-cpp-client
# JSON_RCP_CPP_FOUND, If false, do not try to use json-rpc-cpp.
# only look in default directories
find_path(
JSON_RPC_CPP_INCLUDE_DIR
NAMES jsonrpccpp/server.h
PATH_SUFFIXES jsonrpc
DOC "json-rpc-cpp include dir"
)
find_library(
JSON_RPC_CPP_COMMON_LIBRARY
NAMES jsonrpccpp-common
DOC "json-rpc-cpp common library"
)
find_library(
JSON_RPC_CPP_SERVER_LIBRARY
NAMES jsonrpccpp-server
DOC "json-rpc-cpp server library"
)
find_library(
JSON_RPC_CPP_CLIENT_LIBRARY
NAMES jsonrpccpp-client
DOC "json-rpc-cpp client library"
)
# these are the variables to be uses by the calling script
set (JSON_RPC_CPP_INCLUDE_DIRS ${JSON_RPC_CPP_INCLUDE_DIR})
set (JSON_RPC_CPP_LIBRARIES ${JSON_RPC_CPP_COMMON_LIBRARY} ${JSON_RPC_CPP_SERVER_LIBRARY} ${JSON_RPC_CPP_CLIENT_LIBRARY})
set (JSON_RPC_CPP_SERVER_LIBRARIES ${JSON_RPC_CPP_COMMON_LIBRARY} ${JSON_RPC_CPP_SERVER_LIBRARY})
set (JSON_RPC_CPP_CLIENT_LIBRARIES ${JSON_RPC_CPP_COMMON_LIBRARY} ${JSON_RPC_CPP_CLIENT_LIBRARY})
# handle the QUIETLY and REQUIRED arguments and set JSON_RPC_CPP_FOUND to TRUE
# if all listed variables are TRUE, hide their existence from configuration view
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(json_rpc_cpp DEFAULT_MSG
JSON_RPC_CPP_COMMON_LIBRARY JSON_RPC_CPP_SERVER_LIBRARY JSON_RPC_CPP_CLIENT_LIBRARY JSON_RPC_CPP_INCLUDE_DIR)
mark_as_advanced (JSON_RPC_CPP_COMMON_LIBRARY JSON_RPC_CPP_SERVER_LIBRARY JSON_RPC_CPP_CLIENT_LIBRARY JSON_RPC_CPP_INCLUDE_DIR)

48
cmake/FindJsoncpp.cmake

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

48
cmake/FindLevelDB.cmake

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

34
cmake/FindMiniupnpc.cmake

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

34
cmake/FindReadline.cmake

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

47
eth/CMakeLists.txt

@ -1,48 +1,33 @@
cmake_policy(SET CMP0015 NEW) cmake_policy(SET CMP0015 NEW)
set(CMAKE_AUTOMOC OFF)
aux_source_directory(. SRC_LIST) aux_source_directory(. SRC_LIST)
include_directories(${Boost_INCLUDE_DIRS})
include_directories(${JSON_RPC_CPP_INCLUDE_DIRS})
include_directories(..) include_directories(..)
set(EXECUTABLE eth) set(EXECUTABLE eth)
file(GLOB HEADERS "*.h") file(GLOB HEADERS "*.h")
add_executable(${EXECUTABLE} ${SRC_LIST} ${HEADERS}) add_executable(${EXECUTABLE} ${SRC_LIST} ${HEADERS})
target_link_libraries(${EXECUTABLE} webthree) add_dependencies(${EXECUTABLE} BuildInfo.h)
target_link_libraries(${EXECUTABLE} secp256k1)
target_link_libraries(${EXECUTABLE} gmp) target_link_libraries(${EXECUTABLE} ${Boost_REGEX_LIBRARIES})
if(MINIUPNPC_LS) target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS})
endif() if (READLINE_FOUND)
target_link_libraries(${EXECUTABLE} ${LEVELDB_LS}) target_link_libraries(${EXECUTABLE} ${READLINE_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS})
if(JSONRPC_LS)
target_link_libraries(${EXECUTABLE} web3jsonrpc)
endif() endif()
if(READLINE_LS)
target_link_libraries(${EXECUTABLE} ${READLINE_LS}) if (JSONRPC)
target_link_libraries(${EXECUTABLE} web3jsonrpc)
endif() endif()
if ("${TARGET_PLATFORM}" STREQUAL "w64") target_link_libraries(${EXECUTABLE} webthree)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++") target_link_libraries(${EXECUTABLE} secp256k1)
target_link_libraries(${EXECUTABLE} boost_system-mt-s)
target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s)
target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s)
target_link_libraries(${EXECUTABLE} gcc)
target_link_libraries(${EXECUTABLE} gdi32)
target_link_libraries(${EXECUTABLE} ws2_32)
target_link_libraries(${EXECUTABLE} mswsock)
target_link_libraries(${EXECUTABLE} shlwapi)
target_link_libraries(${EXECUTABLE} iphlpapi)
set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS)
elseif (UNIX)
else ()
target_link_libraries(${EXECUTABLE} boost_system)
target_link_libraries(${EXECUTABLE} boost_filesystem)
find_package(Threads REQUIRED)
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
endif ()
install( TARGETS ${EXECUTABLE} DESTINATION bin ) install( TARGETS ${EXECUTABLE} DESTINATION bin )

35
eth/main.cpp

@ -27,10 +27,6 @@
#include <signal.h> #include <signal.h>
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim_all.hpp> #include <boost/algorithm/string/trim_all.hpp>
#if ETH_JSONRPC
#include <jsonrpc/connectors/httpserver.h>
#include <libweb3jsonrpc/CorsHttpServer.h>
#endif
#include <libdevcrypto/FileSystem.h> #include <libdevcrypto/FileSystem.h>
#include <libevmcore/Instruction.h> #include <libevmcore/Instruction.h>
#include <libevm/VM.h> #include <libevm/VM.h>
@ -42,6 +38,7 @@
#endif #endif
#if ETH_JSONRPC #if ETH_JSONRPC
#include <libweb3jsonrpc/WebThreeStubServer.h> #include <libweb3jsonrpc/WebThreeStubServer.h>
#include <libweb3jsonrpc/CorsHttpServer.h>
#endif #endif
#include "BuildInfo.h" #include "BuildInfo.h"
using namespace std; using namespace std;
@ -338,9 +335,11 @@ int main(int argc, char** argv)
#if ETH_JSONRPC #if ETH_JSONRPC
shared_ptr<WebThreeStubServer> jsonrpcServer; shared_ptr<WebThreeStubServer> jsonrpcServer;
unique_ptr<jsonrpc::AbstractServerConnector> jsonrpcConnector;
if (jsonrpc > -1) if (jsonrpc > -1)
{ {
jsonrpcServer = shared_ptr<WebThreeStubServer>(new WebThreeStubServer(new jsonrpc::CorsHttpServer(jsonrpc), web3, {us})); jsonrpcConnector = unique_ptr<jsonrpc::AbstractServerConnector>(new jsonrpc::HttpServer(jsonrpc));
jsonrpcServer = shared_ptr<WebThreeStubServer>(new WebThreeStubServer(*jsonrpcConnector.get(), web3, vector<KeyPair>({us})));
jsonrpcServer->setIdentities({us}); jsonrpcServer->setIdentities({us});
jsonrpcServer->StartListening(); jsonrpcServer->StartListening();
} }
@ -428,7 +427,8 @@ int main(int argc, char** argv)
{ {
if (jsonrpc < 0) if (jsonrpc < 0)
jsonrpc = 8080; jsonrpc = 8080;
jsonrpcServer = make_shared<WebThreeStubServer>(new jsonrpc::CorsHttpServer(jsonrpc), web3, vector<KeyPair>({us})); jsonrpcConnector = unique_ptr<jsonrpc::AbstractServerConnector>(new jsonrpc::HttpServer(jsonrpc));
jsonrpcServer = shared_ptr<WebThreeStubServer>(new WebThreeStubServer(*jsonrpcConnector.get(), web3, vector<KeyPair>({us})));
jsonrpcServer->setIdentities({us}); jsonrpcServer->setIdentities({us});
jsonrpcServer->StartListening(); jsonrpcServer->StartListening();
} }
@ -441,9 +441,8 @@ int main(int argc, char** argv)
#endif #endif
else if (cmd == "address") else if (cmd == "address")
{ {
cout << "Current address:" << endl; cout << "Current address:" << endl
const char* addchr = toHex(us.address().asArray()).c_str(); << toHex(us.address().asArray()) << endl;
cout << addchr << endl;
} }
else if (cmd == "secret") else if (cmd == "secret")
{ {
@ -620,7 +619,7 @@ int main(int argc, char** argv)
dev::eth::State state =c->state(index + 1,c->blockChain().numberHash(block)); dev::eth::State state =c->state(index + 1,c->blockChain().numberHash(block));
if (index < state.pending().size()) if (index < state.pending().size())
{ {
Executive e(state); Executive e(state, 0);
Transaction t = state.pending()[index]; Transaction t = state.pending()[index];
state = state.fromPending(index); state = state.fromPending(index);
bytes r = t.rlp(); bytes r = t.rlp();
@ -630,10 +629,10 @@ int main(int argc, char** argv)
OnOpFunc oof; OnOpFunc oof;
if (format == "pretty") if (format == "pretty")
oof = [&](uint64_t steps, Instruction instr, bigint newMemSize, bigint gasCost, void* vvm, void const* vextVM) oof = [&](uint64_t steps, Instruction instr, bigint newMemSize, bigint gasCost, dev::eth::VM* vvm, dev::eth::ExtVMFace const* vextVM)
{ {
dev::eth::VM* vm = (VM*)vvm; dev::eth::VM* vm = vvm;
dev::eth::ExtVM const* ext = (ExtVM const*)vextVM; dev::eth::ExtVM const* ext = static_cast<ExtVM const*>(vextVM);
f << endl << " STACK" << endl; f << endl << " STACK" << endl;
for (auto i: vm->stack()) for (auto i: vm->stack())
f << (h256)i << endl; f << (h256)i << endl;
@ -644,17 +643,17 @@ int main(int argc, char** argv)
f << dec << ext->depth << " | " << ext->myAddress << " | #" << steps << " | " << hex << setw(4) << setfill('0') << vm->curPC() << " : " << dev::eth::instructionInfo(instr).name << " | " << dec << vm->gas() << " | -" << dec << gasCost << " | " << newMemSize << "x32"; f << dec << ext->depth << " | " << ext->myAddress << " | #" << steps << " | " << hex << setw(4) << setfill('0') << vm->curPC() << " : " << dev::eth::instructionInfo(instr).name << " | " << dec << vm->gas() << " | -" << dec << gasCost << " | " << newMemSize << "x32";
}; };
else if (format == "standard") else if (format == "standard")
oof = [&](uint64_t, Instruction instr, bigint, bigint, void* vvm, void const* vextVM) oof = [&](uint64_t, Instruction instr, bigint, bigint, dev::eth::VM* vvm, dev::eth::ExtVMFace const* vextVM)
{ {
dev::eth::VM* vm = (VM*)vvm; dev::eth::VM* vm = vvm;
dev::eth::ExtVM const* ext = (ExtVM const*)vextVM; dev::eth::ExtVM const* ext = static_cast<ExtVM const*>(vextVM);
f << ext->myAddress << " " << hex << toHex(dev::toCompactBigEndian(vm->curPC(), 1)) << " " << hex << toHex(dev::toCompactBigEndian((int)(byte)instr, 1)) << " " << hex << toHex(dev::toCompactBigEndian((uint64_t)vm->gas(), 1)) << endl; f << ext->myAddress << " " << hex << toHex(dev::toCompactBigEndian(vm->curPC(), 1)) << " " << hex << toHex(dev::toCompactBigEndian((int)(byte)instr, 1)) << " " << hex << toHex(dev::toCompactBigEndian((uint64_t)vm->gas(), 1)) << endl;
}; };
else if (format == "standard+") else if (format == "standard+")
oof = [&](uint64_t, Instruction instr, bigint, bigint, void* vvm, void const* vextVM) oof = [&](uint64_t, Instruction instr, bigint, bigint, dev::eth::VM* vvm, dev::eth::ExtVMFace const* vextVM)
{ {
dev::eth::VM* vm = (VM*)vvm; dev::eth::VM* vm = (VM*)vvm;
dev::eth::ExtVM const* ext = (ExtVM const*)vextVM; dev::eth::ExtVM const* ext = static_cast<ExtVM const*>(vextVM);
if (instr == Instruction::STOP || instr == Instruction::RETURN || instr == Instruction::SUICIDE) if (instr == Instruction::STOP || instr == Instruction::RETURN || instr == Instruction::SUICIDE)
for (auto const& i: ext->state().storage(ext->myAddress)) for (auto const& i: ext->state().storage(ext->myAddress))
f << toHex(dev::toCompactBigEndian(i.first, 1)) << " " << toHex(dev::toCompactBigEndian(i.second, 1)) << endl; f << toHex(dev::toCompactBigEndian(i.first, 1)) << " " << toHex(dev::toCompactBigEndian(i.second, 1)) << endl;

30
exp/CMakeLists.txt

@ -1,7 +1,9 @@
cmake_policy(SET CMP0015 NEW) cmake_policy(SET CMP0015 NEW)
set(CMAKE_AUTOMOC OFF)
aux_source_directory(. SRC_LIST) aux_source_directory(. SRC_LIST)
include_directories(${LEVELDB_INCLUDE_DIRS})
include_directories(..) include_directories(..)
set(EXECUTABLE exp) set(EXECUTABLE exp)
@ -10,32 +12,6 @@ add_executable(${EXECUTABLE} ${SRC_LIST})
target_link_libraries(${EXECUTABLE} ethereum) target_link_libraries(${EXECUTABLE} ethereum)
target_link_libraries(${EXECUTABLE} p2p) target_link_libraries(${EXECUTABLE} p2p)
target_link_libraries(${EXECUTABLE} gmp)
target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS})
if(MINIUPNPC_LS)
target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS})
endif()
target_link_libraries(${EXECUTABLE} ${LEVELDB_LS})
if ("${TARGET_PLATFORM}" STREQUAL "w64") install( TARGETS ${EXECUTABLE} DESTINATION bin)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++")
target_link_libraries(${EXECUTABLE} gcc)
target_link_libraries(${EXECUTABLE} gdi32)
target_link_libraries(${EXECUTABLE} ws2_32)
target_link_libraries(${EXECUTABLE} mswsock)
target_link_libraries(${EXECUTABLE} shlwapi)
target_link_libraries(${EXECUTABLE} iphlpapi)
target_link_libraries(${EXECUTABLE} boost_system-mt-s)
target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s)
target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s)
set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS)
elseif (UNIX)
else ()
target_link_libraries(${EXECUTABLE} boost_system)
target_link_libraries(${EXECUTABLE} boost_filesystem)
find_package(Threads REQUIRED)
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
endif ()
install( TARGETS ${EXECUTABLE} DESTINATION bin )

90
exp/main.cpp

@ -20,6 +20,7 @@
* Ethereum client. * Ethereum client.
*/ */
#include <functional> #include <functional>
#include <libethereum/AccountDiff.h>
#include <libdevcore/Log.h> #include <libdevcore/Log.h>
#include <libdevcore/Common.h> #include <libdevcore/Common.h>
#include <libdevcore/CommonData.h> #include <libdevcore/CommonData.h>
@ -28,6 +29,8 @@
#include <libp2p/All.h> #include <libp2p/All.h>
#include <libdevcore/RangeMask.h> #include <libdevcore/RangeMask.h>
#include <libethereum/DownloadMan.h> #include <libethereum/DownloadMan.h>
#include <libethereum/All.h>
#include <liblll/All.h>
#include <libwhisper/WhisperPeer.h> #include <libwhisper/WhisperPeer.h>
#include <libwhisper/WhisperHost.h> #include <libwhisper/WhisperHost.h>
using namespace std; using namespace std;
@ -36,7 +39,7 @@ using namespace dev::eth;
using namespace dev::p2p; using namespace dev::p2p;
using namespace dev::shh; using namespace dev::shh;
#if 1 #if 0
int main() int main()
{ {
DownloadMan man; DownloadMan man;
@ -72,72 +75,25 @@ int main()
cnote << i;*/ cnote << i;*/
return 0; return 0;
} }
#endif #else
int main()
/*int other(bool& o_started)
{ {
setThreadName("other"); KeyPair u = KeyPair::create();
KeyPair cb = KeyPair::create();
short listenPort = 30300; OverlayDB db;
State s(cb.address(), db, BaseState::Empty);
Host ph("Test", NetworkPreferences(listenPort, "", false, true)); cnote << s.rootHash();
auto wh = ph.registerCapability(new WhisperHost()); s.addBalance(u.address(), 1 * ether);
Address c = s.newContract(1000 * ether, compileLLL("(suicide (caller))"));
ph.start(); s.commit();
State before = s;
o_started = true; cnote << "State before transaction: " << before;
Transaction t(0, 10000, 10000, c, bytes(), 0, u.secret());
/// Only interested in odd packets cnote << "Transaction: " << t;
auto w = wh->installWatch(BuildTopicMask()("odd")); cnote << s.balance(c);
s.execute(t.rlp());
unsigned last = 0; cnote << "State after transaction: " << s;
unsigned total = 0; cnote << before.diff(s);
for (int i = 0; i < 100 && last < 81; ++i)
{
for (auto i: wh->checkWatch(w))
{
Message msg = wh->envelope(i).open();
last = RLP(msg.payload()).toInt<unsigned>();
cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
total += last;
}
this_thread::sleep_for(chrono::milliseconds(50));
}
return total;
} }
#endif
int main(int, char**)
{
g_logVerbosity = 0;
bool started = false;
unsigned result;
std::thread listener([&](){ return (result = other(started)); });
while (!started)
this_thread::sleep_for(chrono::milliseconds(50));
short listenPort = 30303;
string remoteHost = "127.0.0.1";
short remotePort = 30300;
Host ph("Test", NetworkPreferences(listenPort, "", false, true));
auto wh = ph.registerCapability(new WhisperHost());
ph.start();
if (!remoteHost.empty())
ph.connect(remoteHost, remotePort);
KeyPair us = KeyPair::create();
for (int i = 0; i < 10; ++i)
{
wh->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"));
this_thread::sleep_for(chrono::milliseconds(250));
}
listener.join();
assert(result == 1 + 9 + 25 + 49 + 81);
return 0;
}*/

55
extdep/CMakeLists.txt

@ -0,0 +1,55 @@
cmake_minimum_required(VERSION 2.8.12)
include(ExternalProject)
include(CMakeParseArguments)
include(eth_download.cmake)
# all dependencies will be installed into this directory, separated by platform
string(TOLOWER ${CMAKE_SYSTEM_NAME} _system_name)
set(ETH_DEPENDENCY_INSTALL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/install/${_system_name}")
set(ETH_DEPENDENCY_SERVER "http://poc-7.ethdev.com/precompiled/${_system_name}")
file(MAKE_DIRECTORY ${ETH_DEPENDENCY_INSTALL_DIR}/lib)
file(MAKE_DIRECTORY ${ETH_DEPENDENCY_INSTALL_DIR}/include)
file(MAKE_DIRECTORY ${ETH_DEPENDENCY_INSTALL_DIR}/bin)
if (ETH_COMPILE)
# json-rpc-cpp and its dependencies
include(compile/jsoncpp.cmake)
include(compile/argtable2.cmake)
include(compile/curl.cmake)
include(compile/json-rpc-cpp.cmake)
# qt and its dependencies
include(compile/icu.cmake)
include(compile/jom.cmake)
include(compile/qt.cmake)
# leveldb and its dependencies
include(compile/snappy.cmake)
include(compile/leveldb.cmake)
# cryptopp
include(compile/cryptopp.cmake)
# boost
include(compile/boost.cmake)
else()
eth_download(jsoncpp)
eth_download(json-rpc-cpp 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)
eth_download(cryptopp)
eth_download(boost)
eth_download(curl)
endif()
# will be re-eanbled later
# include(miniupnpc.cmake)
# if install phase of extep fails, even if libs are already created, the ethereum install will fail

16
extdep/Readme.md

@ -0,0 +1,16 @@
# cpp-ethereum external dependencies
**This is Work-in-Progress!**
This directory hosts the external libraries that are needed to build cpp-ethereum.
To automatically download, build, and link libraries, do
```
cd extdep; mkdir build; cd build; cmake ..; make
```
this will take some time.
To check which libraries are already included, check `CMakeLists.txt`. Other libraries still need to be fetched via the system's package manager.
Libraries will be installed in `cpp-ethereum/extdep/install/<platform-name>`

9
extdep/cmake/FindCURL.cmake

@ -0,0 +1,9 @@
# hacky way to resolve nested dependencies - needed for json-rpc-cpp
find_library(CURL_LIBRARY NAMES curl
PATHS
${ETH_DEPENDENCY_INSTALL_DIR}/lib
)
set(CURL_LIBRARIES ${CURL_LIBRARY})
set(CURL_INCLUDE_DIRS ${ETH_DEPENDENCY_INSTALL_DIR}/include)

13
extdep/compile/argtable2.cmake

@ -0,0 +1,13 @@
if (APPLE)
elseif (WIN32)
ExternalProject_Add(argtable2
GIT_REPOSITORY https://github.com/debris/argtable.git
GIT_TAG master
BINARY_DIR argtable2-prefix/src/argtable2
CONFIGURE_COMMAND cmake .
BUILD_COMMAND devenv argtable2.sln /build release
INSTALL_COMMAND cmd /c cp src/Release/argtable2.lib ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp src/argtable2.h ${ETH_DEPENDENCY_INSTALL_DIR}/include
)
else()
endif()

19
extdep/compile/boost.cmake

@ -0,0 +1,19 @@
if (APPLE)
elseif (WIN32)
set(boost_address_model)
# on windows 64:
# set(boost_address_model address-model=64)
set(boost_targets --with-filesystem --with-system --with-thread --with-date_time --with-regex --with-test --with-chrono --with-program_options)
ExternalProject_Add(boost
URL http://downloads.sourceforge.net/project/boost/boost/1.55.0/boost_1_55_0.tar.gz
BINARY_DIR boost-prefix/src/boost
CONFIGURE_COMMAND ./bootstrap.bat
BUILD_COMMAND ./b2.exe -j4 --build-type=complete link=static runtime-link=shared variant=debug,release threading=multi ${boost_addressModel} ${boost_targets} install --prefix=${ETH_DEPENDENCY_INSTALL_DIR}
INSTALL_COMMAND cmake -E rename ${ETH_DEPENDENCY_INSTALL_DIR}/include/boost-1_55/boost ${ETH_DEPENDENCY_INSTALL_DIR}/include/boost
)
else()
endif()

33
extdep/compile/cryptopp.cmake

@ -0,0 +1,33 @@
# CryptoPP does not have good cross-platform support, there exist several different other projects to make it work ...
# TODO the OS X build throws a lot of warnings, but compiles fine
if (APPLE)
ExternalProject_Add(cryptopp
URL https://downloads.sourceforge.net/project/cryptopp/cryptopp/5.6.2/cryptopp562.zip
BINARY_DIR cryptopp-prefix/src/cryptopp
CONFIGURE_COMMAND ""
BUILD_COMMAND make CXX=clang++ CXXFLAGS=-DCRYPTOPP_DISABLE_ASM
INSTALL_COMMAND make install PREFIX=${ETH_DEPENDENCY_INSTALL_DIR}
)
elseif (WIN32)
file(MAKE_DIRECTORY ${ETH_DEPENDENCY_INSTALL_DIR}/include/cryptopp)
ExternalProject_Add(cryptopp
SVN_REPOSITORY http://svn.code.sf.net/p/cryptopp/code/trunk/c5
SVN_REVISION -r "541"
BINARY_DIR cryptopp-prefix/src/cryptopp
CONFIGURE_COMMAND devenv cryptest.sln /upgrade
BUILD_COMMAND devenv cryptest.sln /build release
INSTALL_COMMAND cmd /c cp Win32/DLL_Output/Release/cryptopp.dll ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp Win32/DLL_Output/Release/cryptopp.lib ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp *.h ${ETH_DEPENDENCY_INSTALL_DIR}/include/cryptopp
)
# on Linux, the default Makefile does not work.
else()
ExternalProject_Add(cryptopp
URL https://github.com/mmoss/cryptopp/archive/v5.6.2.zip
BINARY_DIR cryptopp-prefix/src/cryptopp
CONFIGURE_COMMAND ""
BUILD_COMMAND scons --shared --prefix=${ETH_DEPENDENCY_INSTALL_DIR}
INSTALL_COMMAND ""
)
endif()

29
extdep/compile/curl.cmake

@ -0,0 +1,29 @@
if (APPLE)
ExternalProject_Add(curl
URL http://curl.haxx.se/download/curl-7.38.0.tar.bz2
BINARY_DIR curl-prefix/src/curl
CONFIGURE_COMMAND ./configure --with-darwinssl --prefix=${ETH_DEPENDENCY_INSTALL_DIR} --exec-prefix=${ETH_DEPENDENCY_INSTALL_DIR}
BUILD_COMMAND make -j 3
INSTALL_COMMAND make install
)
elseif (WIN32)
ExternalProject_Add(curl
GIT_REPOSITORY https://github.com/debris/libcurl-7.29
GIT_TAG master
BINARY_DIR curl-prefix/src/curl
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND cmd /c cp lib/release/libcurl.lib ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp -R include/curl ${ETH_DEPENDENCY_INSTALL_DIR}/include
)
else()
ExternalProject_Add(curl
URL http://curl.haxx.se/download/curl-7.38.0.tar.bz2
BINARY_DIR curl-prefix/src/curl
CONFIGURE_COMMAND CONFIG_CMD ./configure --prefix=${ETH_DEPENDENCY_INSTALL_DIR} --exec-prefix=${ETH_DEPENDENCY_INSTALL_DIR}
BUILD_COMMAND make -j 3
INSTALL_COMMAND make install
)
endif()

17
extdep/compile/icu.cmake

@ -0,0 +1,17 @@
if (APPLE)
elseif (WIN32)
ExternalProject_Add(icu
GIT_REPOSITORY https://github.com/debris/icu-win32.git
GIT_TAG master
BINARY_DIR icu-prefix/src/icu
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND cmake -E copy_directory . ${ETH_DEPENDENCY_INSTALL_DIR}
)
else()
endif()

16
extdep/compile/jom.cmake

@ -0,0 +1,16 @@
if (APPLE)
elseif (WIN32)
ExternalProject_Add(jom
URL http://download.qt-project.org/official_releases/jom/jom.zip
BINARY_DIR jom-prefix/src/jom
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND cmake -E copy jom.exe ${ETH_DEPENDENCY_INSTALL_DIR}/bin
)
else()
endif()

40
extdep/compile/json-rpc-cpp.cmake

@ -0,0 +1,40 @@
# json-rpc-cpp is under heavy development, not yet stable, and multiplatform builds are not yet available.
# DO NOT MESS WITH THESE SETTINGS! IF YOU HAVE TO MAKE CHANGES HERE, CONSULT sven@ethdev.com BEFOREHAND!!
# DO NOT CHANGE ANYTHING HERE!
if(APPLE)
ExternalProject_Add(json-rpc-cpp
# DEPENDS argtable2 jsoncpp
# DEPENDS curl # re-enable later, when we build curl again
GIT_REPOSITORY https://github.com/cinemast/libjson-rpc-cpp.git
GIT_TAG v0.3.2
BINARY_DIR json-rpc-cpp-prefix/src/json-rpc-cpp
CONFIGURE_COMMAND cmake -DCMAKE_INSTALL_PREFIX=${ETH_DEPENDENCY_INSTALL_DIR} -DCMAKE_MODULE_PATH:PATH=${CMAKE_CURRENT_SOURCE_DIR}/cmake -DETH_DEPENDENCY_INSTALL_DIR:PATH=${ETH_DEPENDENCY_INSTALL_DIR} -DCMAKE_BUILD_TYPE=None -DCMAKE_FIND_FRAMEWORK=LAST -Wno-dev .
BUILD_COMMAND make -j 3
INSTALL_COMMAND make install && ${CMAKE_CURRENT_SOURCE_DIR}/scripts/json-rpc-cpp_osx.sh . ${ETH_DEPENDENCY_INSTALL_DIR}
)
elseif (WIN32)
ExternalProject_Add(json-rpc-cpp
DEPENDS argtable2 jsoncpp curl
GIT_REPOSITORY https://github.com/debris/libjson-rpc-cpp.git
GIT_TAG windows
BINARY_DIR json-rpc-cpp-prefix/src/json-rpc-cpp
CONFIGURE_COMMAND cmake -DCMAKE_PREFIX_PATH=${ETH_DEPENDENCY_INSTALL_DIR} -DCURL_LIBRARIES=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libcurl.lib .
BUILD_COMMAND devenv libjson-rpc-cpp.sln /build release
INSTALL_COMMAND cmd /c cp lib/Release/* ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp -R src/jsonrpccpp ${ETH_DEPENDENCY_INSTALL_DIR}/include
)
else()
ExternalProject_Add(json-rpc-cpp
# DEPENDS argtable2 jsoncpp
# DEPENDS curl # re-enable later, when we build curl again
GIT_REPOSITORY https://github.com/cinemast/libjson-rpc-cpp.git
GIT_TAG v0.3.2
BINARY_DIR json-rpc-cpp-prefix/src/json-rpc-cpp
CONFIGURE_COMMAND cmake -DCMAKE_INSTALL_PREFIX=${ETH_DEPENDENCY_INSTALL_DIR} -DCMAKE_MODULE_PATH:PATH=${CMAKE_CURRENT_SOURCE_DIR}/cmake -DETH_DEPENDENCY_INSTALL_DIR:PATH=${ETH_DEPENDENCY_INSTALL_DIR} -DCMAKE_BUILD_TYPE=None -DCMAKE_FIND_FRAMEWORK=LAST .
BUILD_COMMAND make -j 3
INSTALL_COMMAND make install
)
endif()

16
extdep/compile/jsoncpp.cmake

@ -0,0 +1,16 @@
if (APPLE)
elseif (WIN32)
file(MAKE_DIRECTORY ${ETH_DEPENDENCY_INSTALL_DIR}/include/jsoncpp)
ExternalProject_Add(jsoncpp
GIT_REPOSITORY https://github.com/open-source-parsers/jsoncpp
GIT_TAG svn-import
BINARY_DIR jsoncpp-prefix/src/jsoncpp
CONFIGURE_COMMAND cmake .
BUILD_COMMAND devenv jsoncpp.sln /build release
INSTALL_COMMAND cmd /c cp lib/Release/jsoncpp.lib ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp -R include/json ${ETH_DEPENDENCY_INSTALL_DIR}/include/jsoncpp
)
else()
endif()

23
extdep/compile/leveldb.cmake

@ -0,0 +1,23 @@
if (APPLE)
ExternalProject_Add(leveldb
#DEPENDS snappy
URL https://leveldb.googlecode.com/files/leveldb-1.15.0.tar.gz
BINARY_DIR leveldb-prefix/src/leveldb
#CONFIGURE_COMMAND patch < ${CMAKE_CURRENT_SOURCE_DIR}/compile/leveldb_osx.patch
CONFIGURE_COMMAND ""
BUILD_COMMAND export ETH_DEPENDENCY_INSTALL_DIR=${ETH_DEPENDENCY_INSTALL_DIR} && make -j 3
INSTALL_COMMAND cp -rf include/leveldb ${ETH_DEPENDENCY_INSTALL_DIR}/include/ && cp libleveldb.a ${ETH_DEPENDENCY_INSTALL_DIR}/lib && cp libleveldb.dylib.1.15 ${ETH_DEPENDENCY_INSTALL_DIR}/lib/libleveldb.dylib
)
elseif (WIN32)
ExternalProject_Add(leveldb
GIT_REPOSITORY https://github.com/debris/leveldb-win32.git
GIT_TAG master
BINARY_DIR leveldb-prefix/src/leveldb
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND cmd /c cp lib/LibLevelDB.lib ${ETH_DEPENDENCY_INSTALL_DIR}/lib/leveldb.lib && cp -R include/leveldb ${ETH_DEPENDENCY_INSTALL_DIR}/include
)
else()
endif()

18
extdep/compile/leveldb_osx.patch

@ -0,0 +1,18 @@
--- Makefile 2014-11-07 00:54:05.000000000 +0100
+++ MakefilePatch 2014-11-07 00:56:59.000000000 +0100
@@ -17,11 +17,11 @@
# this file is generated by the previous line to set build flags and sources
include build_config.mk
-CFLAGS += -I. -I./include $(PLATFORM_CCFLAGS) $(OPT)
-CXXFLAGS += -I. -I./include $(PLATFORM_CXXFLAGS) $(OPT)
+CFLAGS += -I. -I./include $(PLATFORM_CCFLAGS) $(OPT)
+CXXFLAGS += -I. -I./include $(PLATFORM_CXXFLAGS) $(OPT) -DSNAPPY -I$(ETH_DEPENDENCY_INSTALL_DIR)/include
-LDFLAGS += $(PLATFORM_LDFLAGS)
-LIBS += $(PLATFORM_LIBS)
+LDFLAGS += $(PLATFORM_LDFLAGS) -L$(ETH_DEPENDENCY_INSTALL_DIR)/lib
+LIBS += $(PLATFORM_LIBS) -lsnappy
LIBOBJECTS = $(SOURCES:.cc=.o)
MEMENVOBJECTS = $(MEMENV_SOURCES:.cc=.o)

32
extdep/compile/qt.cmake

@ -0,0 +1,32 @@
if (APPLE)
ExternalProject_add(qt
URL http://qtmirror.ics.com/pub/qtproject/official_releases/qt/5.3/5.3.2/single/qt-everywhere-opensource-src-5.3.2.tar.gz
BINARY_DIR qt-prefix/src/qt
PATCH_COMMAND patch -d qtmultimedia/src/plugins/avfoundation/mediaplayer < ${CMAKE_CURRENT_SOURCE_DIR}/compile/qt_osx.patch
CONFIGURE_COMMAND ./configure -prefix ${ETH_DEPENDENCY_INSTALL_DIR} -system-zlib -qt-libpng -qt-libjpeg -confirm-license -opensource -nomake tests -release -nomake examples -no-xcb -arch x86_64
BUILD_COMMAND make
INSTALL_COMMAND make install
)
elseif(WIN32)
ExternalProject_Add(qt
DEPENDS icu jom
URL http://qtmirror.ics.com/pub/qtproject/official_releases/qt/5.3/5.3.2/single/qt-everywhere-opensource-src-5.3.2.tar.gz
BINARY_DIR qt-prefix/src/qt
UPDATE_COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/compile/qt_tools.bat
#PATCH_COMMAND cmake -E copy ${CMAKE_CURRENT_SOURCE_DIR}/compile/qt_configure.bat qtbase/configure.bat
CONFIGURE_COMMAND configure -prefix ${ETH_DEPENDENCY_INSTALL_DIR} -opensource -confirm-license -release -opengl desktop -platform win32-msvc2013 -icu -I ${ETH_DEPENDENCY_INSTALL_DIR}/include -L ${ETH_DEPENDENCY_INSTALL_DIR}/lib -nomake tests -nomake examples
BUILD_COMMAND nmake
INSTALL_COMMAND nmake install
)
ExternalProject_Add_Step(qt configure_paths
COMMAND set PATH=${ETH_DEPENDENCY_INSTALL_DIR}/bin;%cd%/gnuwin32/bin;%cd%/qtbase/bin;%PATH%
DEPENDEES patch
DEPENDERS configure
)
else()
endif()

111
extdep/compile/qt_configure.bat

@ -0,0 +1,111 @@
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::
:: Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
:: Contact: http://www.qt-project.org/legal
::
:: This file is part of the tools applications of the Qt Toolkit.
::
:: $QT_BEGIN_LICENSE:LGPL$
:: Commercial License Usage
:: Licensees holding valid commercial Qt licenses may use this file in
:: accordance with the commercial license agreement provided with the
:: Software or, alternatively, in accordance with the terms contained in
:: a written agreement between you and Digia. For licensing terms and
:: conditions see http://qt.digia.com/licensing. For further information
:: use the contact form at http://qt.digia.com/contact-us.
::
:: GNU Lesser General Public License Usage
:: Alternatively, this file may be used under the terms of the GNU Lesser
:: General Public License version 2.1 as published by the Free Software
:: Foundation and appearing in the file LICENSE.LGPL included in the
:: packaging of this file. Please review the following information to
:: ensure the GNU Lesser General Public License version 2.1 requirements
:: will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
::
:: In addition, as a special exception, Digia gives you certain additional
:: rights. These rights are described in the Digia Qt LGPL Exception
:: version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
::
:: GNU General Public License Usage
:: Alternatively, this file may be used under the terms of the GNU
:: General Public License version 3.0 as published by the Free Software
:: Foundation and appearing in the file LICENSE.GPL included in the
:: packaging of this file. Please review the following information to
:: ensure the GNU General Public License version 3.0 requirements will be
:: met: http://www.gnu.org/copyleft/gpl.html.
::
::
:: $QT_END_LICENSE$
::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
@echo off
set QTSRC=%~dp0
set QTDIR=%CD%
::if not exist %QTSRC%\.gitignore goto sconf
echo Please wait while bootstrapping configure ...
for %%C in (cl.exe icl.exe g++.exe perl.exe) do set %%C=%%~$PATH:C
if "%perl.exe%" == "" (
echo Perl not found in PATH. Aborting. >&2
exit /b 1
)
if not exist mkspecs (
md mkspecs
if errorlevel 1 goto exit
)
perl %QTSRC%bin\syncqt.pl -minimal -module QtCore -outdir %QTDIR% %QTSRC%
if errorlevel 1 goto exit
if not exist tools\configure (
md tools\configure
if errorlevel 1 goto exit
)
cd tools\configure
if errorlevel 1 goto exit
echo #### Generated by configure.bat - DO NOT EDIT! ####> Makefile
echo/>> Makefile
for /f "tokens=3 usebackq" %%V in (`findstr QT_VERSION_STR %QTSRC%\src\corelib\global\qglobal.h`) do @echo QTVERSION = %%~V>> Makefile
if not "%cl.exe%" == "" (
echo CXX = cl>>Makefile
echo EXTRA_CXXFLAGS =>>Makefile
rem This must have a trailing space.
echo QTSRC = %QTSRC% >> Makefile
set tmpl=win32
set make=nmake
) else if not "%icl.exe%" == "" (
echo CXX = icl>>Makefile
echo EXTRA_CXXFLAGS = /Zc:forScope>>Makefile
rem This must have a trailing space.
echo QTSRC = %QTSRC% >> Makefile
set tmpl=win32
set make=nmake
) else if not "%g++.exe%" == "" (
echo CXX = g++>>Makefile
echo EXTRA_CXXFLAGS =>>Makefile
rem This must NOT have a trailing space.
echo QTSRC = %QTSRC:\=/%>> Makefile
set tmpl=mingw
set make=mingw32-make
) else (
echo No suitable compiler found in PATH. Aborting. >&2
cd ..\..
exit /b 1
)
echo/>> Makefile
type %QTSRC%tools\configure\Makefile.%tmpl% >> Makefile
%make%
if errorlevel 1 (cd ..\.. & exit /b 1)
cd ..\..
:conf
configure.exe -srcdir %QTSRC% %*
goto exit
:sconf
%QTSRC%\configure.exe %*
:exit

11
extdep/compile/qt_osx.patch

@ -0,0 +1,11 @@
--- avfmediaplayersession.mm 2014-09-11 12:48:26.000000000 +0200
+++ avfmediaplayersessionPatch.mm 2014-12-01 12:53:14.000000000 +0100
@@ -295,7 +295,7 @@
//AVPlayerItem "status" property value observer.
if (context == AVFMediaPlayerSessionObserverStatusObservationContext)
{
- AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
+ AVPlayerStatus status = (AVPlayerStatus)[[change objectForKey:NSKeyValueChangeNewKey] integerValue];
switch (status)
{
//Indicates that the status of the player is not yet known because

2
extdep/compile/qt_tools.bat

@ -0,0 +1,2 @@
rem : import VC environment vars
call "%VS120COMNTOOLS%\..\..\VC\vcvarsall.bat" x86

14
extdep/compile/snappy.cmake

@ -0,0 +1,14 @@
if (APPLE)
ExternalProject_Add(snappy
URL https://snappy.googlecode.com/files/snappy-1.1.1.tar.gz
BINARY_DIR snappy-prefix/src/snappy
CONFIGURE_COMMAND ./configure --disable-dependency-tracking --prefix=${ETH_DEPENDENCY_INSTALL_DIR}
BUILD_COMMAND ""
INSTALL_COMMAND make install
)
elseif(WIN32)
else()
endif()

74
extdep/eth_download.cmake

@ -0,0 +1,74 @@
# this macro requires the following variables to be specified:
#
# ETH_DEPENDENCY_SERVER - server from which dependencies should be downloaded
# ETH_DEPENDENCY_INSTALL_DIR - install location for all dependencies
#
# usage:
#
# eth_download("json-rpc-cpp")
# eth_download("json-rpc-cpp" VERSION "0.3.2")
#
# params:
# VERSION - exact version we want to use
# OSX_SCRIPT - script which will be executed on apple in install phase
# UNIX_SCRIPT - script which will be executed on unix in install phase
# WIN_SCRIPT - script which will be executed on win in install phase
# OSX_SCRIPT, WIN_SCRIPT, UNIX_SCRIPT are taking 2 params:
# $1 is package_source,
# $2 is ETH_DEPENDENCY_INSTALL_DIR
#
# parsing arguments
# http://www.cmake.org/cmake/help/v3.0/module/CMakeParseArguments.html
#
# for macos you may need to specify OSX_SCRIPT with install_name_tool to fix dylib
# http://stackoverflow.com/questions/2985315/using-install-name-tool-whats-going-wrong
#
# TODO:
# check if install_command is handling symlinks correctly on linux and windows
macro(eth_download eth_package_name)
set (extra_macro_args ${ARGN})
set (options)
set (one_value_args VERSION OSX_SCRIPT UNIX_SCRIPT WIN_SCRIPT)
set (multi_value_args)
cmake_parse_arguments (ETH_DOWNLOAD "${options}" "${one_value_args}" "${multi_value_args}" ${extra_macro_args})
if (ETH_DOWNLOAD_VERSION)
set(eth_tar_name "${eth_package_name}-${ETH_DOWNLOAD_VERSION}.tar.gz")
else()
set(eth_tar_name "${eth_package_name}.tar.gz")
endif()
message(STATUS "download path for ${eth_package_name} is : ${ETH_DEPENDENCY_SERVER}/${eth_tar_name}")
# we need that to copy symlinks
# see http://superuser.com/questions/138587/how-to-copy-symbolic-links
if (APPLE)
set (eth_package_copy cp -a . ${ETH_DEPENDENCY_INSTALL_DIR})
set (eth_package_install ${ETH_DOWNLOAD_OSX_SCRIPT})
elseif (UNIX)
set (eth_package_copy cp -a . ${ETH_DEPENDENCY_INSTALL_DIR})
set (eth_package_install ${ETH_DOWNLOAD_UNIX_SCRIPT})
else ()
set (eth_package_copy cmake -E copy_directory . ${ETH_DEPENDENCY_INSTALL_DIR})
set (eth_package_install ${ETH_DOWNLOAD_WIN_SCRIPT})
endif()
if (eth_package_install)
message(STATUS "install script: ${eth_package_install}")
set (eth_package_install ${eth_package_install} . ${ETH_DEPENDENCY_INSTALL_DIR})
else ()
set (eth_package_install echo 0) # cause empty string is not handled properly
endif()
ExternalProject_Add(${eth_package_name}
URL ${ETH_DEPENDENCY_SERVER}/${eth_tar_name}
BINARY_DIR ${eth_package_name}-prefix/src/${eth_package_name}
CONFIGURE_COMMAND ""
BUILD_COMMAND ${eth_package_copy}
INSTALL_COMMAND ${eth_package_install}
)
endmacro()

11
extdep/miniupnpc.cmake

@ -0,0 +1,11 @@
# TODO this file is not used yet, but will be in future
include(ExternalProject)
ExternalProject_Add(miniupnpc
URL http://miniupnp.tuxfamily.org/files/download.php?file=miniupnpc-1.9.20141027.tar.gz
BINARY_DIR miniupnpc-prefix/src/miniupnpc
CONFIGURE_COMMAND ""
BUILD_COMMAND make -j 3
INSTALL_COMMAND make install INSTALLPREFIX=${ETH_DEPENDENCY_INSTALL_DIR}
)

29
extdep/scripts/json-rpc-cpp_osx.sh

@ -0,0 +1,29 @@
#!/bin/bash
ETH_DEPENDENCY_SOURCE_DIR=$1
ETH_DEPENDENCY_INSTALL_DIR=$2
OLD_COMMON_DYLIB="libjsonrpccpp-common.0.dylib"
COMMON_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libjsonrpccpp-common.0.dylib
SERVER_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libjsonrpccpp-server.0.dylib
CLIENT_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libjsonrpccpp-client.0.dylib
# fix bin
STAB_EXEC=${ETH_DEPENDENCY_INSTALL_DIR}/bin/jsonrpcstub
install_name_tool -change ${OLD_COMMON_DYLIB} ${COMMON_DYLIB} ${STAB_EXEC}
# fix common
install_name_tool -id ${COMMON_DYLIB} ${COMMON_DYLIB}
# fix server
install_name_tool -id ${SERVER_DYLIB} ${SERVER_DYLIB}
install_name_tool -change ${OLD_COMMON_DYLIB} ${COMMON_DYLIB} ${SERVER_DYLIB}
# fix client
install_name_tool -id ${CLIENT_DYLIB} ${CLIENT_DYLIB}
install_name_tool -change ${OLD_COMMON_DYLIB} ${COMMON_DYLIB} ${CLIENT_DYLIB}
# TODO fix argtable and jsoncpp once they are downloaded as dependencies

12
extdep/scripts/leveldb_osx.sh

@ -0,0 +1,12 @@
#!/bin/bash
ETH_DEPENDENCY_SOURCE_DIR=$1
ETH_DEPENDENCY_INSTALL_DIR=$2
OLD_SNAPPY_DYLIB="/Users/marekkotewicz/ethereum/cpp-ethereum/extdep/install/darwin/lib/libsnappy.1.dylib"
SNAPPY_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libsnappy.dylib
LEVELDB_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libleveldb.dylib
install_name_tool -id ${LEVELDB_DYLIB} ${LEVELDB_DYLIB}
install_name_tool -change ${OLD_SNAPPY_DYLIB} ${SNAPPY_DYLIB} ${LEVELDB_DYLIB}

8
extdep/scripts/snappy_osx.sh

@ -0,0 +1,8 @@
#!/bin/bash
ETH_DEPENDENCY_SOURCE_DIR=$1
ETH_DEPENDENCY_INSTALL_DIR=$2
SNAPPY_DYLIB=${ETH_DEPENDENCY_INSTALL_DIR}/lib/libsnappy.dylib
install_name_tool -id ${SNAPPY_DYLIB} ${SNAPPY_DYLIB}

117
iethxi/CMakeLists.txt

@ -1,117 +0,0 @@
cmake_policy(SET CMP0015 NEW)
if ("${TARGET_PLATFORM}" STREQUAL "w64")
cmake_policy(SET CMP0020 NEW)
endif ()
set(CMAKE_INCLUDE_CURRENT_DIR ON)
aux_source_directory(. SRC_LIST)
include_directories(..)
link_directories(../libethcore)
link_directories(../libethereum)
link_directories(../libqethereum)
# Find Qt5 for Apple and update src_list for windows
if (APPLE)
# homebrew defaults to qt4 and installs qt5 as 'keg-only'
# which places it into /usr/local/opt insteadof /usr/local.
set(CMAKE_PREFIX_PATH /usr/local/opt/qt5)
include_directories(/usr/local/opt/qt5/include /usr/local/include)
elseif ("${TARGET_PLATFORM}" STREQUAL "w64")
set(SRC_LIST ${SRC_LIST} ../windows/qt_plugin_import.cpp)
elseif (UNIX)
set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ";$ENV{QTDIR}/lib/cmake")
endif ()
find_package(Qt5Widgets REQUIRED)
find_package(Qt5Gui REQUIRED)
find_package(Qt5Quick REQUIRED)
find_package(Qt5Qml REQUIRED)
find_package(Qt5Network REQUIRED)
qt5_wrap_ui(ui_Main.h Main.ui)
qt5_add_resources(RESOURCE_ADDED Resources.qrc)
# Set name of binary and add_executable()
if (APPLE)
set(EXECUTEABLE IEthXi)
set(CMAKE_INSTALL_PREFIX ./)
set(BIN_INSTALL_DIR ".")
set(DOC_INSTALL_DIR ".")
set(PROJECT_VERSION "${ETH_VERSION}")
set(MACOSX_BUNDLE_INFO_STRING "${PROJECT_NAME} ${PROJECT_VERSION}")
set(MACOSX_BUNDLE_BUNDLE_VERSION "${PROJECT_NAME} ${PROJECT_VERSION}")
set(MACOSX_BUNDLE_LONG_VERSION_STRING "${PROJECT_NAME} ${PROJECT_VERSION}")
set(MACOSX_BUNDLE_SHORT_VERSION_STRING "${PROJECT_VERSION}")
set(MACOSX_BUNDLE_COPYRIGHT "${PROJECT_COPYRIGHT_YEAR} ${PROJECT_VENDOR}")
set(MACOSX_BUNDLE_GUI_IDENTIFIER "${PROJECT_DOMAIN_SECOND}.${PROJECT_DOMAIN_FIRST}")
set(MACOSX_BUNDLE_BUNDLE_NAME ${EXECUTEABLE})
include(BundleUtilities)
add_executable(${EXECUTEABLE} MACOSX_BUNDLE Main.ui ${RESOURCE_ADDED} ${SRC_LIST})
else ()
set(EXECUTEABLE iethxi)
add_executable(${EXECUTEABLE} Main.ui ${RESOURCE_ADDED} ${SRC_LIST})
endif ()
qt5_use_modules(${EXECUTEABLE} Core Gui Widgets Network Quick Qml)
target_link_libraries(${EXECUTEABLE} qethereum ethereum secp256k1 ${CRYPTOPP_LS})
if (APPLE)
if (${ADDFRAMEWORKS})
set_target_properties(${EXECUTEABLE} PROPERTIES MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/EthereumMacOSXBundleInfo.plist.in")
endif ()
SET_SOURCE_FILES_PROPERTIES(${EXECUTEABLE} PROPERTIES MACOSX_PACKAGE_LOCATION MacOS)
# This is a workaround for when the build-type defaults to Debug, and when a multi-config generator like xcode is used, where the type
# will not be set but defaults to release.
set(generator_lowercase "${CMAKE_GENERATOR}")
string(TOLOWER "${CMAKE_GENERATOR}" generator_lowercase)
if ("${generator_lowercase}" STREQUAL "xcode")
# TODO: Not sure how to resolve this. Possibly \${TARGET_BUILD_DIR}
set(binary_build_dir "${CMAKE_CURRENT_BINARY_DIR}/Debug")
else ()
set(binary_build_dir "${CMAKE_CURRENT_BINARY_DIR}")
endif ()
set(APPS ${binary_build_dir}/${EXECUTEABLE}.app)
# This tool and the next will automatically looked at the linked libraries in order to determine what dependencies are required. Thus, target_link_libaries only needs to add ethereum and secp256k1 (above)
install(CODE "
include(BundleUtilities)
set(BU_CHMOD_BUNDLE_ITEMS 1)
fixup_bundle(\"${APPS}\" \"${BUNDLELIBS}\" \"../libqethereum ../libethereum ../secp256k1\")
" COMPONENT RUNTIME )
if (${ADDFRAMEWORKS})
add_custom_target(addframeworks ALL
COMMAND /usr/local/opt/qt5/bin/macdeployqt ${binary_build_dir}/${EXECUTEABLE}.app
WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}
DEPENDS ${PROJECT_NAME}
)
endif ()
elseif ("${TARGET_PLATFORM}" STREQUAL "w64")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-keep-inline-dllexport -static-libgcc -static-libstdc++ -static")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-s -Wl,-subsystem,windows -mthreads -L/usr/x86_64-w64-mingw32/plugins/platforms")
target_link_libraries(${EXECUTEABLE} gcc)
target_link_libraries(${EXECUTEABLE} mingw32 qtmain mswsock iphlpapi qwindows shlwapi Qt5PlatformSupport gdi32 comdlg32 oleaut32 imm32 winmm ole32 uuid ws2_32)
target_link_libraries(${EXECUTEABLE} boost_system-mt-s)
target_link_libraries(${EXECUTEABLE} boost_filesystem-mt-s)
target_link_libraries(${EXECUTEABLE} boost_thread_win32-mt-s)
target_link_libraries(${EXECUTEABLE} Qt5PlatformSupport)
set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS)
elseif (UNIX)
else ()
target_link_libraries(${EXECUTEABLE} boost_system)
target_link_libraries(${EXECUTEABLE} boost_filesystem)
find_package(Threads REQUIRED)
target_link_libraries(${EXECUTEABLE} ${CMAKE_THREAD_LIBS_INIT})
install( TARGETS ${EXECUTEABLE} RUNTIME DESTINATION bin )
endif ()

38
iethxi/EthereumMacOSXBundleInfo.plist.in

@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${MACOSX_BUNDLE_EXECUTABLE_NAME}</string>
<key>CFBundleGetInfoString</key>
<string>${MACOSX_BUNDLE_INFO_STRING}</string>
<key>CFBundleIconFile</key>
<string>${MACOSX_BUNDLE_ICON_FILE}</string>
<key>CFBundleIdentifier</key>
<string>${MACOSX_BUNDLE_GUI_IDENTIFIER}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleLongVersionString</key>
<string>${MACOSX_BUNDLE_LONG_VERSION_STRING}</string>
<key>CFBundleName</key>
<string>${MACOSX_BUNDLE_BUNDLE_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>${MACOSX_BUNDLE_SHORT_VERSION_STRING}</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${MACOSX_BUNDLE_BUNDLE_VERSION}</string>
<key>CSResourcesFileMapped</key>
<true/>
<key>LSRequiresCarbon</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>${MACOSX_BUNDLE_COPYRIGHT}</string>
<key>NSHighResolutionCapable</key>
<true/>
</dict>
</plist>

168
iethxi/Main.ui

@ -1,168 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Main</class>
<widget class="QMainWindow" name="Main">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>562</width>
<height>488</height>
</rect>
</property>
<property name="windowTitle">
<string>Walleth</string>
</property>
<property name="dockNestingEnabled">
<bool>true</bool>
</property>
<property name="dockOptions">
<set>QMainWindow::AllowNestedDocks|QMainWindow::AllowTabbedDocks|QMainWindow::VerticalTabs</set>
</property>
<property name="sizeGripEnabled" stdset="0">
<bool>true</bool>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<layout class="QHBoxLayout" name="fullDisplay">
<item>
<widget class="QLabel" name="balance">
<property name="text">
<string>0 wei</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="peerCount">
<property name="text">
<string>0 peers</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="blockCount">
<property name="text">
<string>1 block</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>562</width>
<height>25</height>
</rect>
</property>
<widget class="QMenu" name="menu_File">
<property name="title">
<string>&amp;File</string>
</property>
<addaction name="quit"/>
</widget>
<widget class="QMenu" name="menu_Network">
<property name="title">
<string>&amp;Network</string>
</property>
<addaction name="upnp"/>
<addaction name="net"/>
<addaction name="connect"/>
</widget>
<widget class="QMenu" name="menu_Tools">
<property name="title">
<string>T&amp;ools</string>
</property>
<addaction name="mine"/>
<addaction name="create"/>
<addaction name="preview"/>
</widget>
<widget class="QMenu" name="menu_Help">
<property name="title">
<string>&amp;Help</string>
</property>
<addaction name="about"/>
</widget>
<addaction name="menu_File"/>
<addaction name="menu_Network"/>
<addaction name="menu_Tools"/>
<addaction name="menu_Help"/>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<action name="quit">
<property name="text">
<string>&amp;Quit</string>
</property>
</action>
<action name="upnp">
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>true</bool>
</property>
<property name="text">
<string>Use &amp;UPnP</string>
</property>
</action>
<action name="connect">
<property name="text">
<string>&amp;Connect to Peer...</string>
</property>
</action>
<action name="net">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>Enable &amp;Network</string>
</property>
</action>
<action name="mine">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>&amp;Mine</string>
</property>
</action>
<action name="create">
<property name="text">
<string>&amp;New Address</string>
</property>
</action>
<action name="about">
<property name="text">
<string>&amp;About...</string>
</property>
</action>
<action name="preview">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>&amp;Preview</string>
</property>
</action>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>

59
iethxi/MainWin.cpp

@ -1,59 +0,0 @@
#include <QtNetwork/QNetworkReply>
#include <QtQuick/QQuickView>
#include <QtQml/QQmlContext>
#include <QtQml/QQmlEngine>
#include <QtQml/QtQml>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QInputDialog>
#include <QtGui/QClipboard>
#include <QtCore/QtCore>
#include <libethcore/FileSystem.h>
#include <libethcore/Dagger.h>
#include <libevmcore/Instruction.h>
#include <libethereum/Client.h>
#include <libethereum/EthereumHost.h>
#include "BuildInfo.h"
#include "MainWin.h"
#include "ui_Main.h"
using namespace std;
using namespace eth;
Main::Main(QWidget *parent) :
QObject(parent)
{
/* qRegisterMetaType<eth::u256>("eth::u256");
qRegisterMetaType<eth::KeyPair>("eth::KeyPair");
qRegisterMetaType<eth::Secret>("eth::Secret");
qRegisterMetaType<eth::Address>("eth::Address");
qRegisterMetaType<QmlAccount*>("QmlAccount*");
qRegisterMetaType<QmlEthereum*>("QmlEthereum*");
qmlRegisterType<QmlEthereum>("org.ethereum", 1, 0, "Ethereum");
qmlRegisterType<QmlAccount>("org.ethereum", 1, 0, "Account");
qmlRegisterSingletonType<QmlU256Helper>("org.ethereum", 1, 0, "Balance", QmlEthereum::constructU256Helper);
qmlRegisterSingletonType<QmlKeyHelper>("org.ethereum", 1, 0, "Key", QmlEthereum::constructKeyHelper);
*/
/*
ui->librariesView->setModel(m_libraryMan);
ui->graphsView->setModel(m_graphMan);
*/
// QQmlContext* context = m_view->rootContext();
// context->setContextProperty("u256", new U256Helper(this));
}
Main::~Main()
{
}
// extra bits needed to link on VS
#ifdef _MSC_VER
// include moc file, ofuscated to hide from automoc
#include\
"moc_MainWin.cpp"
#endif

18
iethxi/MainWin.h

@ -1,18 +0,0 @@
#ifndef MAIN_H
#define MAIN_H
#include <QtQml/QQmlApplicationEngine>
class Main: public QObject
{
Q_OBJECT
public:
explicit Main(QWidget *parent = 0);
~Main();
private:
QQmlApplicationEngine* m_view;
};
#endif // MAIN_H

5
iethxi/Resources.qrc

@ -1,5 +0,0 @@
<RCC>
<qresource prefix="/">
<file>Simple.qml</file>
</qresource>
</RCC>

9
iethxi/Simple.qml

@ -1,9 +0,0 @@
import QtQuick.Controls 1.1
ApplicationWindow {
title: "My App"
Button {
text: "Push Me"
anchors.centerIn: parent
}
}

9
iethxi/main.cpp

@ -1,9 +0,0 @@
#include <QtQml/QQmlApplicationEngine>
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QQmlApplicationEngine app(QUrl("qrc:/Simple.qml"));
return a.exec();
}

8
libdevcore/All.h

@ -1,8 +0,0 @@
#pragma once
#include "Common.h"
#include "CommonData.h"
#include "CommonIO.h"
#include "FixedHash.h"
#include "Log.h"
#include "RLP.h"

41
libdevcore/CMakeLists.txt

@ -1,49 +1,42 @@
cmake_policy(SET CMP0015 NEW) cmake_policy(SET CMP0015 NEW)
# this policy was introduced in cmake 3.0
if (CMAKE_MAJOR_VERSION GREATER 1 AND CMAKE_MINOR_VERSION GREATER 7 AND CMAKE_PATCH_VERSION GREATER 11) # remove if, once 3.0 will be used on unix
cmake_policy(SET CMP0022 NEW) if (${CMAKE_MAJOR_VERSION} GREATER 2)
# old policy do not use MACOSX_RPATH
cmake_policy(SET CMP0042 OLD)
endif() endif()
set(CMAKE_AUTOMOC OFF)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB")
aux_source_directory(. SRC_LIST) aux_source_directory(. SRC_LIST)
include_directories(${Boost_INCLUDE_DIRS})
include_directories(..)
set(EXECUTABLE devcore) set(EXECUTABLE devcore)
file(GLOB HEADERS "*.h") file(GLOB HEADERS "*.h")
if(ETH_STATIC) if(ETH_STATIC)
add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS})
else() else()
add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS})
endif() endif()
include_directories(..) target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${Boost_CHRONO_LIBRARIES})
if("${TARGET_PLATFORM}" STREQUAL "w64") if (APPLE)
include_directories(/usr/x86_64-w64-mingw32/include/cryptopp)
target_link_libraries(${EXECUTABLE} boost_system-mt-s)
target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s)
target_link_libraries(${EXECUTABLE} iphlpapi)
target_link_libraries(${EXECUTABLE} ws2_32)
target_link_libraries(${EXECUTABLE} mswsock)
target_link_libraries(${EXECUTABLE} shlwapi)
elseif (APPLE)
# Latest mavericks boost libraries only come with -mt
target_link_libraries(${EXECUTABLE} boost_system-mt)
target_link_libraries(${EXECUTABLE} boost_filesystem-mt)
target_link_libraries(${EXECUTABLE} boost_thread-mt)
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
elseif (UNIX) elseif (UNIX)
find_package(Boost 1.53 REQUIRED COMPONENTS thread system)
target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY} ${Boost_SYSTEM_LIBRARY})
find_package(Threads REQUIRED)
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
else ()
target_link_libraries(${EXECUTABLE} boost_thread)
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT}) target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
endif () endif()
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

21
libdevcore/CommonData.cpp

@ -14,7 +14,7 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file Common.cpp /** @file CommonData.cpp
* @author Gav Wood <i@gavwood.com> * @author Gav Wood <i@gavwood.com>
* @date 2014 * @date 2014
*/ */
@ -23,7 +23,8 @@
#include <random> #include <random>
#include "Exceptions.h" #include "Exceptions.h"
#include <libdevcore/Log.h> #include "Log.h"
using namespace std; using namespace std;
using namespace dev; using namespace dev;
@ -88,13 +89,25 @@ bytes dev::fromHex(std::string const& _s)
{ {
ret.push_back(fromHex(_s[s++])); ret.push_back(fromHex(_s[s++]));
} }
catch (...){ ret.push_back(0); cwarn << boost::current_exception_diagnostic_information(); } catch (...)
{
ret.push_back(0);
// msvc does not support it
#ifndef BOOST_NO_EXCEPTIONS
cwarn << boost::current_exception_diagnostic_information();
#endif
}
for (unsigned i = s; i < _s.size(); i += 2) for (unsigned i = s; i < _s.size(); i += 2)
try try
{ {
ret.push_back((byte)(fromHex(_s[i]) * 16 + fromHex(_s[i + 1]))); ret.push_back((byte)(fromHex(_s[i]) * 16 + fromHex(_s[i + 1])));
} }
catch (...){ ret.push_back(0); cwarn << boost::current_exception_diagnostic_information(); } catch (...){
ret.push_back(0);
#ifndef BOOST_NO_EXCEPTIONS
cwarn << boost::current_exception_diagnostic_information();
#endif
}
return ret; return ret;
} }

2
libdevcore/CommonData.h

@ -14,7 +14,7 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file Common.h /** @file CommonData.h
* @author Gav Wood <i@gavwood.com> * @author Gav Wood <i@gavwood.com>
* @date 2014 * @date 2014
* *

7
libdevcore/CommonJS.cpp

@ -112,13 +112,8 @@ std::string fromRaw(h256 _n, unsigned* _inc)
return ""; return "";
} }
Address fromString(std::string _sn) Address fromString(std::string const& _sn)
{ {
if (_sn.size() > 32)
_sn.resize(32);
h256 n;
memcpy(n.data(), _sn.data(), _sn.size());
memset(n.data() + _sn.size(), 0, 32 - _sn.size());
if (_sn.size() == 40) if (_sn.size() == 40)
return Address(fromHex(_sn)); return Address(fromHex(_sn));
else else

2
libdevcore/CommonJS.h

@ -52,7 +52,7 @@ bytes unpadded(bytes _s);
std::string unpadded(std::string _s); std::string unpadded(std::string _s);
std::string prettyU256(u256 _n); std::string prettyU256(u256 _n);
std::string fromRaw(h256 _n, unsigned* _inc = nullptr); std::string fromRaw(h256 _n, unsigned* _inc = nullptr);
Address fromString(std::string _a); Address fromString(std::string const& _a);
template <unsigned N> FixedHash<N> jsToFixed(std::string const& _s) template <unsigned N> FixedHash<N> jsToFixed(std::string const& _s)
{ {

8
libdevcore/RLP.h

@ -28,10 +28,10 @@
#include <exception> #include <exception>
#include <iostream> #include <iostream>
#include <iomanip> #include <iomanip>
#include <libdevcore/vector_ref.h> #include "vector_ref.h"
#include <libdevcore/Common.h> #include "Common.h"
#include <libdevcore/Exceptions.h> #include "Exceptions.h"
#include <libdevcore/FixedHash.h> #include "FixedHash.h"
namespace dev namespace dev
{ {

2
libdevcore/RangeMask.h

@ -14,7 +14,7 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file EthereumHost.h /** @file RangeMask.h
* @author Gav Wood <i@gavwood.com> * @author Gav Wood <i@gavwood.com>
* @date 2014 * @date 2014
*/ */

13
libdevcore/_libdevcore.cpp

@ -1,13 +0,0 @@
#ifdef _MSC_VER
#include "All.h"
#include "Common.cpp"
#include "CommonData.cpp"
#include "CommonIO.cpp"
#include "CommonJS.h"
#include "FixedHash.cpp"
#include "Guards.cpp"
#include "Log.cpp"
#include "RangeMask.cpp"
#include "RLP.cpp"
#include "Worker.cpp"
#endif

1
libdevcore/vector_ref.h

@ -40,6 +40,7 @@ public:
vector_ref<_T> cropped(size_t _begin, size_t _count = ~size_t(0)) const { if (m_data && _begin + std::max(size_t(0), _count) <= m_count) return vector_ref<_T>(m_data + _begin, _count == ~size_t(0) ? m_count - _begin : _count); else return vector_ref<_T>(); } vector_ref<_T> cropped(size_t _begin, size_t _count = ~size_t(0)) const { if (m_data && _begin + std::max(size_t(0), _count) <= m_count) return vector_ref<_T>(m_data + _begin, _count == ~size_t(0) ? m_count - _begin : _count); else return vector_ref<_T>(); }
void retarget(_T const* _d, size_t _s) { m_data = _d; m_count = _s; } void retarget(_T const* _d, size_t _s) { m_data = _d; m_count = _s; }
void retarget(std::vector<_T> const& _t) { m_data = _t.data(); m_count = _t.size(); } void retarget(std::vector<_T> const& _t) { m_data = _t.data(); m_count = _t.size(); }
void copyTo(vector_ref<typename std::remove_const<_T>::type> _t) const { memcpy(_t.data(), m_data, std::min(_t.size(), m_count) * sizeof(_T)); }
_T* begin() { return m_data; } _T* begin() { return m_data; }
_T* end() { return m_data + m_count; } _T* end() { return m_data + m_count; }

8
libdevcrypto/All.h

@ -1,8 +0,0 @@
#pragma once
#include "Common.h"
#include "AES.h"
#include "ECDHE.h"
#include "FileSystem.h"
#include "SHA3.h"
#include "TrieDB.h"

51
libdevcrypto/CMakeLists.txt

@ -1,7 +1,19 @@
cmake_policy(SET CMP0015 NEW) cmake_policy(SET CMP0015 NEW)
# this policy was introduced in cmake 3.0
# remove if, once 3.0 will be used on unix
if (${CMAKE_MAJOR_VERSION} GREATER 2)
# old policy do not use MACOSX_RPATH
cmake_policy(SET CMP0042 OLD)
endif()
set(CMAKE_AUTOMOC OFF)
aux_source_directory(. SRC_LIST) aux_source_directory(. SRC_LIST)
include_directories(${Boost_INCLUDE_DIRS})
include_directories(${CRYPTOPP_INCLUDE_DIRS})
include_directories(${LEVELDB_INCLUDE_DIRS})
include_directories(..)
set(EXECUTABLE devcrypto) set(EXECUTABLE devcrypto)
file(GLOB HEADERS "*.h") file(GLOB HEADERS "*.h")
@ -11,43 +23,10 @@ else()
add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS})
endif() endif()
include_directories(..) target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${LEVELDB_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LIBRARIES})
target_link_libraries(${EXECUTABLE} devcore) target_link_libraries(${EXECUTABLE} devcore)
target_link_libraries(${EXECUTABLE} secp256k1)
target_link_libraries(${EXECUTABLE} gmp)
target_link_libraries(${EXECUTABLE} ${LEVELDB_LS})
target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS})
if("${TARGET_PLATFORM}" STREQUAL "w64")
target_link_libraries(${EXECUTABLE} boost_system-mt-s)
target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s)
target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s)
target_link_libraries(${EXECUTABLE} iphlpapi)
target_link_libraries(${EXECUTABLE} ws2_32)
target_link_libraries(${EXECUTABLE} mswsock)
target_link_libraries(${EXECUTABLE} shlwapi)
elseif (APPLE)
# Latest mavericks boost libraries only come with -mt
target_link_libraries(${EXECUTABLE} boost_system-mt)
target_link_libraries(${EXECUTABLE} boost_filesystem-mt)
target_link_libraries(${EXECUTABLE} boost_thread-mt)
find_package(Threads REQUIRED)
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
elseif (UNIX)
find_package(Boost 1.53 REQUIRED COMPONENTS filesystem)
target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY})
target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY})
target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY})
target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY})
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
else ()
target_link_libraries(${EXECUTABLE} boost_system)
target_link_libraries(${EXECUTABLE} boost_filesystem)
target_link_libraries(${EXECUTABLE} boost_thread)
find_package(Threads REQUIRED)
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
endif ()
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

5
libdevcrypto/Common.h

@ -45,6 +45,11 @@ using Signature = h520;
struct SignatureStruct struct SignatureStruct
{ {
SignatureStruct() {}
SignatureStruct(Signature const& _s) { *(h520*)this = _s; }
SignatureStruct(h256 _r, h256 _s, byte _v): r(_r), s(_s), v(_v) {}
operator Signature() const { return *(h520 const*)this; }
/// @returns true if r,s,v values are valid, otherwise false /// @returns true if r,s,v values are valid, otherwise false
bool isValid(); bool isValid();

6
libdevcrypto/CryptoPP.cpp

@ -52,6 +52,12 @@ void Secp256k1::decrypt(Secret const& _k, bytes& io_text)
{ {
CryptoPP::ECIES<CryptoPP::ECP>::Decryptor d; CryptoPP::ECIES<CryptoPP::ECP>::Decryptor d;
initializeDLScheme(_k, d); initializeDLScheme(_k, d);
if (!io_text.size())
{
io_text.resize(1);
io_text[0] = 0;
}
size_t clen = io_text.size(); size_t clen = io_text.size();
bytes plain; bytes plain;

26
libdevcrypto/CryptoPP.h

@ -34,19 +34,19 @@
#pragma GCC diagnostic ignored "-Wunused-variable" #pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor" #pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
#pragma GCC diagnostic ignored "-Wextra" #pragma GCC diagnostic ignored "-Wextra"
#include <sha.h> #include <cryptopp/sha.h>
#include <sha3.h> #include <cryptopp/sha3.h>
#include <ripemd.h> #include <cryptopp/ripemd.h>
#include <aes.h> #include <cryptopp/aes.h>
#include <pwdbased.h> #include <cryptopp/pwdbased.h>
#include <modes.h> #include <cryptopp/modes.h>
#include <filters.h> #include <cryptopp/filters.h>
#include <eccrypto.h> #include <cryptopp/eccrypto.h>
#include <ecp.h> #include <cryptopp/ecp.h>
#include <files.h> #include <cryptopp/files.h>
#include <osrng.h> #include <cryptopp/osrng.h>
#include <oids.h> #include <cryptopp/oids.h>
#include <dsa.h> #include <cryptopp/dsa.h>
#pragma warning(pop) #pragma warning(pop)
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
#include "SHA3.h" #include "SHA3.h"

2
libdevcrypto/OverlayDB.cpp

@ -14,7 +14,7 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file TrieDB.cpp /** @file OverlayDB.cpp
* @author Gav Wood <i@gavwood.com> * @author Gav Wood <i@gavwood.com>
* @date 2014 * @date 2014
*/ */

2
libdevcrypto/OverlayDB.h

@ -14,7 +14,7 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file MemoryDB.h /** @file OverlayDB.h
* @author Gav Wood <i@gavwood.com> * @author Gav Wood <i@gavwood.com>
* @date 2014 * @date 2014
*/ */

2
libdevcrypto/SHA3.cpp

@ -30,7 +30,7 @@ namespace dev
{ {
h256 EmptySHA3 = sha3(bytesConstRef()); h256 EmptySHA3 = sha3(bytesConstRef());
h256 EmptyListSHA3 = sha3(RLPEmptyList); h256 EmptyListSHA3 = sha3(rlpList());
std::string sha3(std::string const& _input, bool _hex) std::string sha3(std::string const& _input, bool _hex)
{ {

2
libdevcrypto/SHA3.h

@ -14,7 +14,7 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file FixedHash.h /** @file SHA3.h
* @author Gav Wood <i@gavwood.com> * @author Gav Wood <i@gavwood.com>
* @date 2014 * @date 2014
* *

4
libdevcrypto/TrieDB.cpp

@ -24,9 +24,5 @@
using namespace std; using namespace std;
using namespace dev; using namespace dev;
#if !ETH_LANGUAGES
h256 const dev::c_shaNull = sha3(rlp("")); h256 const dev::c_shaNull = sha3(rlp(""));
h256 const dev::EmptyTrie = c_shaNull; h256 const dev::EmptyTrie = c_shaNull;
#endif

7
libethcore/All.h

@ -1,7 +0,0 @@
#pragma once
#include "BlockInfo.h"
#include "CommonEth.h"
#include "ProofOfWork.h"
#include "Exceptions.h"

37
libethcore/BlockInfo.cpp

@ -19,8 +19,6 @@
* @date 2014 * @date 2014
*/ */
#if !ETH_LANGUAGES
#include <libdevcore/Common.h> #include <libdevcore/Common.h>
#include <libdevcore/RLP.h> #include <libdevcore/RLP.h>
#include <libdevcrypto/TrieDB.h> #include <libdevcrypto/TrieDB.h>
@ -42,6 +40,25 @@ BlockInfo::BlockInfo(bytesConstRef _block, bool _checkNonce)
populate(_block, _checkNonce); populate(_block, _checkNonce);
} }
void BlockInfo::setEmpty()
{
parentHash = h256();
sha3Uncles = EmptyListSHA3;
coinbaseAddress = Address();
stateRoot = EmptyTrie;
transactionsRoot = EmptyTrie;
receiptsRoot = EmptyTrie;
logBloom = LogBloom();
difficulty = 0;
number = 0;
gasLimit = 0;
gasUsed = 0;
timestamp = 0;
extraData.clear();
nonce = h256();
hash = headerHash(WithNonce);
}
BlockInfo BlockInfo::fromHeader(bytesConstRef _block) BlockInfo BlockInfo::fromHeader(bytesConstRef _block)
{ {
BlockInfo ret; BlockInfo ret;
@ -49,19 +66,19 @@ BlockInfo BlockInfo::fromHeader(bytesConstRef _block)
return ret; return ret;
} }
h256 BlockInfo::headerHashWithoutNonce() const h256 BlockInfo::headerHash(IncludeNonce _n) const
{ {
RLPStream s; RLPStream s;
streamRLP(s, false); streamRLP(s, _n);
return sha3(s.out()); return sha3(s.out());
} }
void BlockInfo::streamRLP(RLPStream& _s, bool _nonce) const void BlockInfo::streamRLP(RLPStream& _s, IncludeNonce _n) const
{ {
_s.appendList(_nonce ? 14 : 13) _s.appendList(_n == WithNonce ? 14 : 13)
<< parentHash << sha3Uncles << coinbaseAddress << stateRoot << transactionsRoot << receiptsRoot << logBloom << parentHash << sha3Uncles << coinbaseAddress << stateRoot << transactionsRoot << receiptsRoot << logBloom
<< difficulty << number << gasLimit << gasUsed << timestamp << extraData; << difficulty << number << gasLimit << gasUsed << timestamp << extraData;
if (_nonce) if (_n == WithNonce)
_s << nonce; _s << nonce;
} }
@ -100,8 +117,8 @@ void BlockInfo::populateFromHeader(RLP const& _header, bool _checkNonce)
} }
// check it hashes according to proof of work or that it's the genesis block. // check it hashes according to proof of work or that it's the genesis block.
if (_checkNonce && parentHash && !ProofOfWork::verify(headerHashWithoutNonce(), nonce, difficulty)) if (_checkNonce && parentHash && !ProofOfWork::verify(headerHash(WithoutNonce), nonce, difficulty))
BOOST_THROW_EXCEPTION(InvalidBlockNonce(headerHashWithoutNonce(), nonce, difficulty)); BOOST_THROW_EXCEPTION(InvalidBlockNonce(headerHash(WithoutNonce), nonce, difficulty));
if (gasUsed > gasLimit) if (gasUsed > gasLimit)
BOOST_THROW_EXCEPTION(TooMuchGasUsed()); BOOST_THROW_EXCEPTION(TooMuchGasUsed());
@ -197,5 +214,3 @@ void BlockInfo::verifyParent(BlockInfo const& _parent) const
BOOST_THROW_EXCEPTION(InvalidNumber()); BOOST_THROW_EXCEPTION(InvalidNumber());
} }
} }
#endif

18
libethcore/BlockInfo.h

@ -32,6 +32,12 @@ namespace eth
extern u256 c_genesisDifficulty; extern u256 c_genesisDifficulty;
enum IncludeNonce
{
WithoutNonce = 0,
WithNonce = 1
};
/** @brief Encapsulation of a block header. /** @brief Encapsulation of a block header.
* Class to contain all of a block header's data. It is able to parse a block header and populate * Class to contain all of a block header's data. It is able to parse a block header and populate
* from some given RLP block serialisation with the static fromHeader(), through the method * from some given RLP block serialisation with the static fromHeader(), through the method
@ -48,7 +54,7 @@ extern u256 c_genesisDifficulty;
* *
* The difficulty and gas-limit derivations may be calculated with the calculateDifficulty() * The difficulty and gas-limit derivations may be calculated with the calculateDifficulty()
* and calculateGasLimit() and the object serialised to RLP with streamRLP. To determine the * and calculateGasLimit() and the object serialised to RLP with streamRLP. To determine the
* header hash without the nonce (for mining), the method headerHashWithoutNonce() is provided. * header hash without the nonce (for mining), the method headerHash(WithoutNonce) is provided.
* *
* The default constructor creates an empty object, which can be tested against with the boolean * The default constructor creates an empty object, which can be tested against with the boolean
* conversion operator. * conversion operator.
@ -63,7 +69,7 @@ public:
h256 stateRoot; h256 stateRoot;
h256 transactionsRoot; h256 transactionsRoot;
h256 receiptsRoot; h256 receiptsRoot;
h512 logBloom; // TODO LogBloom - get include LogBloom logBloom;
u256 difficulty; u256 difficulty;
u256 number; u256 number;
u256 gasLimit; u256 gasLimit;
@ -102,6 +108,8 @@ public:
} }
bool operator!=(BlockInfo const& _cmp) const { return !operator==(_cmp); } bool operator!=(BlockInfo const& _cmp) const { return !operator==(_cmp); }
void setEmpty();
void populateFromHeader(RLP const& _header, bool _checkNonce = true); void populateFromHeader(RLP const& _header, bool _checkNonce = true);
void populate(bytesConstRef _block, bool _checkNonce = true); void populate(bytesConstRef _block, bool _checkNonce = true);
void populate(bytes const& _block, bool _checkNonce = true) { populate(&_block, _checkNonce); } void populate(bytes const& _block, bool _checkNonce = true) { populate(&_block, _checkNonce); }
@ -112,9 +120,9 @@ public:
u256 calculateDifficulty(BlockInfo const& _parent) const; u256 calculateDifficulty(BlockInfo const& _parent) const;
u256 calculateGasLimit(BlockInfo const& _parent) const; u256 calculateGasLimit(BlockInfo const& _parent) const;
/// No-nonce sha3 of the header only. /// sha3 of the header only.
h256 headerHashWithoutNonce() const; h256 headerHash(IncludeNonce _n) const;
void streamRLP(RLPStream& _s, bool _nonce) const; void streamRLP(RLPStream& _s, IncludeNonce _n) const;
}; };
inline std::ostream& operator<<(std::ostream& _out, BlockInfo const& _bi) inline std::ostream& operator<<(std::ostream& _out, BlockInfo const& _bi)

47
libethcore/CMakeLists.txt

@ -1,54 +1,29 @@
cmake_policy(SET CMP0015 NEW) cmake_policy(SET CMP0015 NEW)
# this policy was introduced in cmake 3.0
# remove if, once 3.0 will be used on unix
if (${CMAKE_MAJOR_VERSION} GREATER 2)
# old policy do not use MACOSX_RPATH
cmake_policy(SET CMP0042 OLD)
endif()
set(CMAKE_AUTOMOC OFF)
aux_source_directory(. SRC_LIST) aux_source_directory(. SRC_LIST)
include_directories(${Boost_INCLUDE_DIRS})
include_directories(..)
set(EXECUTABLE ethcore) set(EXECUTABLE ethcore)
file(GLOB HEADERS "*.h") file(GLOB HEADERS "*.h")
if(ETH_STATIC) if(ETH_STATIC)
add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS})
else() else()
add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS})
endif() endif()
include_directories(..)
target_link_libraries(${EXECUTABLE} devcrypto) target_link_libraries(${EXECUTABLE} devcrypto)
target_link_libraries(${EXECUTABLE} devcore) target_link_libraries(${EXECUTABLE} devcore)
target_link_libraries(${EXECUTABLE} secp256k1)
target_link_libraries(${EXECUTABLE} gmp)
target_link_libraries(${EXECUTABLE} ${LEVELDB_LS})
target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS})
if("${TARGET_PLATFORM}" STREQUAL "w64")
target_link_libraries(${EXECUTABLE} boost_system-mt-s)
target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s)
target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s)
target_link_libraries(${EXECUTABLE} iphlpapi)
target_link_libraries(${EXECUTABLE} ws2_32)
target_link_libraries(${EXECUTABLE} mswsock)
target_link_libraries(${EXECUTABLE} shlwapi)
elseif (APPLE)
# Latest mavericks boost libraries only come with -mt
target_link_libraries(${EXECUTABLE} boost_system-mt)
target_link_libraries(${EXECUTABLE} boost_filesystem-mt)
target_link_libraries(${EXECUTABLE} boost_thread-mt)
find_package(Threads REQUIRED)
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
elseif (UNIX)
find_package(Boost 1.53 REQUIRED COMPONENTS filesystem)
target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY})
target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY})
target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY})
target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY})
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
else ()
target_link_libraries(${EXECUTABLE} boost_system)
target_link_libraries(${EXECUTABLE} boost_filesystem)
target_link_libraries(${EXECUTABLE} boost_thread)
find_package(Threads REQUIRED)
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
endif ()
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

3
libethcore/CommonEth.cpp

@ -21,7 +21,6 @@
#include "CommonEth.h" #include "CommonEth.h"
#include <random> #include <random>
#include <secp256k1/secp256k1.h>
#include <libdevcrypto/SHA3.h> #include <libdevcrypto/SHA3.h>
#include "Exceptions.h" #include "Exceptions.h"
using namespace std; using namespace std;
@ -33,7 +32,7 @@ namespace dev
namespace eth namespace eth
{ {
const unsigned c_protocolVersion = 46; const unsigned c_protocolVersion = 49;
const unsigned c_databaseVersion = 5; const unsigned c_databaseVersion = 5;
static const vector<pair<u256, string>> g_units = static const vector<pair<u256, string>> g_units =

3
libethcore/CommonEth.h

@ -44,6 +44,9 @@ std::string formatBalance(u256 _b);
/// Get information concerning the currency denominations. /// Get information concerning the currency denominations.
std::vector<std::pair<u256, std::string>> const& units(); std::vector<std::pair<u256, std::string>> const& units();
/// The log bloom's size (512 bit).
using LogBloom = h512;
// The various denominations; here for ease of use where needed within code. // The various denominations; here for ease of use where needed within code.
static const u256 Uether = ((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000; static const u256 Uether = ((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000;
static const u256 Vether = ((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000; static const u256 Vether = ((((u256(1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000000) * 1000000;

3
libethcore/ProofOfWork.cpp

@ -19,8 +19,6 @@
* @date 2014 * @date 2014
*/ */
#if !ETH_LANGUAGES
#include <boost/detail/endian.hpp> #include <boost/detail/endian.hpp>
#include <chrono> #include <chrono>
#include <array> #include <array>
@ -107,4 +105,3 @@ h256 DaggerEvaluator::eval(h256 const& _root, h256 const& _nonce)
} }
} }
#endif

7
libethcore/_libethcore.cpp

@ -1,7 +0,0 @@
#ifdef _MSC_VER
#include "All.h"
#include "BlockInfo.cpp"
#include "CommonEth.cpp"
#include "ProofOfWork.cpp"
#include "Exceptions.cpp"
#endif

5
libethereum/BlockChain.cpp

@ -145,7 +145,7 @@ void BlockChain::open(std::string _path, bool _killExisting)
if (!details(m_genesisHash)) if (!details(m_genesisHash))
{ {
// Insert details of genesis block. // Insert details of genesis block.
m_details[m_genesisHash] = BlockDetails(0, c_genesisDifficulty, h256(), {}, h256()); m_details[m_genesisHash] = BlockDetails(0, c_genesisDifficulty, h256(), {});
auto r = m_details[m_genesisHash].rlp(); auto r = m_details[m_genesisHash].rlp();
m_extrasDB->Put(m_writeOptions, ldb::Slice((char const*)&m_genesisHash, 32), (ldb::Slice)dev::ref(r)); m_extrasDB->Put(m_writeOptions, ldb::Slice((char const*)&m_genesisHash, 32), (ldb::Slice)dev::ref(r));
} }
@ -303,7 +303,6 @@ h256s BlockChain::import(bytes const& _block, OverlayDB const& _db)
// Get total difficulty increase and update state, checking it. // Get total difficulty increase and update state, checking it.
State s(bi.coinbaseAddress, _db); State s(bi.coinbaseAddress, _db);
auto tdIncrease = s.enactOn(&_block, bi, *this); auto tdIncrease = s.enactOn(&_block, bi, *this);
auto b = s.oldBloom();
BlockLogBlooms blb; BlockLogBlooms blb;
BlockReceipts br; BlockReceipts br;
for (unsigned i = 0; i < s.pending().size(); ++i) for (unsigned i = 0; i < s.pending().size(); ++i)
@ -320,7 +319,7 @@ h256s BlockChain::import(bytes const& _block, OverlayDB const& _db)
// All ok - insert into DB // All ok - insert into DB
{ {
WriteGuard l(x_details); WriteGuard l(x_details);
m_details[newHash] = BlockDetails((unsigned)pd.number + 1, td, bi.parentHash, {}, b); m_details[newHash] = BlockDetails((unsigned)pd.number + 1, td, bi.parentHash, {});
m_details[bi.parentHash].children.push_back(newHash); m_details[bi.parentHash].children.push_back(newHash);
} }
{ {

3
libethereum/BlockDetails.cpp

@ -32,10 +32,9 @@ BlockDetails::BlockDetails(RLP const& _r)
totalDifficulty = _r[1].toInt<u256>(); totalDifficulty = _r[1].toInt<u256>();
parent = _r[2].toHash<h256>(); parent = _r[2].toHash<h256>();
children = _r[3].toVector<h256>(); children = _r[3].toVector<h256>();
bloom = _r[4].toHash<h256>();
} }
bytes BlockDetails::rlp() const bytes BlockDetails::rlp() const
{ {
return rlpList(number, totalDifficulty, parent, children, bloom); return rlpList(number, totalDifficulty, parent, children);
} }

4
libethereum/BlockDetails.h

@ -28,7 +28,6 @@
#include <libdevcore/Log.h> #include <libdevcore/Log.h>
#include <libdevcore/RLP.h> #include <libdevcore/RLP.h>
#include "Manifest.h"
#include "TransactionReceipt.h" #include "TransactionReceipt.h"
namespace ldb = leveldb; namespace ldb = leveldb;
@ -40,7 +39,7 @@ namespace eth
struct BlockDetails struct BlockDetails
{ {
BlockDetails(): number(0), totalDifficulty(0) {} BlockDetails(): number(0), totalDifficulty(0) {}
BlockDetails(unsigned _n, u256 _tD, h256 _p, h256s _c, h256 _bloom): number(_n), totalDifficulty(_tD), parent(_p), children(_c), bloom(_bloom) {} BlockDetails(unsigned _n, u256 _tD, h256 _p, h256s _c): number(_n), totalDifficulty(_tD), parent(_p), children(_c) {}
BlockDetails(RLP const& _r); BlockDetails(RLP const& _r);
bytes rlp() const; bytes rlp() const;
@ -51,7 +50,6 @@ struct BlockDetails
u256 totalDifficulty; u256 totalDifficulty;
h256 parent; h256 parent;
h256s children; h256s children;
h256 bloom;
}; };
struct BlockLogBlooms struct BlockLogBlooms

55
libethereum/CMakeLists.txt

@ -1,19 +1,31 @@
cmake_policy(SET CMP0015 NEW) cmake_policy(SET CMP0015 NEW)
# this policy was introduced in cmake 3.0
# remove if, once 3.0 will be used on unix
if (${CMAKE_MAJOR_VERSION} GREATER 2)
# old policy do not use MACOSX_RPATH
cmake_policy(SET CMP0042 OLD)
endif()
set(CMAKE_AUTOMOC OFF)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTATICLIB")
aux_source_directory(. SRC_LIST) aux_source_directory(. SRC_LIST)
include_directories(${LEVELDB_INCLUDE_DIRS})
include_directories(..)
set(EXECUTABLE ethereum) set(EXECUTABLE ethereum)
file(GLOB HEADERS "*.h") file(GLOB HEADERS "*.h")
if(ETH_STATIC)
if (ETH_STATIC)
add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS}) add_library(${EXECUTABLE} STATIC ${SRC_LIST} ${HEADERS})
else() else()
add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS}) add_library(${EXECUTABLE} SHARED ${SRC_LIST} ${HEADERS})
endif() endif()
include_directories(..) target_link_libraries(${EXECUTABLE} ${LEVELDB_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${Boost_REGEX_LIBRARIES})
target_link_libraries(${EXECUTABLE} evm) target_link_libraries(${EXECUTABLE} evm)
target_link_libraries(${EXECUTABLE} lll) target_link_libraries(${EXECUTABLE} lll)
@ -22,45 +34,6 @@ target_link_libraries(${EXECUTABLE} p2p)
target_link_libraries(${EXECUTABLE} devcrypto) target_link_libraries(${EXECUTABLE} devcrypto)
target_link_libraries(${EXECUTABLE} ethcore) target_link_libraries(${EXECUTABLE} ethcore)
target_link_libraries(${EXECUTABLE} secp256k1) target_link_libraries(${EXECUTABLE} secp256k1)
if(MINIUPNPC_LS)
target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS})
endif()
target_link_libraries(${EXECUTABLE} ${LEVELDB_LS})
target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LS})
target_link_libraries(${EXECUTABLE} gmp)
if("${TARGET_PLATFORM}" STREQUAL "w64")
target_link_libraries(${EXECUTABLE} boost_system-mt-s)
target_link_libraries(${EXECUTABLE} boost_regex-mt-s)
target_link_libraries(${EXECUTABLE} boost_filesystem-mt-s)
target_link_libraries(${EXECUTABLE} boost_thread_win32-mt-s)
target_link_libraries(${EXECUTABLE} iphlpapi)
target_link_libraries(${EXECUTABLE} ws2_32)
target_link_libraries(${EXECUTABLE} mswsock)
target_link_libraries(${EXECUTABLE} shlwapi)
elseif (APPLE)
# Latest mavericks boost libraries only come with -mt
target_link_libraries(${EXECUTABLE} boost_system-mt)
target_link_libraries(${EXECUTABLE} boost_regex-mt)
target_link_libraries(${EXECUTABLE} boost_filesystem-mt)
target_link_libraries(${EXECUTABLE} boost_thread-mt)
find_package(Threads REQUIRED)
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
elseif (UNIX)
target_link_libraries(${EXECUTABLE} ${Boost_SYSTEM_LIBRARY})
target_link_libraries(${EXECUTABLE} ${Boost_REGEX_LIBRARY})
target_link_libraries(${EXECUTABLE} ${Boost_FILESYSTEM_LIBRARY})
target_link_libraries(${EXECUTABLE} ${Boost_THREAD_LIBRARY})
target_link_libraries(${EXECUTABLE} ${Boost_DATE_TIME_LIBRARY})
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
else ()
target_link_libraries(${EXECUTABLE} boost_system)
target_link_libraries(${EXECUTABLE} boost_regex)
target_link_libraries(${EXECUTABLE} boost_filesystem)
target_link_libraries(${EXECUTABLE} boost_thread)
find_package(Threads REQUIRED)
target_link_libraries(${EXECUTABLE} ${CMAKE_THREAD_LIBS_INIT})
endif ()
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

101
libethereum/CachedAddressState.cpp

@ -0,0 +1,101 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file CachedAddressState.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "CachedAddressState.h"
#include <libdevcrypto/Common.h>
#include <libdevcrypto/TrieDB.h>
#include "Account.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
bool CachedAddressState::exists() const
{
return (m_r && (!m_s || m_s->isAlive())) || (m_s && m_s->isAlive());
}
u256 CachedAddressState::balance() const
{
return m_r ? m_s ? m_s->balance() : m_r[1].toInt<u256>() : 0;
}
u256 CachedAddressState::nonce() const
{
return m_r ? m_s ? m_s->nonce() : m_r[0].toInt<u256>() : 0;
}
bytes CachedAddressState::code() const
{
if (m_s && m_s->codeCacheValid())
return m_s->code();
h256 h = m_r ? m_s ? m_s->codeHash() : m_r[3].toHash<h256>() : EmptySHA3;
return h == EmptySHA3 ? bytes() : asBytes(m_o->lookup(h));
}
std::map<u256, u256> CachedAddressState::storage() const
{
std::map<u256, u256> ret;
if (m_r)
{
TrieDB<h256, OverlayDB> memdb(const_cast<OverlayDB*>(m_o), m_r[2].toHash<h256>()); // promise we won't alter the overlay! :)
for (auto const& j: memdb)
ret[j.first] = RLP(j.second).toInt<u256>();
}
if (m_s)
for (auto const& j: m_s->storageOverlay())
if ((!ret.count(j.first) && j.second) || (ret.count(j.first) && ret.at(j.first) != j.second))
ret[j.first] = j.second;
return ret;
}
AccountDiff CachedAddressState::diff(CachedAddressState const& _c)
{
AccountDiff ret;
ret.exist = Diff<bool>(exists(), _c.exists());
ret.balance = Diff<u256>(balance(), _c.balance());
ret.nonce = Diff<u256>(nonce(), _c.nonce());
ret.code = Diff<bytes>(code(), _c.code());
auto st = storage();
auto cst = _c.storage();
auto it = st.begin();
auto cit = cst.begin();
while (it != st.end() || cit != cst.end())
{
if (it != st.end() && cit != cst.end() && it->first == cit->first && (it->second || cit->second) && (it->second != cit->second))
ret.storage[it->first] = Diff<u256>(it->second, cit->second);
else if (it != st.end() && (cit == cst.end() || it->first < cit->first) && it->second)
ret.storage[it->first] = Diff<u256>(it->second, 0);
else if (cit != cst.end() && (it == st.end() || it->first > cit->first) && cit->second)
ret.storage[cit->first] = Diff<u256>(0, cit->second);
if (it == st.end())
++cit;
else if (cit == cst.end())
++it;
else if (it->first < cit->first)
++it;
else if (it->first > cit->first)
++cit;
else
++it, ++cit;
}
return ret;
}

60
libethereum/CachedAddressState.h

@ -0,0 +1,60 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file CachedAddressState.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
#include <string>
#include <libdevcore/Common.h>
#include <libdevcore/RLP.h>
#include "AccountDiff.h"
namespace dev
{
class OverlayDB;
namespace eth
{
class Account;
class CachedAddressState
{
public:
CachedAddressState(std::string const& _rlp, Account const* _s, OverlayDB const* _o): m_rS(_rlp), m_r(m_rS), m_s(_s), m_o(_o) {}
bool exists() const;
u256 balance() const;
u256 nonce() const;
bytes code() const;
std::map<u256, u256> storage() const;
AccountDiff diff(CachedAddressState const& _c);
private:
std::string m_rS;
RLP m_r;
Account const* m_s;
OverlayDB const* m_o;
};
}
}

2
libethereum/Client.cpp

@ -217,7 +217,7 @@ void Client::noteChanged(h256Set const& _filters)
for (auto& i: m_watches) for (auto& i: m_watches)
if (_filters.count(i.second.id)) if (_filters.count(i.second.id))
{ {
cwatch << "!!!" << i.first << i.second.id; // cwatch << "!!!" << i.first << i.second.id;
i.second.changes++; i.second.changes++;
} }
} }

5
libethereum/Client.h

@ -36,8 +36,7 @@
#include "TransactionQueue.h" #include "TransactionQueue.h"
#include "State.h" #include "State.h"
#include "CommonNet.h" #include "CommonNet.h"
#include "PastMessage.h" #include "LogFilter.h"
#include "MessageFilter.h"
#include "Miner.h" #include "Miner.h"
#include "Interface.h" #include "Interface.h"
@ -79,8 +78,6 @@ static const int GenesisBlock = INT_MIN;
struct InstalledFilter struct InstalledFilter
{ {
// InstalledFilter(MessageFilter const& _f): filter(_f) {}
// MessageFilter filter;
InstalledFilter(LogFilter const& _f): filter(_f) {} InstalledFilter(LogFilter const& _f): filter(_f) {}
LogFilter filter; LogFilter filter;

2
libethereum/CommonNet.cpp

@ -14,7 +14,7 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file PeerNetwork.cpp /** @file CommonNet.cpp
* @author Gav Wood <i@gavwood.com> * @author Gav Wood <i@gavwood.com>
* @date 2014 * @date 2014
*/ */

2
libethereum/CommonNet.h

@ -14,7 +14,7 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** @file PeerNetwork.h /** @file CommonNet.h
* @author Gav Wood <i@gavwood.com> * @author Gav Wood <i@gavwood.com>
* @date 2014 * @date 2014
* *

171
libethereum/Executive.cpp

@ -1,16 +1,13 @@
/* /*
This file is part of cpp-ethereum. This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful, cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -19,59 +16,31 @@
* @date 2014 * @date 2014
*/ */
#include "Executive.h"
#include <boost/timer.hpp> #include <boost/timer.hpp>
#include <libdevcore/CommonIO.h> #include <libdevcore/CommonIO.h>
#include <libevm/VMFactory.h>
#include <libevm/VM.h> #include <libevm/VM.h>
#include "Interface.h" #include "Interface.h"
#include "Executive.h"
#include "State.h" #include "State.h"
#include "ExtVM.h" #include "ExtVM.h"
#include "Precompiled.h"
using namespace std; using namespace std;
using namespace dev; using namespace dev;
using namespace dev::eth; using namespace dev::eth;
#define ETH_VMTRACE 1 #define ETH_VMTRACE 1
Executive::~Executive()
{
// TODO: Make safe.
delete m_ext;
delete m_vm;
}
u256 Executive::gasUsed() const u256 Executive::gasUsed() const
{ {
return m_t.gas() - m_endGas; return m_t.gas() - m_endGas;
} }
bool Executive::forceSetup(bytesConstRef _rlp) void Executive::accrueSubState(SubState& _parentContext)
{ {
// Entry point for a user-executed transaction. if (m_ext)
m_t = Transaction(_rlp); _parentContext += m_ext->sub;
m_sender = m_t.sender();
// Increment associated nonce for sender.
m_s.noteSending(m_sender);
u256 cost = m_t.value() + m_t.gas() * m_t.gasPrice();
// Pay...
clog(StateDetail) << "Paying" << formatBalance(cost) << "from sender (includes" << m_t.gas() << "gas at" << formatBalance(m_t.gasPrice()) << ")";
m_s.subBalance(m_sender, cost);
if (m_ms)
{
m_ms->from = m_sender;
m_ms->to = m_t.receiveAddress();
m_ms->value = m_t.value();
m_ms->input = m_t.data();
}
auto gasCost = Interface::txGas(m_t.data());
if (m_t.isCreation())
return create(m_sender, m_t.value(), m_t.gasPrice(), m_t.gas() - (u256)gasCost, &m_t.data(), m_sender);
else
return call(m_t.receiveAddress(), m_sender, m_t.value(), m_t.gasPrice(), bytesConstRef(&m_t.data()), m_t.gas() - (u256)gasCost, m_sender);
} }
bool Executive::setup(bytesConstRef _rlp) bool Executive::setup(bytesConstRef _rlp)
@ -79,10 +48,8 @@ bool Executive::setup(bytesConstRef _rlp)
// Entry point for a user-executed transaction. // Entry point for a user-executed transaction.
m_t = Transaction(_rlp); m_t = Transaction(_rlp);
m_sender = m_t.sender();
// Avoid invalid transactions. // Avoid invalid transactions.
auto nonceReq = m_s.transactionsFrom(m_sender); auto nonceReq = m_s.transactionsFrom(m_t.sender());
if (m_t.nonce() != nonceReq) if (m_t.nonce() != nonceReq)
{ {
clog(StateDetail) << "Invalid Nonce: Require" << nonceReq << " Got" << m_t.nonce(); clog(StateDetail) << "Invalid Nonce: Require" << nonceReq << " Got" << m_t.nonce();
@ -101,10 +68,10 @@ bool Executive::setup(bytesConstRef _rlp)
u256 cost = m_t.value() + m_t.gas() * m_t.gasPrice(); u256 cost = m_t.value() + m_t.gas() * m_t.gasPrice();
// Avoid unaffordable transactions. // Avoid unaffordable transactions.
if (m_s.balance(m_sender) < cost) if (m_s.balance(m_t.sender()) < cost)
{ {
clog(StateDetail) << "Not enough cash: Require >" << cost << " Got" << m_s.balance(m_sender); clog(StateDetail) << "Not enough cash: Require >" << cost << " Got" << m_s.balance(m_t.sender());
BOOST_THROW_EXCEPTION(NotEnoughCash() << RequirementError((bigint)cost, (bigint)m_s.balance(m_sender))); BOOST_THROW_EXCEPTION(NotEnoughCash() << RequirementError((bigint)cost, (bigint)m_s.balance(m_t.sender())));
} }
u256 startGasUsed = m_s.gasUsed(); u256 startGasUsed = m_s.gasUsed();
@ -115,36 +82,45 @@ bool Executive::setup(bytesConstRef _rlp)
} }
// Increment associated nonce for sender. // Increment associated nonce for sender.
m_s.noteSending(m_sender); m_s.noteSending(m_t.sender());
// Pay... // Pay...
clog(StateDetail) << "Paying" << formatBalance(cost) << "from sender (includes" << m_t.gas() << "gas at" << formatBalance(m_t.gasPrice()) << ")"; clog(StateDetail) << "Paying" << formatBalance(cost) << "from sender (includes" << m_t.gas() << "gas at" << formatBalance(m_t.gasPrice()) << ")";
m_s.subBalance(m_sender, cost); m_s.subBalance(m_t.sender(), cost);
if (m_ms)
{
m_ms->from = m_sender;
m_ms->to = m_t.receiveAddress();
m_ms->value = m_t.value();
m_ms->input = m_t.data();
}
if (m_t.isCreation()) if (m_t.isCreation())
return create(m_sender, m_t.value(), m_t.gasPrice(), m_t.gas() - (u256)gasCost, &m_t.data(), m_sender); return create(m_t.sender(), m_t.value(), m_t.gasPrice(), m_t.gas() - (u256)gasCost, &m_t.data(), m_t.sender());
else else
return call(m_t.receiveAddress(), m_sender, m_t.value(), m_t.gasPrice(), bytesConstRef(&m_t.data()), m_t.gas() - (u256)gasCost, m_sender); return call(m_t.receiveAddress(), m_t.receiveAddress(), m_t.sender(), m_t.value(), m_t.gasPrice(), bytesConstRef(&m_t.data()), m_t.gas() - (u256)gasCost, m_t.sender());
} }
bool Executive::call(Address _receiveAddress, Address _senderAddress, u256 _value, u256 _gasPrice, bytesConstRef _data, u256 _gas, Address _originAddress) bool Executive::call(Address _receiveAddress, Address _codeAddress, Address _senderAddress, u256 _value, u256 _gasPrice, bytesConstRef _data, u256 _gas, Address _originAddress)
{ {
m_isCreation = false;
// cnote << "Transferring" << formatBalance(_value) << "to receiver."; // cnote << "Transferring" << formatBalance(_value) << "to receiver.";
m_s.addBalance(_receiveAddress, _value); m_s.addBalance(_receiveAddress, _value);
if (m_s.addressHasCode(_receiveAddress)) auto it = !(_codeAddress & ~h160(0xffffffff)) ? precompiled().find((unsigned)(u160)_codeAddress) : precompiled().end();
if (it != precompiled().end())
{
bigint g = it->second.gas(_data);
if (_gas < g)
{
m_endGas = 0;
m_excepted = true;
}
else
{
m_endGas = (u256)(_gas - g);
m_precompiledOut = it->second.exec(_data);
m_out = &m_precompiledOut;
}
}
else if (m_s.addressHasCode(_codeAddress))
{ {
m_vm = new VM(_gas); m_vm = VMFactory::create(_gas);
bytes const& c = m_s.code(_receiveAddress); bytes const& c = m_s.code(_codeAddress);
m_ext = new ExtVM(m_s, _receiveAddress, _senderAddress, _originAddress, _value, _gasPrice, _data, &c, m_ms); m_ext = make_shared<ExtVM>(m_s, _receiveAddress, _senderAddress, _originAddress, _value, _gasPrice, _data, &c, m_depth);
} }
else else
m_endGas = _gas; m_endGas = _gas;
@ -153,6 +129,8 @@ bool Executive::call(Address _receiveAddress, Address _senderAddress, u256 _valu
bool Executive::create(Address _sender, u256 _endowment, u256 _gasPrice, u256 _gas, bytesConstRef _init, Address _origin) bool Executive::create(Address _sender, u256 _endowment, u256 _gasPrice, u256 _gas, bytesConstRef _init, Address _origin)
{ {
m_isCreation = true;
// We can allow for the reverted state (i.e. that with which m_ext is constructed) to contain the m_newAddress, since // We can allow for the reverted state (i.e. that with which m_ext is constructed) to contain the m_newAddress, since
// we delete it explicitly if we decide we need to revert. // we delete it explicitly if we decide we need to revert.
m_newAddress = right160(sha3(rlpList(_sender, m_s.transactionsFrom(_sender) - 1))); m_newAddress = right160(sha3(rlpList(_sender, m_s.transactionsFrom(_sender) - 1)));
@ -161,17 +139,17 @@ bool Executive::create(Address _sender, u256 _endowment, u256 _gasPrice, u256 _g
m_s.m_cache[m_newAddress] = Account(m_s.balance(m_newAddress) + _endowment, Account::ContractConception); m_s.m_cache[m_newAddress] = Account(m_s.balance(m_newAddress) + _endowment, Account::ContractConception);
// Execute _init. // Execute _init.
m_vm = new VM(_gas); m_vm = VMFactory::create(_gas);
m_ext = new ExtVM(m_s, m_newAddress, _sender, _origin, _endowment, _gasPrice, bytesConstRef(), _init, m_ms); m_ext = make_shared<ExtVM>(m_s, m_newAddress, _sender, _origin, _endowment, _gasPrice, bytesConstRef(), _init, m_depth);
return _init.empty(); return _init.empty();
} }
OnOpFunc Executive::simpleTrace() OnOpFunc Executive::simpleTrace()
{ {
return [](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, void* voidVM, void const* voidExt) return [](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, VM* voidVM, ExtVMFace const* voidExt)
{ {
ExtVM const& ext = *(ExtVM const*)voidExt; ExtVM const& ext = *static_cast<ExtVM const*>(voidExt);
VM& vm = *(VM*)voidVM; VM& vm = *voidVM;
ostringstream o; ostringstream o;
o << endl << " STACK" << endl; o << endl << " STACK" << endl;
@ -190,18 +168,22 @@ bool Executive::go(OnOpFunc const& _onOp)
{ {
if (m_vm) if (m_vm)
{ {
#if ETH_TIMED_EXECUTIONS
boost::timer t; boost::timer t;
auto sgas = m_vm->gas(); #endif
bool revert = false;
try try
{ {
m_out = m_vm->go(*m_ext, _onOp); m_out = m_vm->go(*m_ext, _onOp);
if (m_ext) m_endGas = m_vm->gas();
if (m_isCreation)
{ {
m_endGas += min((m_t.gas() - m_endGas) / 2, m_ext->sub.refunds); if (m_out.size() * c_createDataGas <= m_endGas)
m_logs = m_ext->sub.logs; m_endGas -= m_out.size() * c_createDataGas;
else
m_out.reset();
m_s.m_cache[m_newAddress].setCode(m_out);
} }
m_endGas = m_vm->gas();
} }
catch (StepsDone const&) catch (StepsDone const&)
{ {
@ -209,9 +191,10 @@ bool Executive::go(OnOpFunc const& _onOp)
} }
catch (VMException const& _e) catch (VMException const& _e)
{ {
clog(StateChat) << "Safe VM Exception: " << diagnostic_information(_e); clog(StateSafeExceptions) << "Safe VM Exception. " << diagnostic_information(_e);
m_endGas = 0;//m_vm->gas(); m_endGas = 0;
revert = true; m_excepted = true;
m_ext->revert();
} }
catch (Exception const& _e) catch (Exception const& _e)
{ {
@ -223,46 +206,32 @@ bool Executive::go(OnOpFunc const& _onOp)
// TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does. // TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
cwarn << "Unexpected std::exception in VM. This is probably unrecoverable. " << _e.what(); cwarn << "Unexpected std::exception in VM. This is probably unrecoverable. " << _e.what();
} }
#if ETH_TIMED_EXECUTIONS
cnote << "VM took:" << t.elapsed() << "; gas used: " << (sgas - m_endGas); cnote << "VM took:" << t.elapsed() << "; gas used: " << (sgas - m_endGas);
#endif
// Write state out only in the case of a non-excepted transaction.
if (revert)
{
m_ext->revert();
// Explicitly delete a newly created address - this will still be in the reverted state.
if (m_newAddress)
{
m_s.m_cache.erase(m_newAddress);
m_newAddress = Address();
}
}
} }
return true; return true;
} }
u256 Executive::gas() const
{
return m_vm ? m_vm->gas() : m_endGas;
}
void Executive::finalize(OnOpFunc const&) void Executive::finalize(OnOpFunc const&)
{ {
if (m_t.isCreation() && m_newAddress && m_out.size()) // SSTORE refunds...
// non-reverted creation - put code in place. // must be done before the miner gets the fees.
m_s.m_cache[m_newAddress].setCode(m_out); if (m_ext)
m_endGas += min((m_t.gas() - m_endGas) / 2, m_ext->sub.refunds);
// cnote << "Refunding" << formatBalance(m_endGas * m_ext->gasPrice) << "to origin (=" << m_endGas << "*" << formatBalance(m_ext->gasPrice) << ")"; // cnote << "Refunding" << formatBalance(m_endGas * m_ext->gasPrice) << "to origin (=" << m_endGas << "*" << formatBalance(m_ext->gasPrice) << ")";
m_s.addBalance(m_sender, m_endGas * m_t.gasPrice()); m_s.addBalance(m_t.sender(), m_endGas * m_t.gasPrice());
u256 feesEarned = (m_t.gas() - m_endGas) * m_t.gasPrice(); u256 feesEarned = (m_t.gas() - m_endGas) * m_t.gasPrice();
// cnote << "Transferring" << formatBalance(gasSpent) << "to miner.";
m_s.addBalance(m_s.m_currentBlock.coinbaseAddress, feesEarned); m_s.addBalance(m_s.m_currentBlock.coinbaseAddress, feesEarned);
if (m_ms)
m_ms->output = m_out.toBytes();
// Suicides... // Suicides...
if (m_ext) if (m_ext)
for (auto a: m_ext->sub.suicides) for (auto a: m_ext->sub.suicides)
m_s.m_cache[a].kill(); m_s.m_cache[a].kill();
// Logs..
if (m_ext)
m_logs = m_ext->sub.logs;
} }

99
libethereum/Executive.h

@ -1,16 +1,13 @@
/* /*
This file is part of cpp-ethereum. This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful, cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/ */
@ -25,62 +22,96 @@
#include <libdevcore/Log.h> #include <libdevcore/Log.h>
#include <libevmcore/Instruction.h> #include <libevmcore/Instruction.h>
#include <libethcore/CommonEth.h> #include <libethcore/CommonEth.h>
#include <libevm/ExtVMFace.h> #include <libevm/VMFace.h>
#include "Transaction.h" #include "Transaction.h"
#include "Manifest.h"
namespace dev namespace dev
{ {
namespace eth namespace eth
{ {
class VM;
class ExtVM;
class State; class State;
class ExtVM;
struct Manifest;
struct VMTraceChannel: public LogChannel { static const char* name() { return "EVM"; } static const int verbosity = 11; }; struct VMTraceChannel: public LogChannel { static const char* name() { return "EVM"; } static const int verbosity = 11; };
/**
* @brief Message-call/contract-creation executor; useful for executing transactions.
*
* Two ways of using this class - either as a transaction executive or a CALL/CREATE executive.
* In the first use, after construction, begin with setup() and end with finalize(). Call go()
* after setup() only if it returns false.
* In the second use, after construction, begin with call() or create() and end with
* accrueSubState(). Call go() after call()/create() only if it returns false.
*/
class Executive class Executive
{ {
public: public:
Executive(State& _s, Manifest* o_ms = nullptr): m_s(_s), m_ms(o_ms) {} /// Basic constructor.
~Executive(); Executive(State& _s, unsigned _level): m_s(_s), m_depth(_level) {}
/// Basic destructor.
~Executive() = default;
Executive(Executive const&) = delete;
void operator=(Executive) = delete;
/// Set up the executive for evaluating a transaction. You must call finalize() following this.
/// @returns true iff go() must be called (and thus a VM execution in required).
bool setup(bytesConstRef _transaction); bool setup(bytesConstRef _transaction);
bool forceSetup(bytesConstRef _transaction); /// Finalise a transaction previously set up with setup().
bool create(Address _txSender, u256 _endowment, u256 _gasPrice, u256 _gas, bytesConstRef _code, Address _originAddress); /// @warning Only valid after setup(), and possibly go().
bool call(Address _myAddress, Address _txSender, u256 _txValue, u256 _gasPrice, bytesConstRef _txData, u256 _gas, Address _originAddress);
bool go(OnOpFunc const& _onOp = OnOpFunc());
void finalize(OnOpFunc const& _onOp = OnOpFunc()); void finalize(OnOpFunc const& _onOp = OnOpFunc());
/// @returns the transaction from setup().
/// @warning Only valid after setup().
Transaction const& t() const { return m_t; }
/// @returns the log entries created by this operation.
/// @warning Only valid after finalise().
LogEntries const& logs() const { return m_logs; }
/// @returns total gas used in the transaction/operation.
/// @warning Only valid after finalise().
u256 gasUsed() const; u256 gasUsed() const;
static OnOpFunc simpleTrace(); /// Set up the executive for evaluating a bare CREATE (contract-creation) operation.
/// @returns false iff go() must be called (and thus a VM execution in required).
Transaction const& t() const { return m_t; } bool create(Address _txSender, u256 _endowment, u256 _gasPrice, u256 _gas, bytesConstRef _code, Address _originAddress);
/// Set up the executive for evaluating a bare CALL (message call) operation.
/// @returns false iff go() must be called (and thus a VM execution in required).
bool call(Address _myAddress, Address _codeAddress, Address _txSender, u256 _txValue, u256 _gasPrice, bytesConstRef _txData, u256 _gas, Address _originAddress);
/// Finalise an operation through accruing the substate into the parent context.
void accrueSubState(SubState& _parentContext);
/// Executes (or continues execution of) the VM.
/// @returns false iff go() must be called again to finish the transction.
bool go(OnOpFunc const& _onOp = OnOpFunc());
u256 gas() const; /// Operation function for providing a simple trace of the VM execution.
static OnOpFunc simpleTrace();
/// @returns gas remaining after the transaction/operation.
u256 endGas() const { return m_endGas; }
/// @returns output data of the transaction/operation.
bytesConstRef out() const { return m_out; } bytesConstRef out() const { return m_out; }
/// @returns the new address for the created contract in the CREATE operation.
h160 newAddress() const { return m_newAddress; } h160 newAddress() const { return m_newAddress; }
LogEntries const& logs() const { return m_logs; } /// @returns true iff the operation ended with a VM exception.
bool excepted() const { return m_excepted; }
VM const& vm() const { return *m_vm; }
State const& state() const { return m_s; }
ExtVM const& ext() const { return *m_ext; }
private: private:
State& m_s; State& m_s; ///< The state to which this operation/transaction is applied.
ExtVM* m_ext = nullptr; // TODO: make safe. std::shared_ptr<ExtVM> m_ext; ///< The VM externality object for the VM execution or null if no VM is required.
VM* m_vm = nullptr; std::unique_ptr<VMFace> m_vm; ///< The VM object or null if no VM is required.
Manifest* m_ms = nullptr; bytes m_precompiledOut; ///< Used for the output when there is no VM for a contract (i.e. precompiled).
bytesConstRef m_out; bytesConstRef m_out; ///< The copyable output.
Address m_newAddress; Address m_newAddress; ///< The address of the created contract in the case of create() being called.
Transaction m_t; unsigned m_depth = 0; ///< The context's call-depth.
Address m_sender; bool m_isCreation = false; ///< True if the transaction creates a contract, or if create() is called.
u256 m_endGas; bool m_excepted = false; ///< True if the VM execution resulted in an exception.
u256 m_endGas; ///< The final amount of gas for the transaction.
LogEntries m_logs;
Transaction m_t; ///< The original transaction. Set by setup().
LogEntries m_logs; ///< The log entries created by this transaction. Set by finalize().
}; };
} }

36
libethereum/ExtVM.cpp

@ -21,5 +21,37 @@
#include "ExtVM.h" #include "ExtVM.h"
#pragma GCC diagnostic ignored "-Wunused-variable" #include "Executive.h"
namespace { char dummy; }; using namespace std;
using namespace dev;
using namespace dev::eth;
bool ExtVM::call(Address _receiveAddress, u256 _txValue, bytesConstRef _txData, u256& io_gas, bytesRef _out, OnOpFunc const& _onOp, Address _myAddressOverride, Address _codeAddressOverride)
{
Executive e(m_s, depth + 1);
if (!e.call(_receiveAddress, _codeAddressOverride ? _codeAddressOverride : _receiveAddress, _myAddressOverride ? _myAddressOverride : myAddress, _txValue, gasPrice, _txData, io_gas, origin))
{
e.go(_onOp);
e.accrueSubState(sub);
}
io_gas = e.endGas();
e.out().copyTo(_out);
return !e.excepted();
}
h160 ExtVM::create(u256 _endowment, u256& io_gas, bytesConstRef _code, OnOpFunc const& _onOp)
{
// Increment associated nonce for sender.
m_s.noteSending(myAddress);
Executive e(m_s, depth + 1);
if (!e.create(myAddress, _endowment, gasPrice, io_gas, _code, origin))
{
e.go(_onOp);
e.accrueSubState(sub);
}
io_gas = e.endGas();
return e.newAddress();
}

32
libethereum/ExtVM.h

@ -39,8 +39,8 @@ class ExtVM: public ExtVMFace
{ {
public: public:
/// Full constructor. /// Full constructor.
ExtVM(State& _s, Address _myAddress, Address _caller, Address _origin, u256 _value, u256 _gasPrice, bytesConstRef _data, bytesConstRef _code, Manifest* o_ms, unsigned _depth = 0): ExtVM(State& _s, Address _myAddress, Address _caller, Address _origin, u256 _value, u256 _gasPrice, bytesConstRef _data, bytesConstRef _code, unsigned _depth = 0):
ExtVMFace(_myAddress, _caller, _origin, _value, _gasPrice, _data, _code.toBytes(), _s.m_previousBlock, _s.m_currentBlock, _depth), m_s(_s), m_origCache(_s.m_cache), m_ms(o_ms) ExtVMFace(_myAddress, _caller, _origin, _value, _gasPrice, _data, _code.toBytes(), _s.m_previousBlock, _s.m_currentBlock, _depth), m_s(_s), m_origCache(_s.m_cache)
{ {
m_s.ensureCached(_myAddress, true, true); m_s.ensureCached(_myAddress, true, true);
} }
@ -49,34 +49,16 @@ public:
virtual u256 store(u256 _n) override final { return m_s.storage(myAddress, _n); } virtual u256 store(u256 _n) override final { return m_s.storage(myAddress, _n); }
/// Write a value in storage. /// Write a value in storage.
virtual void setStore(u256 _n, u256 _v) override final { m_s.setStorage(myAddress, _n, _v); if (m_ms) m_ms->altered.push_back(_n); } virtual void setStore(u256 _n, u256 _v) override final { m_s.setStorage(myAddress, _n, _v); }
/// Read address's code. /// Read address's code.
virtual bytes const& codeAt(Address _a) override final { return m_s.code(_a); } virtual bytes const& codeAt(Address _a) override final { return m_s.code(_a); }
/// Create a new contract. /// Create a new contract.
virtual h160 create(u256 _endowment, u256* _gas, bytesConstRef _code, OnOpFunc const& _onOp = OnOpFunc()) override final virtual h160 create(u256 _endowment, u256& io_gas, bytesConstRef _code, OnOpFunc const& _onOp = {}) override final;
{
// Increment associated nonce for sender.
m_s.noteSending(myAddress);
if (m_ms)
m_ms->internal.resize(m_ms->internal.size() + 1);
auto ret = m_s.create(myAddress, _endowment, gasPrice, _gas, _code, origin, &sub, m_ms ? &(m_ms->internal.back()) : nullptr, _onOp, depth + 1);
if (m_ms && !m_ms->internal.back().from)
m_ms->internal.pop_back();
return ret;
}
/// Create a new message call. Leave _myAddressOverride as the default to use the present address as caller. /// Create a new message call. Leave _myAddressOverride as the default to use the present address as caller.
virtual bool call(Address _receiveAddress, u256 _txValue, bytesConstRef _txData, u256* _gas, bytesRef _out, OnOpFunc const& _onOp = {}, Address _myAddressOverride = {}, Address _codeAddressOverride = {}) override final virtual bool call(Address _receiveAddress, u256 _txValue, bytesConstRef _txData, u256& io_gas, bytesRef _out, OnOpFunc const& _onOp = {}, Address _myAddressOverride = {}, Address _codeAddressOverride = {}) override final;
{
if (m_ms)
m_ms->internal.resize(m_ms->internal.size() + 1);
auto ret = m_s.call(_receiveAddress, _codeAddressOverride ? _codeAddressOverride : _receiveAddress, _myAddressOverride ? _myAddressOverride : myAddress, _txValue, gasPrice, _txData, _gas, _out, origin, &sub, m_ms ? &(m_ms->internal.back()) : nullptr, _onOp, depth + 1);
if (m_ms && !m_ms->internal.back().from)
m_ms->internal.pop_back();
return ret;
}
/// Read address's balance. /// Read address's balance.
virtual u256 balance(Address _a) override final { return m_s.balance(_a); } virtual u256 balance(Address _a) override final { return m_s.balance(_a); }
@ -91,19 +73,19 @@ public:
virtual void suicide(Address _a) override final virtual void suicide(Address _a) override final
{ {
m_s.addBalance(_a, m_s.balance(myAddress)); m_s.addBalance(_a, m_s.balance(myAddress));
m_s.subBalance(myAddress, m_s.balance(myAddress));
ExtVMFace::suicide(_a); ExtVMFace::suicide(_a);
} }
/// Revert any changes made (by any of the other calls). /// Revert any changes made (by any of the other calls).
/// @TODO check call site for the parent manifest being discarded. /// @TODO check call site for the parent manifest being discarded.
virtual void revert() override final { if (m_ms) *m_ms = Manifest(); m_s.m_cache = m_origCache; } virtual void revert() override final { m_s.m_cache = m_origCache; sub.clear(); }
State& state() const { return m_s; } State& state() const { return m_s; }
private: private:
State& m_s; ///< A reference to the base state. State& m_s; ///< A reference to the base state.
std::map<Address, Account> m_origCache; ///< The cache of the address states (i.e. the externalities) as-was prior to the execution. std::map<Address, Account> m_origCache; ///< The cache of the address states (i.e. the externalities) as-was prior to the execution.
Manifest* m_ms;
}; };
} }

7
libethereum/Interface.h

@ -26,7 +26,7 @@
#include <libdevcore/Guards.h> #include <libdevcore/Guards.h>
#include <libdevcrypto/Common.h> #include <libdevcrypto/Common.h>
#include <libevm/FeeStructure.h> #include <libevm/FeeStructure.h>
#include "MessageFilter.h" #include "LogFilter.h"
#include "Transaction.h" #include "Transaction.h"
#include "AccountDiff.h" #include "AccountDiff.h"
#include "BlockDetails.h" #include "BlockDetails.h"
@ -84,11 +84,6 @@ public:
virtual bytes codeAt(Address _a, int _block) const = 0; virtual bytes codeAt(Address _a, int _block) const = 0;
virtual std::map<u256, u256> storageAt(Address _a, int _block) const = 0; virtual std::map<u256, u256> storageAt(Address _a, int _block) const = 0;
// // [MESSAGE API]
//
// virtual PastMessages messages(unsigned _watchId) const = 0;
// virtual PastMessages messages(MessageFilter const& _filter) const = 0;
// [LOGS API] // [LOGS API]
virtual LogEntries logs(unsigned _watchId) const = 0; virtual LogEntries logs(unsigned _watchId) const = 0;

81
libethereum/LogFilter.cpp

@ -0,0 +1,81 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file LogFilter.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "LogFilter.h"
#include <libdevcrypto/SHA3.h>
#include "State.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
void LogFilter::streamRLP(RLPStream& _s) const
{
_s.appendList(6) << m_addresses << m_topics << m_earliest << m_latest << m_max << m_skip;
}
h256 LogFilter::sha3() const
{
RLPStream s;
streamRLP(s);
return dev::sha3(s.out());
}
bool LogFilter::matches(LogBloom _bloom) const
{
if (m_addresses.size())
{
for (auto i: m_addresses)
if (_bloom.containsBloom<3>(dev::sha3(i)))
goto OK1;
return false;
}
OK1:
if (m_topics.size())
{
for (auto i: m_topics)
if (_bloom.containsBloom<3>(dev::sha3(i)))
goto OK2;
return false;
}
OK2:
return true;
}
bool LogFilter::matches(State const& _s, unsigned _i) const
{
return matches(_s.receipt(_i)).size() > 0;
}
LogEntries LogFilter::matches(TransactionReceipt const& _m) const
{
LogEntries ret;
for (LogEntry const& e: _m.log())
{
if (!m_addresses.empty() && !m_addresses.count(e.address))
continue;
for (auto const& t: m_topics)
if (!std::count(e.topics.begin(), e.topics.end(), t))
continue;
ret.push_back(e);
}
return ret;
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save