Browse Source

Merge pull request #1186 from onepremise/develop

Updates for Building all cpp-ethereum on MinGW(64)
cl-refactor
Gav Wood 10 years ago
parent
commit
f4c93bb091
  1. 1
      alethzero/CMakeLists.txt
  2. 4
      alethzero/MainWin.cpp
  3. 1
      alethzero/MainWin.h
  4. 3
      alethzero/Transact.cpp
  5. 2
      cmake/EthCompilerSettings.cmake
  6. 2
      cmake/FindJsonRpcCpp.cmake
  7. 2
      eth/CMakeLists.txt
  8. 2
      eth/main.cpp
  9. 2
      libdevcore/CMakeLists.txt
  10. 46
      libdevcore/UndefMacros.h
  11. 2
      libdevcore/debugbreak.h
  12. 2
      libdevcrypto/CMakeLists.txt
  13. 2
      libethcore/CMakeLists.txt
  14. 7
      libethereum/CMakeLists.txt
  15. 2
      libethereum/Client.h
  16. 1
      libethereum/EthereumHost.h
  17. 4
      libethereum/EthereumPeer.h
  18. 2
      libethereumx/CMakeLists.txt
  19. 2
      libevm/CMakeLists.txt
  20. 2
      libevmcore/CMakeLists.txt
  21. 2
      libjsqrc/CMakeLists.txt
  22. 2
      liblll/CMakeLists.txt
  23. 3
      libnatspec/CMakeLists.txt
  24. 7
      libp2p/CMakeLists.txt
  25. 3
      libp2p/Common.h
  26. 2
      libp2p/Host.cpp
  27. 1
      libp2p/Host.h
  28. 27
      libp2p/Network.cpp
  29. 96
      libp2p/NodeTable.h
  30. 3
      libp2p/Session.h
  31. 53
      libp2p/UDP.h
  32. 2
      libserpent/CMakeLists.txt
  33. 2
      libsolidity/CMakeLists.txt
  34. 1
      libsolidity/Token.h
  35. 2
      libsolidity/Types.h
  36. 3
      libweb3jsonrpc/CMakeLists.txt
  37. 3
      libweb3jsonrpc/WebThreeStubServer.cpp
  38. 9
      libweb3jsonrpc/WebThreeStubServerBase.cpp
  39. 3
      libwebthree/CMakeLists.txt
  40. 2
      libwebthree/WebThree.cpp
  41. 6
      libwebthree/WebThree.h
  42. 3
      libwhisper/CMakeLists.txt
  43. 1
      libwhisper/Common.h
  44. 1
      libwhisper/Interface.h
  45. 1
      libwhisper/Message.h
  46. 1
      libwhisper/WhisperHost.h
  47. 1
      libwhisper/WhisperPeer.h
  48. 1
      mix/CMakeLists.txt
  49. 3
      mix/ClientModel.cpp
  50. 3
      mix/DebuggingStateWrapper.h
  51. 3
      mix/Extension.cpp
  52. 1
      mix/QContractDefinition.cpp
  53. 1
      neth/CMakeLists.txt
  54. 2
      neth/main.cpp
  55. 14
      secp256k1/CMakeLists.txt
  56. 2
      test/TestHelper.cpp
  57. 2
      test/TestHelper.h
  58. 2
      test/createRandomTest.cpp
  59. 1
      test/fork.cpp
  60. 6
      test/genesis.cpp
  61. 8
      test/hexPrefix.cpp
  62. 37
      test/net.cpp
  63. 146
      test/rlp.cpp
  64. 1
      test/state.cpp
  65. 4
      test/trie.cpp
  66. 1
      test/txTest.cpp
  67. 6
      test/vm.cpp
  68. 2
      test/vm.h
  69. 32
      test/whisperTopic.cpp
  70. 1
      third/CMakeLists.txt
  71. 16
      third/MainWin.cpp

1
alethzero/CMakeLists.txt

@ -13,6 +13,7 @@ aux_source_directory(. SRC_LIST)
include_directories(BEFORE ${JSONCPP_INCLUDE_DIRS}) include_directories(BEFORE ${JSONCPP_INCLUDE_DIRS})
include_directories(BEFORE ..) include_directories(BEFORE ..)
include_directories(${JSON_RPC_CPP_INCLUDE_DIRS}) include_directories(${JSON_RPC_CPP_INCLUDE_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
qt5_wrap_ui(ui_Main.h Main.ui) qt5_wrap_ui(ui_Main.h Main.ui)
qt5_wrap_ui(ui_Debugger.h Debugger.ui) qt5_wrap_ui(ui_Debugger.h Debugger.ui)

4
alethzero/MainWin.cpp

@ -20,6 +20,10 @@
*/ */
#include <fstream> #include <fstream>
// Make sure boost/asio.hpp is included before windows.h.
#include <boost/asio.hpp>
#include <QtNetwork/QNetworkReply> #include <QtNetwork/QNetworkReply>
#include <QtWidgets/QFileDialog> #include <QtWidgets/QFileDialog>
#include <QtWidgets/QMessageBox> #include <QtWidgets/QMessageBox>

1
alethzero/MainWin.h

@ -26,6 +26,7 @@
#endif #endif
#include <map> #include <map>
#include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkAccessManager>
#include <QtCore/QAbstractListModel> #include <QtCore/QAbstractListModel>
#include <QtCore/QMutex> #include <QtCore/QMutex>

3
alethzero/Transact.cpp

@ -19,6 +19,9 @@
* @date 2015 * @date 2015
*/ */
// Make sure boost/asio.hpp is included before windows.h.
#include <boost/asio.hpp>
#include "Transact.h" #include "Transact.h"
#include <fstream> #include <fstream>

2
cmake/EthCompilerSettings.cmake

@ -3,7 +3,7 @@
# 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 -Werror -DSHAREDLIB -fPIC") set(CMAKE_CXX_FLAGS "-std=c++11 -Wall -Wno-unknown-pragmas -Wextra -Werror -DSHAREDLIB -fPIC ${CMAKE_CXX_FLAGS}")
set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DETH_DEBUG") set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g -DETH_DEBUG")
set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG -DETH_RELEASE") set(CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG -DETH_RELEASE")
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG -DETH_RELEASE") set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG -DETH_RELEASE")

2
cmake/FindJsonRpcCpp.cmake

@ -14,7 +14,7 @@
# only look in default directories # only look in default directories
find_path( find_path(
JSON_RPC_CPP_INCLUDE_DIR JSON_RPC_CPP_INCLUDE_DIR
NAMES jsonrpccpp/server.h NAMES jsonrpccpp/server.h jsonrpc/server.h
PATH_SUFFIXES jsonrpc PATH_SUFFIXES jsonrpc
DOC "json-rpc-cpp include dir" DOC "json-rpc-cpp include dir"
) )

2
eth/CMakeLists.txt

@ -28,7 +28,7 @@ endif()
target_link_libraries(${EXECUTABLE} webthree) target_link_libraries(${EXECUTABLE} webthree)
target_link_libraries(${EXECUTABLE} secp256k1) target_link_libraries(${EXECUTABLE} secp256k1)
if (WIN32) if (DEFINED WIN32 AND NOT DEFINED CMAKE_COMPILER_IS_MINGW)
add_custom_command(TARGET ${EXECUTABLE} POST_BUILD COMMAND ${CMAKE_COMMAND} ARGS -E copy ${MHD_DLL_RELEASE} "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}") add_custom_command(TARGET ${EXECUTABLE} POST_BUILD COMMAND ${CMAKE_COMMAND} ARGS -E copy ${MHD_DLL_RELEASE} "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}")
endif() endif()

2
eth/main.cpp

@ -25,8 +25,10 @@
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#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>
#include <libdevcrypto/FileSystem.h> #include <libdevcrypto/FileSystem.h>
#include <libevmcore/Instruction.h> #include <libevmcore/Instruction.h>
#include <libdevcore/StructuredLogger.h> #include <libdevcore/StructuredLogger.h>

2
libdevcore/CMakeLists.txt

@ -44,6 +44,6 @@ elseif (UNIX)
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} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

46
libdevcore/UndefMacros.h

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

2
libdevcore/debugbreak.h

@ -27,7 +27,7 @@
#ifndef DEBUG_BREAK_H #ifndef DEBUG_BREAK_H
#define DEBUG_BREAK_H #define DEBUG_BREAK_H
#ifdef _MSC_VER #if defined(_MSC_VER) || defined(__MINGW32__)
#define debug_break __debugbreak #define debug_break __debugbreak

2
libdevcrypto/CMakeLists.txt

@ -28,6 +28,6 @@ target_link_libraries(${EXECUTABLE} ${LEVELDB_LIBRARIES})
target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LIBRARIES}) target_link_libraries(${EXECUTABLE} ${CRYPTOPP_LIBRARIES})
target_link_libraries(${EXECUTABLE} devcore) target_link_libraries(${EXECUTABLE} devcore)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

2
libethcore/CMakeLists.txt

@ -25,6 +25,6 @@ endif()
target_link_libraries(${EXECUTABLE} devcrypto) target_link_libraries(${EXECUTABLE} devcrypto)
target_link_libraries(${EXECUTABLE} devcore) target_link_libraries(${EXECUTABLE} devcore)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

7
libethereum/CMakeLists.txt

@ -13,6 +13,7 @@ aux_source_directory(. SRC_LIST)
include_directories(BEFORE ..) include_directories(BEFORE ..)
include_directories(${LEVELDB_INCLUDE_DIRS}) include_directories(${LEVELDB_INCLUDE_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
set(EXECUTABLE ethereum) set(EXECUTABLE ethereum)
@ -35,6 +36,10 @@ 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)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) if (CMAKE_COMPILER_IS_MINGW)
target_link_libraries(${EXECUTABLE} ssp shlwapi)
endif()
install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

2
libethereum/Client.h

@ -27,7 +27,9 @@
#include <atomic> #include <atomic>
#include <string> #include <string>
#include <array> #include <array>
#include <boost/utility.hpp> #include <boost/utility.hpp>
#include <libdevcore/Common.h> #include <libdevcore/Common.h>
#include <libdevcore/CommonIO.h> #include <libdevcore/CommonIO.h>
#include <libdevcore/Guards.h> #include <libdevcore/Guards.h>

1
libethereum/EthereumHost.h

@ -28,6 +28,7 @@
#include <memory> #include <memory>
#include <utility> #include <utility>
#include <thread> #include <thread>
#include <libdevcore/Guards.h> #include <libdevcore/Guards.h>
#include <libdevcore/Worker.h> #include <libdevcore/Worker.h>
#include <libdevcore/RangeMask.h> #include <libdevcore/RangeMask.h>

4
libethereum/EthereumPeer.h

@ -26,6 +26,10 @@
#include <set> #include <set>
#include <memory> #include <memory>
#include <utility> #include <utility>
// Make sure boost/asio.hpp is included before windows.h.
#include <boost/asio.hpp>
#include <libdevcore/RLP.h> #include <libdevcore/RLP.h>
#include <libdevcore/Guards.h> #include <libdevcore/Guards.h>
#include <libdevcore/RangeMask.h> #include <libdevcore/RangeMask.h>

2
libethereumx/CMakeLists.txt

@ -30,6 +30,6 @@ target_link_libraries(${EXECUTABLE} lll)
target_link_libraries(${EXECUTABLE} ethcore) target_link_libraries(${EXECUTABLE} ethcore)
target_link_libraries(${EXECUTABLE} secp256k1) target_link_libraries(${EXECUTABLE} secp256k1)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

2
libevm/CMakeLists.txt

@ -34,6 +34,6 @@ if (EVMJIT)
target_link_libraries(${EXECUTABLE} evmjit-cpp) target_link_libraries(${EXECUTABLE} evmjit-cpp)
endif() endif()
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

2
libevmcore/CMakeLists.txt

@ -26,6 +26,6 @@ endif()
target_link_libraries(${EXECUTABLE} devcore) target_link_libraries(${EXECUTABLE} devcore)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

2
libjsqrc/CMakeLists.txt

@ -22,4 +22,4 @@ if (ETH_NODE AND ETH_NPM)
add_dependencies(jsqrc ethereumjs) add_dependencies(jsqrc ethereumjs)
endif() endif()
install( TARGETS jsqrc ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS jsqrc RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )

2
liblll/CMakeLists.txt

@ -27,6 +27,6 @@ endif()
target_link_libraries(${EXECUTABLE} evmcore) target_link_libraries(${EXECUTABLE} evmcore)
target_link_libraries(${EXECUTABLE} devcore) target_link_libraries(${EXECUTABLE} devcore)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

3
libnatspec/CMakeLists.txt

@ -14,6 +14,7 @@ set(CMAKE_INCLUDE_CURRENT_DIR ON)
aux_source_directory(. SRC_LIST) aux_source_directory(. SRC_LIST)
include_directories(BEFORE ..) include_directories(BEFORE ..)
include_directories(${Boost_INCLUDE_DIRS})
set(EXECUTABLE natspec) set(EXECUTABLE natspec)
@ -31,5 +32,5 @@ target_link_libraries(${EXECUTABLE} Qt5::Core)
target_link_libraries(${EXECUTABLE} Qt5::Qml) target_link_libraries(${EXECUTABLE} Qt5::Qml)
target_link_libraries(${EXECUTABLE} devcore) target_link_libraries(${EXECUTABLE} devcore)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

7
libp2p/CMakeLists.txt

@ -15,6 +15,7 @@ include_directories(BEFORE ..)
# we may not use it in libp2p, but one of our dependecies is including leveldb in header file # we may not use it in libp2p, but one of our dependecies is including leveldb in header file
# and windows is failing to build without that # and windows is failing to build without that
include_directories(${LEVELDB_INCLUDE_DIRS}) include_directories(${LEVELDB_INCLUDE_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
if (MINIUPNPC_FOUND) if (MINIUPNPC_FOUND)
include_directories(${MINIUPNPC_INCLUDE_DIRS}) include_directories(${MINIUPNPC_INCLUDE_DIRS})
@ -37,6 +38,10 @@ endif()
target_link_libraries(${EXECUTABLE} devcrypto) target_link_libraries(${EXECUTABLE} devcrypto)
target_link_libraries(${EXECUTABLE} devcore) target_link_libraries(${EXECUTABLE} devcore)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) if (CMAKE_COMPILER_IS_MINGW)
target_link_libraries(${EXECUTABLE} ws2_32 mswsock)
endif()
install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

3
libp2p/Common.h

@ -27,8 +27,11 @@
#include <string> #include <string>
#include <set> #include <set>
#include <vector> #include <vector>
// Make sure boost/asio.hpp is included before windows.h.
#include <boost/asio.hpp> #include <boost/asio.hpp>
#include <boost/asio/ip/tcp.hpp> #include <boost/asio/ip/tcp.hpp>
#include <chrono> #include <chrono>
#include <libdevcrypto/Common.h> #include <libdevcrypto/Common.h>
#include <libdevcore/Log.h> #include <libdevcore/Log.h>

2
libp2p/Host.cpp

@ -24,7 +24,9 @@
#include <chrono> #include <chrono>
#include <thread> #include <thread>
#include <mutex> #include <mutex>
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
#include <libdevcore/Common.h> #include <libdevcore/Common.h>
#include <libdevcore/CommonIO.h> #include <libdevcore/CommonIO.h>
#include <libdevcore/StructuredLogger.h> #include <libdevcore/StructuredLogger.h>

1
libp2p/Host.h

@ -30,6 +30,7 @@
#include <utility> #include <utility>
#include <thread> #include <thread>
#include <chrono> #include <chrono>
#include <libdevcore/Guards.h> #include <libdevcore/Guards.h>
#include <libdevcore/Worker.h> #include <libdevcore/Worker.h>
#include <libdevcore/RangeMask.h> #include <libdevcore/RangeMask.h>

27
libp2p/Network.cpp

@ -27,6 +27,7 @@
#endif #endif
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
#include <libdevcore/Common.h> #include <libdevcore/Common.h>
#include <libdevcore/CommonIO.h> #include <libdevcore/CommonIO.h>
#include <libethcore/Exceptions.h> #include <libethcore/Exceptions.h>
@ -46,7 +47,7 @@ std::vector<bi::address> Network::getInterfaceAddresses()
WSAData wsaData; WSAData wsaData;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
BOOST_THROW_EXCEPTION(NoNetworking()); BOOST_THROW_EXCEPTION(NoNetworking());
char ac[80]; char ac[80];
if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR)
{ {
@ -54,7 +55,7 @@ std::vector<bi::address> Network::getInterfaceAddresses()
WSACleanup(); WSACleanup();
BOOST_THROW_EXCEPTION(NoNetworking()); BOOST_THROW_EXCEPTION(NoNetworking());
} }
struct hostent* phe = gethostbyname(ac); struct hostent* phe = gethostbyname(ac);
if (phe == 0) if (phe == 0)
{ {
@ -62,7 +63,7 @@ std::vector<bi::address> Network::getInterfaceAddresses()
WSACleanup(); WSACleanup();
BOOST_THROW_EXCEPTION(NoNetworking()); BOOST_THROW_EXCEPTION(NoNetworking());
} }
for (int i = 0; phe->h_addr_list[i] != 0; ++i) for (int i = 0; phe->h_addr_list[i] != 0; ++i)
{ {
struct in_addr addr; struct in_addr addr;
@ -72,18 +73,18 @@ std::vector<bi::address> Network::getInterfaceAddresses()
if (!isLocalHostAddress(address)) if (!isLocalHostAddress(address))
addresses.push_back(address.to_v4()); addresses.push_back(address.to_v4());
} }
WSACleanup(); WSACleanup();
#else #else
ifaddrs* ifaddr; ifaddrs* ifaddr;
if (getifaddrs(&ifaddr) == -1) if (getifaddrs(&ifaddr) == -1)
BOOST_THROW_EXCEPTION(NoNetworking()); BOOST_THROW_EXCEPTION(NoNetworking());
for (auto ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) for (auto ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{ {
if (!ifa->ifa_addr || string(ifa->ifa_name) == "lo0") if (!ifa->ifa_addr || string(ifa->ifa_name) == "lo0")
continue; continue;
if (ifa->ifa_addr->sa_family == AF_INET) if (ifa->ifa_addr->sa_family == AF_INET)
{ {
in_addr addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr; in_addr addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
@ -102,12 +103,12 @@ std::vector<bi::address> Network::getInterfaceAddresses()
addresses.push_back(address); addresses.push_back(address);
} }
} }
if (ifaddr!=NULL) if (ifaddr!=NULL)
freeifaddrs(ifaddr); freeifaddrs(ifaddr);
#endif #endif
return std::move(addresses); return std::move(addresses);
} }
@ -134,7 +135,7 @@ int Network::tcp4Listen(bi::tcp::acceptor& _acceptor, unsigned short _listenPort
// both attempts failed // both attempts failed
cwarn << "Couldn't start accepting connections on host. Something very wrong with network?\n" << boost::current_exception_diagnostic_information(); cwarn << "Couldn't start accepting connections on host. Something very wrong with network?\n" << boost::current_exception_diagnostic_information();
} }
// first attempt failed // first attempt failed
_acceptor.close(); _acceptor.close();
continue; continue;
@ -146,7 +147,7 @@ int Network::tcp4Listen(bi::tcp::acceptor& _acceptor, unsigned short _listenPort
bi::tcp::endpoint Network::traverseNAT(std::vector<bi::address> const& _ifAddresses, unsigned short _listenPort, bi::address& o_upnpifaddr) bi::tcp::endpoint Network::traverseNAT(std::vector<bi::address> const& _ifAddresses, unsigned short _listenPort, bi::address& o_upnpifaddr)
{ {
asserts(_listenPort != 0); asserts(_listenPort != 0);
UPnP* upnp = nullptr; UPnP* upnp = nullptr;
try try
{ {
@ -154,7 +155,7 @@ bi::tcp::endpoint Network::traverseNAT(std::vector<bi::address> const& _ifAddres
} }
// let m_upnp continue as null - we handle it properly. // let m_upnp continue as null - we handle it properly.
catch (NoUPnPDevice) {} catch (NoUPnPDevice) {}
bi::tcp::endpoint upnpep; bi::tcp::endpoint upnpep;
if (upnp && upnp->isValid()) if (upnp && upnp->isValid())
{ {
@ -178,7 +179,7 @@ bi::tcp::endpoint Network::traverseNAT(std::vector<bi::address> const& _ifAddres
} }
else else
clog(NetWarn) << "Couldn't punch through NAT (or no NAT in place)."; clog(NetWarn) << "Couldn't punch through NAT (or no NAT in place).";
if (upnp) if (upnp)
delete upnp; delete upnp;
} }

96
libp2p/NodeTable.h

@ -1,16 +1,16 @@
/* /*
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/>.
*/ */
@ -23,7 +23,9 @@
#include <algorithm> #include <algorithm>
#include <deque> #include <deque>
#include <boost/integer/static_log2.hpp> #include <boost/integer/static_log2.hpp>
#include <libp2p/UDP.h> #include <libp2p/UDP.h>
#include "Common.h" #include "Common.h"
@ -54,7 +56,7 @@ class NodeTableEventHandler
friend class NodeTable; friend class NodeTable;
public: public:
virtual void processEvent(NodeId const& _n, NodeTableEventType const& _e) = 0; virtual void processEvent(NodeId const& _n, NodeTableEventType const& _e) = 0;
protected: protected:
/// Called by NodeTable on behalf of an implementation (Host) to process new events without blocking nodetable. /// Called by NodeTable on behalf of an implementation (Host) to process new events without blocking nodetable.
void processEvents() void processEvents()
@ -73,10 +75,10 @@ protected:
for (auto const& e: events) for (auto const& e: events)
processEvent(e.first, e.second); processEvent(e.first, e.second);
} }
/// Called by NodeTable to append event. /// Called by NodeTable to append event.
virtual void appendEvent(NodeId _n, NodeTableEventType _e) { Guard l(x_events); m_nodeEventHandler.push_back(_n); m_events[_n] = _e; } virtual void appendEvent(NodeId _n, NodeTableEventType _e) { Guard l(x_events); m_nodeEventHandler.push_back(_n); m_events[_n] = _e; }
Mutex x_events; Mutex x_events;
std::list<NodeId> m_nodeEventHandler; std::list<NodeId> m_nodeEventHandler;
std::map<NodeId, NodeTableEventType> m_events; std::map<NodeId, NodeTableEventType> m_events;
@ -84,16 +86,16 @@ protected:
class NodeTable; class NodeTable;
inline std::ostream& operator<<(std::ostream& _out, NodeTable const& _nodeTable); inline std::ostream& operator<<(std::ostream& _out, NodeTable const& _nodeTable);
/** /**
* NodeTable using modified kademlia for node discovery and preference. * NodeTable using modified kademlia for node discovery and preference.
* Node table requires an IO service, creates a socket for incoming * Node table requires an IO service, creates a socket for incoming
* UDP messages and implements a kademlia-like protocol. Node requests and * UDP messages and implements a kademlia-like protocol. Node requests and
* responses are used to build a node table which can be queried to * responses are used to build a node table which can be queried to
* obtain a list of potential nodes to connect to, and, passes events to * obtain a list of potential nodes to connect to, and, passes events to
* Host whenever a node is added or removed to/from the table. * Host whenever a node is added or removed to/from the table.
* *
* Thread-safety is ensured by modifying NodeEntry details via * Thread-safety is ensured by modifying NodeEntry details via
* shared_ptr replacement instead of mutating values. * shared_ptr replacement instead of mutating values.
* *
* NodeTable accepts a port for UDP and will listen to the port on all available * NodeTable accepts a port for UDP and will listen to the port on all available
@ -130,69 +132,69 @@ class NodeTable: UDPSocketEvents, public std::enable_shared_from_this<NodeTable>
using NodeSocket = UDPSocket<NodeTable, 1280>; using NodeSocket = UDPSocket<NodeTable, 1280>;
using TimePoint = std::chrono::steady_clock::time_point; using TimePoint = std::chrono::steady_clock::time_point;
using EvictionTimeout = std::pair<std::pair<NodeId, TimePoint>, NodeId>; ///< First NodeId may be evicted and replaced with second NodeId. using EvictionTimeout = std::pair<std::pair<NodeId, TimePoint>, NodeId>; ///< First NodeId may be evicted and replaced with second NodeId.
public: public:
NodeTable(ba::io_service& _io, KeyPair _alias, uint16_t _udpPort = 30303); NodeTable(ba::io_service& _io, KeyPair _alias, uint16_t _udpPort = 30303);
~NodeTable(); ~NodeTable();
/// Returns distance based on xor metric two node ids. Used by NodeEntry and NodeTable. /// Returns distance based on xor metric two node ids. Used by NodeEntry and NodeTable.
static unsigned distance(NodeId const& _a, NodeId const& _b) { u512 d = _a ^ _b; unsigned ret; for (ret = 0; d >>= 1; ++ret) {}; return ret; } static unsigned distance(NodeId const& _a, NodeId const& _b) { u512 d = _a ^ _b; unsigned ret; for (ret = 0; d >>= 1; ++ret) {}; return ret; }
/// Set event handler for NodeEntryAdded and NodeEntryRemoved events. /// Set event handler for NodeEntryAdded and NodeEntryRemoved events.
void setEventHandler(NodeTableEventHandler* _handler) { m_nodeEventHandler.reset(_handler); } void setEventHandler(NodeTableEventHandler* _handler) { m_nodeEventHandler.reset(_handler); }
/// Called by implementation which provided handler to process NodeEntryAdded/NodeEntryRemoved events. Events are coalesced by type whereby old events are ignored. /// Called by implementation which provided handler to process NodeEntryAdded/NodeEntryRemoved events. Events are coalesced by type whereby old events are ignored.
void processEvents(); void processEvents();
/// Add node. Node will be pinged if it's not already known. /// Add node. Node will be pinged if it's not already known.
std::shared_ptr<NodeEntry> addNode(Public const& _pubk, bi::udp::endpoint const& _udp, bi::tcp::endpoint const& _tcp); std::shared_ptr<NodeEntry> addNode(Public const& _pubk, bi::udp::endpoint const& _udp, bi::tcp::endpoint const& _tcp);
/// Add node. Node will be pinged if it's not already known. /// Add node. Node will be pinged if it's not already known.
std::shared_ptr<NodeEntry> addNode(Node const& _node); std::shared_ptr<NodeEntry> addNode(Node const& _node);
/// To be called when node table is empty. Runs node discovery with m_node.id as the target in order to populate node-table. /// To be called when node table is empty. Runs node discovery with m_node.id as the target in order to populate node-table.
void discover(); void discover();
/// Returns list of node ids active in node table. /// Returns list of node ids active in node table.
std::list<NodeId> nodes() const; std::list<NodeId> nodes() const;
/// Returns node count. /// Returns node count.
unsigned count() const { return m_nodes.size(); } unsigned count() const { return m_nodes.size(); }
/// Returns snapshot of table. /// Returns snapshot of table.
std::list<NodeEntry> snapshot() const; std::list<NodeEntry> snapshot() const;
/// Returns true if node id is in node table. /// Returns true if node id is in node table.
bool haveNode(NodeId const& _id) { Guard l(x_nodes); return m_nodes.count(_id) > 0; } bool haveNode(NodeId const& _id) { Guard l(x_nodes); return m_nodes.count(_id) > 0; }
/// Returns the Node to the corresponding node id or the empty Node if that id is not found. /// Returns the Node to the corresponding node id or the empty Node if that id is not found.
Node node(NodeId const& _id); Node node(NodeId const& _id);
#if defined(BOOST_AUTO_TEST_SUITE) || defined(_MSC_VER) // MSVC includes access specifier in symbol name #if defined(BOOST_AUTO_TEST_SUITE) || defined(_MSC_VER) // MSVC includes access specifier in symbol name
protected: protected:
#else #else
private: private:
#endif #endif
/// Constants for Kademlia, derived from address space. /// Constants for Kademlia, derived from address space.
static unsigned const s_addressByteSize = sizeof(NodeId); ///< Size of address type in bytes. static unsigned const s_addressByteSize = sizeof(NodeId); ///< Size of address type in bytes.
static unsigned const s_bits = 8 * s_addressByteSize; ///< Denoted by n in [Kademlia]. static unsigned const s_bits = 8 * s_addressByteSize; ///< Denoted by n in [Kademlia].
static unsigned const s_bins = s_bits - 1; ///< Size of m_state (excludes root, which is us). static unsigned const s_bins = s_bits - 1; ///< Size of m_state (excludes root, which is us).
static unsigned const s_maxSteps = boost::static_log2<s_bits>::value; ///< Max iterations of discovery. (discover) static unsigned const s_maxSteps = boost::static_log2<s_bits>::value; ///< Max iterations of discovery. (discover)
/// Chosen constants /// Chosen constants
static unsigned const s_bucketSize = 16; ///< Denoted by k in [Kademlia]. Number of nodes stored in each bucket. static unsigned const s_bucketSize = 16; ///< Denoted by k in [Kademlia]. Number of nodes stored in each bucket.
static unsigned const s_alpha = 3; ///< Denoted by \alpha in [Kademlia]. Number of concurrent FindNode requests. static unsigned const s_alpha = 3; ///< Denoted by \alpha in [Kademlia]. Number of concurrent FindNode requests.
/// Intervals /// Intervals
/* todo: replace boost::posix_time; change constants to upper camelcase */ /* todo: replace boost::posix_time; change constants to upper camelcase */
boost::posix_time::milliseconds const c_evictionCheckInterval = boost::posix_time::milliseconds(75); ///< Interval at which eviction timeouts are checked. boost::posix_time::milliseconds const c_evictionCheckInterval = boost::posix_time::milliseconds(75); ///< Interval at which eviction timeouts are checked.
std::chrono::milliseconds const c_reqTimeout = std::chrono::milliseconds(300); ///< How long to wait for requests (evict, find iterations). std::chrono::milliseconds const c_reqTimeout = std::chrono::milliseconds(300); ///< How long to wait for requests (evict, find iterations).
std::chrono::seconds const c_bucketRefresh = std::chrono::seconds(3600); ///< Refresh interval prevents bucket from becoming stale. [Kademlia] std::chrono::seconds const c_bucketRefresh = std::chrono::seconds(3600); ///< Refresh interval prevents bucket from becoming stale. [Kademlia]
struct NodeBucket struct NodeBucket
{ {
unsigned distance; unsigned distance;
@ -200,50 +202,50 @@ private:
std::list<std::weak_ptr<NodeEntry>> nodes; std::list<std::weak_ptr<NodeEntry>> nodes;
void touch() { modified = std::chrono::steady_clock::now(); } void touch() { modified = std::chrono::steady_clock::now(); }
}; };
/// Used to ping endpoint. /// Used to ping endpoint.
void ping(bi::udp::endpoint _to) const; void ping(bi::udp::endpoint _to) const;
/// Used ping known node. Used by node table when refreshing buckets and as part of eviction process (see evict). /// Used ping known node. Used by node table when refreshing buckets and as part of eviction process (see evict).
void ping(NodeEntry* _n) const; void ping(NodeEntry* _n) const;
/// Returns center node entry which describes this node and used with dist() to calculate xor metric for node table nodes. /// Returns center node entry which describes this node and used with dist() to calculate xor metric for node table nodes.
NodeEntry center() const { return NodeEntry(m_node, m_node.publicKey(), m_node.endpoint.udp); } NodeEntry center() const { return NodeEntry(m_node, m_node.publicKey(), m_node.endpoint.udp); }
/// Used by asynchronous operations to return NodeEntry which is active and managed by node table. /// Used by asynchronous operations to return NodeEntry which is active and managed by node table.
std::shared_ptr<NodeEntry> nodeEntry(NodeId _id); std::shared_ptr<NodeEntry> nodeEntry(NodeId _id);
/// Used to discovery nodes on network which are close to the given target. /// Used to discovery nodes on network which are close to the given target.
/// Sends s_alpha concurrent requests to nodes nearest to target, for nodes nearest to target, up to s_maxSteps rounds. /// Sends s_alpha concurrent requests to nodes nearest to target, for nodes nearest to target, up to s_maxSteps rounds.
void discover(NodeId _target, unsigned _round = 0, std::shared_ptr<std::set<std::shared_ptr<NodeEntry>>> _tried = std::shared_ptr<std::set<std::shared_ptr<NodeEntry>>>()); void discover(NodeId _target, unsigned _round = 0, std::shared_ptr<std::set<std::shared_ptr<NodeEntry>>> _tried = std::shared_ptr<std::set<std::shared_ptr<NodeEntry>>>());
/// Returns nodes from node table which are closest to target. /// Returns nodes from node table which are closest to target.
std::vector<std::shared_ptr<NodeEntry>> nearestNodeEntries(NodeId _target); std::vector<std::shared_ptr<NodeEntry>> nearestNodeEntries(NodeId _target);
/// Asynchronously drops _leastSeen node if it doesn't reply and adds _new node, otherwise _new node is thrown away. /// Asynchronously drops _leastSeen node if it doesn't reply and adds _new node, otherwise _new node is thrown away.
void evict(std::shared_ptr<NodeEntry> _leastSeen, std::shared_ptr<NodeEntry> _new); void evict(std::shared_ptr<NodeEntry> _leastSeen, std::shared_ptr<NodeEntry> _new);
/// Called whenever activity is received from an unknown node in order to maintain node table. /// Called whenever activity is received from an unknown node in order to maintain node table.
void noteActiveNode(Public const& _pubk, bi::udp::endpoint const& _endpoint); void noteActiveNode(Public const& _pubk, bi::udp::endpoint const& _endpoint);
/// Used to drop node when timeout occurs or when evict() result is to keep previous node. /// Used to drop node when timeout occurs or when evict() result is to keep previous node.
void dropNode(std::shared_ptr<NodeEntry> _n); void dropNode(std::shared_ptr<NodeEntry> _n);
/// Returns references to bucket which corresponds to distance of node id. /// Returns references to bucket which corresponds to distance of node id.
/// @warning Only use the return reference locked x_state mutex. /// @warning Only use the return reference locked x_state mutex.
// TODO p2p: Remove this method after removing offset-by-one functionality. // TODO p2p: Remove this method after removing offset-by-one functionality.
NodeBucket& bucket_UNSAFE(NodeEntry const* _n); NodeBucket& bucket_UNSAFE(NodeEntry const* _n);
/// General Network Events /// General Network Events
/// Called by m_socket when packet is received. /// Called by m_socket when packet is received.
void onReceived(UDPSocketFace*, bi::udp::endpoint const& _from, bytesConstRef _packet); void onReceived(UDPSocketFace*, bi::udp::endpoint const& _from, bytesConstRef _packet);
/// Called by m_socket when socket is disconnected. /// Called by m_socket when socket is disconnected.
void onDisconnected(UDPSocketFace*) {} void onDisconnected(UDPSocketFace*) {}
/// Tasks /// Tasks
/// Called by evict() to ensure eviction check is scheduled to run and terminates when no evictions remain. Asynchronous. /// Called by evict() to ensure eviction check is scheduled to run and terminates when no evictions remain. Asynchronous.
void doCheckEvictions(boost::system::error_code const& _ec); void doCheckEvictions(boost::system::error_code const& _ec);
@ -251,7 +253,7 @@ private:
void doRefreshBuckets(boost::system::error_code const& _ec); void doRefreshBuckets(boost::system::error_code const& _ec);
std::unique_ptr<NodeTableEventHandler> m_nodeEventHandler; ///< Event handler for node events. std::unique_ptr<NodeTableEventHandler> m_nodeEventHandler; ///< Event handler for node events.
Node m_node; ///< This node. Node m_node; ///< This node.
Secret m_secret; ///< This nodes secret key. Secret m_secret; ///< This nodes secret key.
@ -308,7 +310,7 @@ struct PingNode: RLPXDatagram<PingNode>
PingNode(bi::udp::endpoint _ep, std::string _src, uint16_t _srcPort, std::chrono::seconds _expiration = std::chrono::seconds(60)): RLPXDatagram<PingNode>(_ep), ipAddress(_src), port(_srcPort), expiration(futureFromEpoch(_expiration)) {} PingNode(bi::udp::endpoint _ep, std::string _src, uint16_t _srcPort, std::chrono::seconds _expiration = std::chrono::seconds(60)): RLPXDatagram<PingNode>(_ep), ipAddress(_src), port(_srcPort), expiration(futureFromEpoch(_expiration)) {}
static const uint8_t type = 1; static const uint8_t type = 1;
unsigned version = 1; unsigned version = 1;
std::string ipAddress; std::string ipAddress;
unsigned port; unsigned port;
@ -333,7 +335,7 @@ struct Pong: RLPXDatagram<Pong>
h256 echo; ///< MCD of PingNode h256 echo; ///< MCD of PingNode
unsigned expiration; unsigned expiration;
void streamRLP(RLPStream& _s) const { _s.appendList(2); _s << echo << expiration; } void streamRLP(RLPStream& _s) const { _s.appendList(2); _s << echo << expiration; }
void interpretRLP(bytesConstRef _bytes) { RLP r(_bytes); echo = (h256)r[0]; expiration = r[1].toInt<unsigned>(); } void interpretRLP(bytesConstRef _bytes) { RLP r(_bytes); echo = (h256)r[0]; expiration = r[1].toInt<unsigned>(); }
}; };
@ -357,10 +359,10 @@ struct FindNode: RLPXDatagram<FindNode>
FindNode(bi::udp::endpoint _ep, NodeId _target, std::chrono::seconds _expiration = std::chrono::seconds(30)): RLPXDatagram<FindNode>(_ep), target(_target), expiration(futureFromEpoch(_expiration)) {} FindNode(bi::udp::endpoint _ep, NodeId _target, std::chrono::seconds _expiration = std::chrono::seconds(30)): RLPXDatagram<FindNode>(_ep), target(_target), expiration(futureFromEpoch(_expiration)) {}
static const uint8_t type = 3; static const uint8_t type = 3;
h512 target; h512 target;
unsigned expiration; unsigned expiration;
void streamRLP(RLPStream& _s) const { _s.appendList(2); _s << target << expiration; } void streamRLP(RLPStream& _s) const { _s.appendList(2); _s << target << expiration; }
void interpretRLP(bytesConstRef _bytes) { RLP r(_bytes); target = r[0].toHash<h512>(); expiration = r[1].toInt<unsigned>(); } void interpretRLP(bytesConstRef _bytes) { RLP r(_bytes); target = r[0].toHash<h512>(); expiration = r[1].toInt<unsigned>(); }
}; };
@ -383,7 +385,7 @@ struct Neighbours: RLPXDatagram<Neighbours>
void streamRLP(RLPStream& _s) const { _s.appendList(3); _s << ipAddress << port << node; } void streamRLP(RLPStream& _s) const { _s.appendList(3); _s << ipAddress << port << node; }
void interpretRLP(RLP const& _r) { ipAddress = _r[0].toString(); port = _r[1].toInt<unsigned>(); node = h512(_r[2].toBytes()); } void interpretRLP(RLP const& _r) { ipAddress = _r[0].toString(); port = _r[1].toInt<unsigned>(); node = h512(_r[2].toBytes()); }
}; };
Neighbours(bi::udp::endpoint _ep): RLPXDatagram<Neighbours>(_ep), expiration(futureFromEpoch(std::chrono::seconds(30))) {} Neighbours(bi::udp::endpoint _ep): RLPXDatagram<Neighbours>(_ep), expiration(futureFromEpoch(std::chrono::seconds(30))) {}
Neighbours(bi::udp::endpoint _to, std::vector<std::shared_ptr<NodeEntry>> const& _nearest, unsigned _offset = 0, unsigned _limit = 0): RLPXDatagram<Neighbours>(_to), expiration(futureFromEpoch(std::chrono::seconds(30))) Neighbours(bi::udp::endpoint _to, std::vector<std::shared_ptr<NodeEntry>> const& _nearest, unsigned _offset = 0, unsigned _limit = 0): RLPXDatagram<Neighbours>(_to), expiration(futureFromEpoch(std::chrono::seconds(30)))
{ {
@ -397,7 +399,7 @@ struct Neighbours: RLPXDatagram<Neighbours>
nodes.push_back(node); nodes.push_back(node);
} }
} }
static const uint8_t type = 4; static const uint8_t type = 4;
std::vector<Node> nodes; std::vector<Node> nodes;
unsigned expiration = 1; unsigned expiration = 1;

3
libp2p/Session.h

@ -27,6 +27,7 @@
#include <set> #include <set>
#include <memory> #include <memory>
#include <utility> #include <utility>
#include <libdevcore/Common.h> #include <libdevcore/Common.h>
#include <libdevcore/RLP.h> #include <libdevcore/RLP.h>
#include <libdevcore/RangeMask.h> #include <libdevcore/RangeMask.h>
@ -112,7 +113,7 @@ private:
bool m_dropped = false; ///< If true, we've already divested ourselves of this peer. We're just waiting for the reads & writes to fail before the shared_ptr goes OOS and the destructor kicks in. bool m_dropped = false; ///< If true, we've already divested ourselves of this peer. We're just waiting for the reads & writes to fail before the shared_ptr goes OOS and the destructor kicks in.
PeerSessionInfo m_info; ///< Dynamic information about this peer. PeerSessionInfo m_info; ///< Dynamic information about this peer.
bool m_theyRequestedNodes = false; ///< Has the peer requested nodes from us without receiveing an answer from us? bool m_theyRequestedNodes = false; ///< Has the peer requested nodes from us without receiveing an answer from us?
bool m_weRequestedNodes = false; ///< Have we requested nodes from the peer and not received an answer yet? bool m_weRequestedNodes = false; ///< Have we requested nodes from the peer and not received an answer yet?

53
libp2p/UDP.h

@ -1,16 +1,16 @@
/* /*
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/>.
*/ */
@ -26,6 +26,7 @@
#include <vector> #include <vector>
#include <deque> #include <deque>
#include <array> #include <array>
#include <libdevcore/Guards.h> #include <libdevcore/Guards.h>
#include <libdevcrypto/Common.h> #include <libdevcrypto/Common.h>
#include <libdevcrypto/SHA3.h> #include <libdevcrypto/SHA3.h>
@ -49,7 +50,7 @@ public:
UDPDatagram(bi::udp::endpoint const& _ep): locus(_ep) {} UDPDatagram(bi::udp::endpoint const& _ep): locus(_ep) {}
UDPDatagram(bi::udp::endpoint const& _ep, bytes _data): data(_data), locus(_ep) {} UDPDatagram(bi::udp::endpoint const& _ep, bytes _data): data(_data), locus(_ep) {}
bi::udp::endpoint const& endpoint() const { return locus; } bi::udp::endpoint const& endpoint() const { return locus; }
bytes data; bytes data;
protected: protected:
bi::udp::endpoint locus; bi::udp::endpoint locus;
@ -63,7 +64,7 @@ struct RLPXDatagramFace: public UDPDatagram
static uint64_t futureFromEpoch(std::chrono::milliseconds _ms) { return std::chrono::duration_cast<std::chrono::seconds>((std::chrono::system_clock::now() + _ms).time_since_epoch()).count(); } static uint64_t futureFromEpoch(std::chrono::milliseconds _ms) { return std::chrono::duration_cast<std::chrono::seconds>((std::chrono::system_clock::now() + _ms).time_since_epoch()).count(); }
static uint64_t futureFromEpoch(std::chrono::seconds _sec) { return std::chrono::duration_cast<std::chrono::seconds>((std::chrono::system_clock::now() + _sec).time_since_epoch()).count(); } static uint64_t futureFromEpoch(std::chrono::seconds _sec) { return std::chrono::duration_cast<std::chrono::seconds>((std::chrono::system_clock::now() + _sec).time_since_epoch()).count(); }
static Public authenticate(bytesConstRef _sig, bytesConstRef _rlp); static Public authenticate(bytesConstRef _sig, bytesConstRef _rlp);
virtual uint8_t packetType() = 0; virtual uint8_t packetType() = 0;
RLPXDatagramFace(bi::udp::endpoint const& _ep): UDPDatagram(_ep) {} RLPXDatagramFace(bi::udp::endpoint const& _ep): UDPDatagram(_ep) {}
virtual h256 sign(Secret const& _from); virtual h256 sign(Secret const& _from);
@ -97,7 +98,7 @@ struct UDPSocketEvents
virtual void onDisconnected(UDPSocketFace*) {}; virtual void onDisconnected(UDPSocketFace*) {};
virtual void onReceived(UDPSocketFace*, bi::udp::endpoint const& _from, bytesConstRef _packetData) = 0; virtual void onReceived(UDPSocketFace*, bi::udp::endpoint const& _from, bytesConstRef _packetData) = 0;
}; };
/** /**
* @brief UDP Interface * @brief UDP Interface
* Handler must implement UDPSocketEvents. * Handler must implement UDPSocketEvents.
@ -111,7 +112,7 @@ class UDPSocket: UDPSocketFace, public std::enable_shared_from_this<UDPSocket<Ha
public: public:
enum { maxDatagramSize = MaxDatagramSize }; enum { maxDatagramSize = MaxDatagramSize };
static_assert(maxDatagramSize < 65507, "UDP datagrams cannot be larger than 65507 bytes"); static_assert(maxDatagramSize < 65507, "UDP datagrams cannot be larger than 65507 bytes");
UDPSocket(ba::io_service& _io, UDPSocketEvents& _host, unsigned _port): m_host(_host), m_endpoint(bi::udp::v4(), _port), m_socket(_io) { m_started.store(false); m_closed.store(true); }; UDPSocket(ba::io_service& _io, UDPSocketEvents& _host, unsigned _port): m_host(_host), m_endpoint(bi::udp::v4(), _port), m_socket(_io) { m_started.store(false); m_closed.store(true); };
virtual ~UDPSocket() { disconnect(); } virtual ~UDPSocket() { disconnect(); }
@ -120,32 +121,32 @@ public:
/// Send datagram. /// Send datagram.
bool send(UDPDatagram const& _datagram); bool send(UDPDatagram const& _datagram);
/// Returns if socket is open. /// Returns if socket is open.
bool isOpen() { return !m_closed; } bool isOpen() { return !m_closed; }
/// Disconnect socket. /// Disconnect socket.
void disconnect() { disconnectWithError(boost::asio::error::connection_reset); } void disconnect() { disconnectWithError(boost::asio::error::connection_reset); }
protected: protected:
void doRead(); void doRead();
void doWrite(); void doWrite();
void disconnectWithError(boost::system::error_code _ec); void disconnectWithError(boost::system::error_code _ec);
std::atomic<bool> m_started; ///< Atomically ensure connection is started once. Start cannot occur unless m_started is false. Managed by start and disconnectWithError. std::atomic<bool> m_started; ///< Atomically ensure connection is started once. Start cannot occur unless m_started is false. Managed by start and disconnectWithError.
std::atomic<bool> m_closed; ///< Connection availability. std::atomic<bool> m_closed; ///< Connection availability.
UDPSocketEvents& m_host; ///< Interface which owns this socket. UDPSocketEvents& m_host; ///< Interface which owns this socket.
bi::udp::endpoint m_endpoint; ///< Endpoint which we listen to. bi::udp::endpoint m_endpoint; ///< Endpoint which we listen to.
Mutex x_sendQ; Mutex x_sendQ;
std::deque<UDPDatagram> m_sendQ; ///< Queue for egress data. std::deque<UDPDatagram> m_sendQ; ///< Queue for egress data.
std::array<byte, maxDatagramSize> m_recvData; ///< Buffer for ingress data. std::array<byte, maxDatagramSize> m_recvData; ///< Buffer for ingress data.
bi::udp::endpoint m_recvEndpoint; ///< Endpoint data was received from. bi::udp::endpoint m_recvEndpoint; ///< Endpoint data was received from.
bi::udp::socket m_socket; ///< Boost asio udp socket. bi::udp::socket m_socket; ///< Boost asio udp socket.
Mutex x_socketError; ///< Mutex for error which can be set from host or IO thread. Mutex x_socketError; ///< Mutex for error which can be set from host or IO thread.
boost::system::error_code m_socketError; ///< Set when shut down due to error. boost::system::error_code m_socketError; ///< Set when shut down due to error.
}; };
@ -156,29 +157,29 @@ void UDPSocket<Handler, MaxDatagramSize>::connect()
bool expect = false; bool expect = false;
if (!m_started.compare_exchange_strong(expect, true)) if (!m_started.compare_exchange_strong(expect, true))
return; return;
m_socket.open(bi::udp::v4()); m_socket.open(bi::udp::v4());
m_socket.bind(m_endpoint); m_socket.bind(m_endpoint);
// clear write queue so reconnect doesn't send stale messages // clear write queue so reconnect doesn't send stale messages
Guard l(x_sendQ); Guard l(x_sendQ);
m_sendQ.clear(); m_sendQ.clear();
m_closed = false; m_closed = false;
doRead(); doRead();
} }
template <typename Handler, unsigned MaxDatagramSize> template <typename Handler, unsigned MaxDatagramSize>
bool UDPSocket<Handler, MaxDatagramSize>::send(UDPDatagram const& _datagram) bool UDPSocket<Handler, MaxDatagramSize>::send(UDPDatagram const& _datagram)
{ {
if (m_closed) if (m_closed)
return false; return false;
Guard l(x_sendQ); Guard l(x_sendQ);
m_sendQ.push_back(_datagram); m_sendQ.push_back(_datagram);
if (m_sendQ.size() == 1) if (m_sendQ.size() == 1)
doWrite(); doWrite();
return true; return true;
} }
@ -187,7 +188,7 @@ void UDPSocket<Handler, MaxDatagramSize>::doRead()
{ {
if (m_closed) if (m_closed)
return; return;
auto self(UDPSocket<Handler, MaxDatagramSize>::shared_from_this()); auto self(UDPSocket<Handler, MaxDatagramSize>::shared_from_this());
m_socket.async_receive_from(boost::asio::buffer(m_recvData), m_recvEndpoint, [this, self](boost::system::error_code _ec, size_t _len) m_socket.async_receive_from(boost::asio::buffer(m_recvData), m_recvEndpoint, [this, self](boost::system::error_code _ec, size_t _len)
{ {
@ -199,13 +200,13 @@ void UDPSocket<Handler, MaxDatagramSize>::doRead()
doRead(); doRead();
}); });
} }
template <typename Handler, unsigned MaxDatagramSize> template <typename Handler, unsigned MaxDatagramSize>
void UDPSocket<Handler, MaxDatagramSize>::doWrite() void UDPSocket<Handler, MaxDatagramSize>::doWrite()
{ {
if (m_closed) if (m_closed)
return; return;
const UDPDatagram& datagram = m_sendQ[0]; const UDPDatagram& datagram = m_sendQ[0];
auto self(UDPSocket<Handler, MaxDatagramSize>::shared_from_this()); auto self(UDPSocket<Handler, MaxDatagramSize>::shared_from_this());
m_socket.async_send_to(boost::asio::buffer(datagram.data), datagram.endpoint(), [this, self](boost::system::error_code _ec, std::size_t) m_socket.async_send_to(boost::asio::buffer(datagram.data), datagram.endpoint(), [this, self](boost::system::error_code _ec, std::size_t)
@ -244,11 +245,11 @@ void UDPSocket<Handler, MaxDatagramSize>::disconnectWithError(boost::system::err
bool expected = true; bool expected = true;
if (!m_started.compare_exchange_strong(expected, false)) if (!m_started.compare_exchange_strong(expected, false))
return; return;
// set m_closed to true to prevent undeliverable egress messages // set m_closed to true to prevent undeliverable egress messages
bool wasClosed = m_closed; bool wasClosed = m_closed;
m_closed = true; m_closed = true;
// close sockets // close sockets
boost::system::error_code ec; boost::system::error_code ec;
m_socket.shutdown(bi::udp::socket::shutdown_both, ec); m_socket.shutdown(bi::udp::socket::shutdown_both, ec);
@ -260,6 +261,6 @@ void UDPSocket<Handler, MaxDatagramSize>::disconnectWithError(boost::system::err
m_host.onDisconnected(this); m_host.onDisconnected(this);
} }
} }
} }

2
libserpent/CMakeLists.txt

@ -27,6 +27,6 @@ target_link_libraries(${EXECUTABLE} lll)
target_link_libraries(${EXECUTABLE} evmcore) target_link_libraries(${EXECUTABLE} evmcore)
target_link_libraries(${EXECUTABLE} devcore) target_link_libraries(${EXECUTABLE} devcore)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

2
libsolidity/CMakeLists.txt

@ -30,6 +30,6 @@ target_link_libraries(${EXECUTABLE} evmcore)
target_link_libraries(${EXECUTABLE} devcore) target_link_libraries(${EXECUTABLE} devcore)
target_link_libraries(${EXECUTABLE} devcrypto) target_link_libraries(${EXECUTABLE} devcrypto)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

1
libsolidity/Token.h

@ -46,6 +46,7 @@
#include <libdevcore/Log.h> #include <libdevcore/Log.h>
#include <libsolidity/Utils.h> #include <libsolidity/Utils.h>
#include <libsolidity/Exceptions.h> #include <libsolidity/Exceptions.h>
#include <libdevcore/UndefMacros.h>
namespace dev namespace dev
{ {

2
libsolidity/Types.h

@ -30,6 +30,7 @@
#include <libsolidity/Exceptions.h> #include <libsolidity/Exceptions.h>
#include <libsolidity/ASTForward.h> #include <libsolidity/ASTForward.h>
#include <libsolidity/Token.h> #include <libsolidity/Token.h>
#include <libdevcore/UndefMacros.h>
namespace dev namespace dev
{ {
@ -67,7 +68,6 @@ private:
MemberMap m_memberTypes; MemberMap m_memberTypes;
}; };
/** /**
* Abstract base class that forms the root of the type hierarchy. * Abstract base class that forms the root of the type hierarchy.
*/ */

3
libweb3jsonrpc/CMakeLists.txt

@ -14,6 +14,7 @@ include_directories(BEFORE ..)
include_directories(${MHD_INCLUDE_DIRS}) include_directories(${MHD_INCLUDE_DIRS})
include_directories(${JSON_RPC_CPP_INCLUDE_DIRS}) include_directories(${JSON_RPC_CPP_INCLUDE_DIRS})
include_directories(${LEVELDB_INCLUDE_DIRS}) include_directories(${LEVELDB_INCLUDE_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
set(EXECUTABLE web3jsonrpc) set(EXECUTABLE web3jsonrpc)
@ -52,7 +53,7 @@ if (ETH_JSON_RPC_STUB)
add_dependencies(${EXECUTABLE} jsonrpcstub) add_dependencies(${EXECUTABLE} jsonrpcstub)
endif() endif()
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

3
libweb3jsonrpc/WebThreeStubServer.cpp

@ -21,7 +21,10 @@
* @date 2014 * @date 2014
*/ */
// Make sure boost/asio.hpp is included before windows.h.
#include <boost/asio.hpp>
#include <boost/filesystem.hpp> #include <boost/filesystem.hpp>
#include <libwebthree/WebThree.h> #include <libwebthree/WebThree.h>
#include <libdevcrypto/FileSystem.h> #include <libdevcrypto/FileSystem.h>
#include "WebThreeStubServer.h" #include "WebThreeStubServer.h"

9
libweb3jsonrpc/WebThreeStubServerBase.cpp

@ -21,6 +21,9 @@
* @date 2014 * @date 2014
*/ */
// Make sure boost/asio.hpp is included before windows.h.
#include <boost/asio.hpp>
#include <libsolidity/CompilerStack.h> #include <libsolidity/CompilerStack.h>
#include <libsolidity/Scanner.h> #include <libsolidity/Scanner.h>
#include <libsolidity/SourceReferenceFormatter.h> #include <libsolidity/SourceReferenceFormatter.h>
@ -89,7 +92,7 @@ static Json::Value toJson(dev::eth::TransactionSkeleton const& _t)
static Json::Value toJson(dev::eth::LocalisedLogEntry const& _e) static Json::Value toJson(dev::eth::LocalisedLogEntry const& _e)
{ {
Json::Value res; Json::Value res;
res["data"] = jsFromBinary(_e.data); res["data"] = jsFromBinary(_e.data);
res["address"] = toJS(_e.address); res["address"] = toJS(_e.address);
for (auto const& t: _e.topics) for (auto const& t: _e.topics)
@ -579,7 +582,7 @@ bool WebThreeStubServerBase::shh_post(Json::Value const& _json)
// TODO: insert validification hook here. // TODO: insert validification hook here.
from = m_ids[m.from()]; from = m_ids[m.from()];
} }
face()->inject(toSealed(_json, m, from)); face()->inject(toSealed(_json, m, from));
return true; return true;
} }
@ -647,7 +650,7 @@ Json::Value WebThreeStubServerBase::shh_changed(int _id)
continue; continue;
ret.append(toJson(h, e, m)); ret.append(toJson(h, e, m));
} }
return ret; return ret;
} }

3
libwebthree/CMakeLists.txt

@ -13,6 +13,7 @@ aux_source_directory(. SRC_LIST)
include_directories(BEFORE ..) include_directories(BEFORE ..)
include_directories(${LEVELDB_INCLUDE_DIRS}) include_directories(${LEVELDB_INCLUDE_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
set(EXECUTABLE webthree) set(EXECUTABLE webthree)
@ -35,6 +36,6 @@ target_link_libraries(${EXECUTABLE} ethcore)
target_link_libraries(${EXECUTABLE} devcrypto) target_link_libraries(${EXECUTABLE} devcrypto)
target_link_libraries(${EXECUTABLE} secp256k1) target_link_libraries(${EXECUTABLE} secp256k1)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

2
libwebthree/WebThree.cpp

@ -23,7 +23,9 @@
#include <chrono> #include <chrono>
#include <thread> #include <thread>
#include <boost/filesystem.hpp> #include <boost/filesystem.hpp>
#include <libdevcore/Log.h> #include <libdevcore/Log.h>
#include <libp2p/Host.h> #include <libp2p/Host.h>
#include <libethereum/Defaults.h> #include <libethereum/Defaults.h>

6
libwebthree/WebThree.h

@ -25,7 +25,11 @@
#include <mutex> #include <mutex>
#include <list> #include <list>
#include <atomic> #include <atomic>
// Make sure boost/asio.hpp is included before windows.h.
#include <boost/asio.hpp>
#include <boost/utility.hpp> #include <boost/utility.hpp>
#include <libdevcore/Common.h> #include <libdevcore/Common.h>
#include <libdevcore/CommonIO.h> #include <libdevcore/CommonIO.h>
#include <libdevcore/Guards.h> #include <libdevcore/Guards.h>
@ -160,7 +164,7 @@ public:
/// Stop the network subsystem. /// Stop the network subsystem.
void stopNetwork() override { m_net.stop(); } void stopNetwork() override { m_net.stop(); }
/// Is network working? there may not be any peers yet. /// Is network working? there may not be any peers yet.
bool isNetworkStarted() const override { return m_net.isStarted(); } bool isNetworkStarted() const override { return m_net.isStarted(); }

3
libwhisper/CMakeLists.txt

@ -13,6 +13,7 @@ aux_source_directory(. SRC_LIST)
include_directories(BEFORE ..) include_directories(BEFORE ..)
include_directories(${LEVELDB_INCLUDE_DIRS}) include_directories(${LEVELDB_INCLUDE_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
set(EXECUTABLE whisper) set(EXECUTABLE whisper)
@ -32,5 +33,5 @@ target_link_libraries(${EXECUTABLE} devcore)
target_link_libraries(${EXECUTABLE} p2p) target_link_libraries(${EXECUTABLE} p2p)
target_link_libraries(${EXECUTABLE} secp256k1) target_link_libraries(${EXECUTABLE} secp256k1)
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

1
libwhisper/Common.h

@ -23,6 +23,7 @@
#include <string> #include <string>
#include <chrono> #include <chrono>
#include <libdevcore/Common.h> #include <libdevcore/Common.h>
#include <libdevcore/Log.h> #include <libdevcore/Log.h>
#include <libdevcore/RLP.h> #include <libdevcore/RLP.h>

1
libwhisper/Interface.h

@ -26,6 +26,7 @@
#include <set> #include <set>
#include <memory> #include <memory>
#include <utility> #include <utility>
#include <libdevcore/RLP.h> #include <libdevcore/RLP.h>
#include <libdevcore/Guards.h> #include <libdevcore/Guards.h>
#include <libdevcrypto/SHA3.h> #include <libdevcrypto/SHA3.h>

1
libwhisper/Message.h

@ -26,6 +26,7 @@
#include <set> #include <set>
#include <memory> #include <memory>
#include <utility> #include <utility>
#include <libdevcore/RLP.h> #include <libdevcore/RLP.h>
#include <libdevcore/Guards.h> #include <libdevcore/Guards.h>
#include <libdevcrypto/Common.h> #include <libdevcrypto/Common.h>

1
libwhisper/WhisperHost.h

@ -26,6 +26,7 @@
#include <set> #include <set>
#include <memory> #include <memory>
#include <utility> #include <utility>
#include <libdevcore/RLP.h> #include <libdevcore/RLP.h>
#include <libdevcore/Worker.h> #include <libdevcore/Worker.h>
#include <libdevcore/Guards.h> #include <libdevcore/Guards.h>

1
libwhisper/WhisperPeer.h

@ -26,6 +26,7 @@
#include <set> #include <set>
#include <memory> #include <memory>
#include <utility> #include <utility>
#include <libdevcore/RLP.h> #include <libdevcore/RLP.h>
#include <libdevcore/Guards.h> #include <libdevcore/Guards.h>
#include <libdevcrypto/SHA3.h> #include <libdevcrypto/SHA3.h>

1
mix/CMakeLists.txt

@ -12,6 +12,7 @@ set(CMAKE_INCLUDE_CURRENT_DIR ON)
aux_source_directory(. SRC_LIST) aux_source_directory(. SRC_LIST)
include_directories(BEFORE ${JSONCPP_INCLUDE_DIRS}) include_directories(BEFORE ${JSONCPP_INCLUDE_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
include_directories(BEFORE ..) include_directories(BEFORE ..)
find_package (Qt5WebEngine QUIET) find_package (Qt5WebEngine QUIET)

3
mix/ClientModel.cpp

@ -18,6 +18,9 @@
* Ethereum IDE client. * Ethereum IDE client.
*/ */
// Make sure boost/asio.hpp is included before windows.h.
#include <boost/asio.hpp>
#include <QtConcurrent/QtConcurrent> #include <QtConcurrent/QtConcurrent>
#include <QDebug> #include <QDebug>
#include <QQmlContext> #include <QQmlContext>

3
mix/DebuggingStateWrapper.h

@ -22,6 +22,9 @@
#pragma once #pragma once
// Make sure boost/asio.hpp is included before windows.h.
#include <boost/asio.hpp>
#include <QStringList> #include <QStringList>
#include <QMap> #include <QMap>
#include <libdevcore/Common.h> #include <libdevcore/Common.h>

3
mix/Extension.cpp

@ -17,13 +17,16 @@
* Ethereum IDE client. * Ethereum IDE client.
*/ */
#include <QMessageBox> #include <QMessageBox>
#include <QDebug> #include <QDebug>
#include <QQmlApplicationEngine> #include <QQmlApplicationEngine>
#include <libevm/VM.h> #include <libevm/VM.h>
#include <libwebthree/WebThree.h> #include <libwebthree/WebThree.h>
#include "Extension.h" #include "Extension.h"
#include "AppContext.h" #include "AppContext.h"
using namespace dev; using namespace dev;
using namespace dev::mix; using namespace dev::mix;

1
mix/QContractDefinition.cpp

@ -20,6 +20,7 @@
*/ */
#include <QObject> #include <QObject>
#include <libsolidity/CompilerStack.h> #include <libsolidity/CompilerStack.h>
#include <libsolidity/AST.h> #include <libsolidity/AST.h>
#include <libsolidity/Scanner.h> #include <libsolidity/Scanner.h>

1
neth/CMakeLists.txt

@ -5,6 +5,7 @@ aux_source_directory(. SRC_LIST)
include_directories(BEFORE ..) include_directories(BEFORE ..)
include_directories(${JSON_RPC_CPP_INCLUDE_DIRS}) include_directories(${JSON_RPC_CPP_INCLUDE_DIRS})
include_directories(${LEVELDB_INCLUDE_DIRS}) include_directories(${LEVELDB_INCLUDE_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
set(EXECUTABLE neth) set(EXECUTABLE neth)

2
neth/main.cpp

@ -25,8 +25,10 @@
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#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>
#include <libdevcrypto/FileSystem.h> #include <libdevcrypto/FileSystem.h>
#include <libevmcore/Instruction.h> #include <libevmcore/Instruction.h>
#include <libethereum/All.h> #include <libethereum/All.h>

14
secp256k1/CMakeLists.txt

@ -21,6 +21,18 @@ if (APPLE OR UNIX)
endif() endif()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -DUSE_FIELD_GMP -DUSE_NUM_GMP -DUSE_FIELD_INV_NUM") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -DUSE_FIELD_GMP -DUSE_NUM_GMP -DUSE_FIELD_INV_NUM")
target_link_libraries(${EXECUTABLE} ${GMP_LIBRARIES}) target_link_libraries(${EXECUTABLE} ${GMP_LIBRARIES})
elseif (CMAKE_COMPILER_IS_MINGW)
include_directories(${Boost_INCLUDE_DIRS})
if (ETH_STATIC)
add_library(${EXECUTABLE} STATIC ${EXECUTABLE}.c field_5x52_asm.asm)
else()
add_library(${EXECUTABLE} SHARED ${EXECUTABLE}.c field_5x52_asm.asm)
endif()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -W -Wall -Wextra -Wcast-align -Wnested-externs -Wshadow -Wstrict-prototypes -Wno-unused-function -DUSE_FIELD_GMP -DUSE_NUM_GMP -DUSE_FIELD_INV_NUM")
target_link_libraries(${EXECUTABLE} ${GMP_LIBRARIES})
else() else()
include_directories(${Boost_INCLUDE_DIRS}) include_directories(${Boost_INCLUDE_DIRS})
@ -36,5 +48,5 @@ else()
endif() endif()
install( TARGETS ${EXECUTABLE} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) install( TARGETS ${EXECUTABLE} RUNTIME DESTINATION bin ARCHIVE DESTINATION lib LIBRARY DESTINATION lib )
install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} ) install( FILES ${HEADERS} DESTINATION include/${EXECUTABLE} )

2
test/TestHelper.cpp

@ -23,7 +23,9 @@
#include <thread> #include <thread>
#include <chrono> #include <chrono>
#include <boost/filesystem/path.hpp> #include <boost/filesystem/path.hpp>
#include <libethereum/Client.h> #include <libethereum/Client.h>
#include <liblll/Compiler.h> #include <liblll/Compiler.h>
#include <libevm/VMFactory.h> #include <libevm/VMFactory.h>

2
test/TestHelper.h

@ -22,7 +22,9 @@
#pragma once #pragma once
#include <functional> #include <functional>
#include <boost/test/unit_test.hpp> #include <boost/test/unit_test.hpp>
#include "JsonSpiritHeaders.h" #include "JsonSpiritHeaders.h"
#include <libethereum/State.h> #include <libethereum/State.h>
#include <libevm/ExtVMFace.h> #include <libevm/ExtVMFace.h>

2
test/createRandomTest.cpp

@ -23,8 +23,10 @@
#include <string> #include <string>
#include <iostream> #include <iostream>
#include <chrono> #include <chrono>
#include <boost/random.hpp> #include <boost/random.hpp>
#include <boost/filesystem/path.hpp> #include <boost/filesystem/path.hpp>
#pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-parameter"
#include <json_spirit/json_spirit.h> #include <json_spirit/json_spirit.h>
#include <json_spirit/json_spirit_reader_template.h> #include <json_spirit/json_spirit_reader_template.h>

1
test/fork.cpp

@ -22,6 +22,7 @@
#include <boost/test/unit_test.hpp> #include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp> #include <boost/filesystem/operations.hpp>
#include <libethereum/Client.h> #include <libethereum/Client.h>
#include <libethereum/CanonBlockChain.h> #include <libethereum/CanonBlockChain.h>
#include <libethereum/EthereumHost.h> #include <libethereum/EthereumHost.h>

6
test/genesis.cpp

@ -22,10 +22,12 @@
#include <fstream> #include <fstream>
#include <random> #include <random>
#include <boost/test/unit_test.hpp>
#include "JsonSpiritHeaders.h" #include "JsonSpiritHeaders.h"
#include <libdevcore/CommonIO.h> #include <libdevcore/CommonIO.h>
#include <libethereum/CanonBlockChain.h> #include <libethereum/CanonBlockChain.h>
#include <boost/test/unit_test.hpp>
#include "TestHelper.h" #include "TestHelper.h"
using namespace std; using namespace std;
@ -40,7 +42,7 @@ BOOST_AUTO_TEST_CASE(emptySHA3Types)
{ {
h256 emptyListSHA3(fromHex("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347")); h256 emptyListSHA3(fromHex("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"));
BOOST_REQUIRE_EQUAL(emptyListSHA3, EmptyListSHA3); BOOST_REQUIRE_EQUAL(emptyListSHA3, EmptyListSHA3);
h256 emptySHA3(fromHex("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")); h256 emptySHA3(fromHex("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"));
BOOST_REQUIRE_EQUAL(emptySHA3, EmptySHA3); BOOST_REQUIRE_EQUAL(emptySHA3, EmptySHA3);
} }

8
test/hexPrefix.cpp

@ -21,11 +21,13 @@
*/ */
#include <fstream> #include <fstream>
#include <boost/test/unit_test.hpp>
#include "JsonSpiritHeaders.h" #include "JsonSpiritHeaders.h"
#include <libdevcore/Log.h> #include <libdevcore/Log.h>
#include <libdevcore/CommonIO.h> #include <libdevcore/CommonIO.h>
#include <libdevcrypto/TrieCommon.h> #include <libdevcrypto/TrieCommon.h>
#include <boost/test/unit_test.hpp>
#include "TestHelper.h" #include "TestHelper.h"
using namespace std; using namespace std;
@ -53,8 +55,8 @@ BOOST_AUTO_TEST_CASE(hexPrefix_test)
for (auto& i: o["seq"].get_array()) for (auto& i: o["seq"].get_array())
v.push_back((byte)i.get_int()); v.push_back((byte)i.get_int());
auto e = hexPrefixEncode(v, o["term"].get_bool()); auto e = hexPrefixEncode(v, o["term"].get_bool());
BOOST_REQUIRE( ! o["out"].is_null() ); BOOST_REQUIRE( ! o["out"].is_null() );
BOOST_CHECK( o["out"].get_str() == toHex(e) ); BOOST_CHECK( o["out"].get_str() == toHex(e) );
} }
} }

37
test/net.cpp

@ -20,6 +20,7 @@
*/ */
#include <boost/test/unit_test.hpp> #include <boost/test/unit_test.hpp>
#include <libdevcore/Worker.h> #include <libdevcore/Worker.h>
#include <libdevcrypto/Common.h> #include <libdevcrypto/Common.h>
#include <libp2p/UDP.h> #include <libp2p/UDP.h>
@ -43,7 +44,7 @@ public:
void start() { startWorking(); } void start() { startWorking(); }
void doWork() { m_io.run(); } void doWork() { m_io.run(); }
void doneWorking() { m_io.reset(); m_io.poll(); m_io.reset(); } void doneWorking() { m_io.reset(); m_io.poll(); m_io.reset(); }
protected: protected:
ba::io_service m_io; ba::io_service m_io;
}; };
@ -52,23 +53,23 @@ struct TestNodeTable: public NodeTable
{ {
/// Constructor /// Constructor
TestNodeTable(ba::io_service& _io, KeyPair _alias, uint16_t _port = 30300): NodeTable(_io, _alias, _port) {} TestNodeTable(ba::io_service& _io, KeyPair _alias, uint16_t _port = 30300): NodeTable(_io, _alias, _port) {}
static std::vector<std::pair<KeyPair,unsigned>> createTestNodes(unsigned _count) static std::vector<std::pair<KeyPair,unsigned>> createTestNodes(unsigned _count)
{ {
std::vector<std::pair<KeyPair,unsigned>> ret; std::vector<std::pair<KeyPair,unsigned>> ret;
asserts(_count < 1000); asserts(_count < 1000);
static uint16_t s_basePort = 30500; static uint16_t s_basePort = 30500;
ret.clear(); ret.clear();
for (unsigned i = 0; i < _count; i++) for (unsigned i = 0; i < _count; i++)
{ {
KeyPair k = KeyPair::create(); KeyPair k = KeyPair::create();
ret.push_back(make_pair(k,s_basePort+i)); ret.push_back(make_pair(k,s_basePort+i));
} }
return std::move(ret); return std::move(ret);
} }
void pingTestNodes(std::vector<std::pair<KeyPair,unsigned>> const& _testNodes) void pingTestNodes(std::vector<std::pair<KeyPair,unsigned>> const& _testNodes)
{ {
bi::address ourIp = bi::address::from_string("127.0.0.1"); bi::address ourIp = bi::address::from_string("127.0.0.1");
@ -78,7 +79,7 @@ struct TestNodeTable: public NodeTable
this_thread::sleep_for(chrono::milliseconds(2)); this_thread::sleep_for(chrono::milliseconds(2));
} }
} }
void populateTestNodes(std::vector<std::pair<KeyPair,unsigned>> const& _testNodes, size_t _count = 0) void populateTestNodes(std::vector<std::pair<KeyPair,unsigned>> const& _testNodes, size_t _count = 0)
{ {
if (!_count) if (!_count)
@ -91,7 +92,7 @@ struct TestNodeTable: public NodeTable
else else
break; break;
} }
void reset() void reset()
{ {
Guard l(x_state); Guard l(x_state);
@ -108,13 +109,13 @@ struct TestNodeTableHost: public TestHost
~TestNodeTableHost() { m_io.stop(); stopWorking(); } ~TestNodeTableHost() { m_io.stop(); stopWorking(); }
void setup() { for (auto n: testNodes) nodeTables.push_back(make_shared<TestNodeTable>(m_io,n.first,n.second)); } void setup() { for (auto n: testNodes) nodeTables.push_back(make_shared<TestNodeTable>(m_io,n.first,n.second)); }
void pingAll() { for (auto& t: nodeTables) t->pingTestNodes(testNodes); } void pingAll() { for (auto& t: nodeTables) t->pingTestNodes(testNodes); }
void populateAll(size_t _count = 0) { for (auto& t: nodeTables) t->populateTestNodes(testNodes, _count); } void populateAll(size_t _count = 0) { for (auto& t: nodeTables) t->populateTestNodes(testNodes, _count); }
void populate(size_t _count = 0) { nodeTable->populateTestNodes(testNodes, _count); } void populate(size_t _count = 0) { nodeTable->populateTestNodes(testNodes, _count); }
KeyPair m_alias; KeyPair m_alias;
shared_ptr<TestNodeTable> nodeTable; shared_ptr<TestNodeTable> nodeTable;
std::vector<std::pair<KeyPair,unsigned>> testNodes; // keypair and port std::vector<std::pair<KeyPair,unsigned>> testNodes; // keypair and port
@ -130,7 +131,7 @@ public:
void onReceived(UDPSocketFace*, bi::udp::endpoint const&, bytesConstRef _packet) { if (_packet.toString() == "AAAA") success = true; } void onReceived(UDPSocketFace*, bi::udp::endpoint const&, bytesConstRef _packet) { if (_packet.toString() == "AAAA") success = true; }
shared_ptr<UDPSocket<TestUDPSocket, 1024>> m_socket; shared_ptr<UDPSocket<TestUDPSocket, 1024>> m_socket;
bool success = false; bool success = false;
}; };
@ -139,7 +140,7 @@ BOOST_AUTO_TEST_CASE(test_neighbours_packet)
KeyPair k = KeyPair::create(); KeyPair k = KeyPair::create();
std::vector<std::pair<KeyPair,unsigned>> testNodes(TestNodeTable::createTestNodes(16)); std::vector<std::pair<KeyPair,unsigned>> testNodes(TestNodeTable::createTestNodes(16));
bi::udp::endpoint to(boost::asio::ip::address::from_string("127.0.0.1"), 30000); bi::udp::endpoint to(boost::asio::ip::address::from_string("127.0.0.1"), 30000);
Neighbours out(to); Neighbours out(to);
for (auto n: testNodes) for (auto n: testNodes)
{ {
@ -186,25 +187,25 @@ BOOST_AUTO_TEST_CASE(kademlia)
node.setup(); node.setup();
node.populate(); node.populate();
clog << "NodeTable:\n" << *node.nodeTable.get() << endl; clog << "NodeTable:\n" << *node.nodeTable.get() << endl;
node.populateAll(); node.populateAll();
clog << "NodeTable:\n" << *node.nodeTable.get() << endl; clog << "NodeTable:\n" << *node.nodeTable.get() << endl;
auto nodes = node.nodeTable->nodes(); auto nodes = node.nodeTable->nodes();
nodes.sort(); nodes.sort();
node.nodeTable->reset(); node.nodeTable->reset();
clog << "NodeTable:\n" << *node.nodeTable.get() << endl; clog << "NodeTable:\n" << *node.nodeTable.get() << endl;
node.populate(1); node.populate(1);
clog << "NodeTable:\n" << *node.nodeTable.get() << endl; clog << "NodeTable:\n" << *node.nodeTable.get() << endl;
node.nodeTable->discover(); node.nodeTable->discover();
this_thread::sleep_for(chrono::milliseconds(2000)); this_thread::sleep_for(chrono::milliseconds(2000));
clog << "NodeTable:\n" << *node.nodeTable.get() << endl; clog << "NodeTable:\n" << *node.nodeTable.get() << endl;
BOOST_REQUIRE_EQUAL(node.nodeTable->count(), 8); BOOST_REQUIRE_EQUAL(node.nodeTable->count(), 8);
auto netNodes = node.nodeTable->nodes(); auto netNodes = node.nodeTable->nodes();
netNodes.sort(); netNodes.sort();

146
test/rlp.cpp

@ -22,11 +22,13 @@
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
#include <boost/test/unit_test.hpp>
#include <libdevcore/Log.h> #include <libdevcore/Log.h>
#include <libdevcore/RLP.h> #include <libdevcore/RLP.h>
#include <libdevcore/Common.h> #include <libdevcore/Common.h>
#include <libdevcore/CommonIO.h> #include <libdevcore/CommonIO.h>
#include <boost/test/unit_test.hpp>
#include <algorithm> #include <algorithm>
#include "JsonSpiritHeaders.h" #include "JsonSpiritHeaders.h"
#include "TestHelper.h" #include "TestHelper.h"
@ -66,76 +68,76 @@ namespace dev
testPath += "/BasicTests"; testPath += "/BasicTests";
string s = asString(contents(testPath + "/rlptest.json")); string s = asString(contents(testPath + "/rlptest.json"));
BOOST_REQUIRE_MESSAGE( s.length() > 0, BOOST_REQUIRE_MESSAGE( s.length() > 0,
"Contents of 'rlptest.json' is empty. Have you cloned the 'tests' repo branch develop?"); "Contents of 'rlptest.json' is empty. Have you cloned the 'tests' repo branch develop?");
js::read_string(s, v); js::read_string(s, v);
} }
static void checkRLPTestCase(js::mObject& o) static void checkRLPTestCase(js::mObject& o)
{ {
BOOST_REQUIRE( o.count("in") > 0 ); BOOST_REQUIRE( o.count("in") > 0 );
BOOST_REQUIRE( o.count("out") > 0 ); BOOST_REQUIRE( o.count("out") > 0 );
BOOST_REQUIRE(!o["out"].is_null()); BOOST_REQUIRE(!o["out"].is_null());
} }
static void checkRLPAgainstJson(js::mValue& v, RLP& u) static void checkRLPAgainstJson(js::mValue& v, RLP& u)
{ {
if ( v.type() == js::str_type ) if ( v.type() == js::str_type )
{ {
const std::string& expectedText = v.get_str(); const std::string& expectedText = v.get_str();
if ( !expectedText.empty() && expectedText.front() == '#' ) if ( !expectedText.empty() && expectedText.front() == '#' )
{ {
// Deal with bigint instead of a raw string // Deal with bigint instead of a raw string
std::string bigIntStr = expectedText.substr(1,expectedText.length()-1); std::string bigIntStr = expectedText.substr(1,expectedText.length()-1);
std::stringstream bintStream(bigIntStr); std::stringstream bintStream(bigIntStr);
bigint val; bigint val;
bintStream >> val; bintStream >> val;
BOOST_CHECK( !u.isList() ); BOOST_CHECK( !u.isList() );
BOOST_CHECK( !u.isNull() ); BOOST_CHECK( !u.isNull() );
BOOST_CHECK( u ); // operator bool() BOOST_CHECK( u ); // operator bool()
BOOST_CHECK(u == val); BOOST_CHECK(u == val);
} }
else else
{ {
BOOST_CHECK( !u.isList() ); BOOST_CHECK( !u.isList() );
BOOST_CHECK( !u.isNull() ); BOOST_CHECK( !u.isNull() );
BOOST_CHECK( u.isData() ); BOOST_CHECK( u.isData() );
BOOST_CHECK( u ); BOOST_CHECK( u );
BOOST_CHECK( u.size() == expectedText.length() ); BOOST_CHECK( u.size() == expectedText.length() );
BOOST_CHECK(u == expectedText); BOOST_CHECK(u == expectedText);
} }
} }
else if ( v.type() == js::int_type ) else if ( v.type() == js::int_type )
{ {
const int expectedValue = v.get_int(); const int expectedValue = v.get_int();
BOOST_CHECK( u.isInt() ); BOOST_CHECK( u.isInt() );
BOOST_CHECK( !u.isList() ); BOOST_CHECK( !u.isList() );
BOOST_CHECK( !u.isNull() ); BOOST_CHECK( !u.isNull() );
BOOST_CHECK( u ); // operator bool() BOOST_CHECK( u ); // operator bool()
BOOST_CHECK(u == expectedValue); BOOST_CHECK(u == expectedValue);
} }
else if ( v.type() == js::array_type ) else if ( v.type() == js::array_type )
{ {
BOOST_CHECK( u.isList() ); BOOST_CHECK( u.isList() );
BOOST_CHECK( !u.isInt() ); BOOST_CHECK( !u.isInt() );
BOOST_CHECK( !u.isData() ); BOOST_CHECK( !u.isData() );
js::mArray& arr = v.get_array(); js::mArray& arr = v.get_array();
BOOST_CHECK( u.itemCount() == arr.size() ); BOOST_CHECK( u.itemCount() == arr.size() );
unsigned i; unsigned i;
for( i = 0; i < arr.size(); i++ ) for( i = 0; i < arr.size(); i++ )
{ {
RLP item = u[i]; RLP item = u[i];
checkRLPAgainstJson(arr[i], item); checkRLPAgainstJson(arr[i], item);
} }
} }
else else
{ {
BOOST_ERROR("Invalid Javascript object!"); BOOST_ERROR("Invalid Javascript object!");
} }
} }
} }
} }
BOOST_AUTO_TEST_SUITE(BasicTests) BOOST_AUTO_TEST_SUITE(BasicTests)
@ -154,30 +156,30 @@ BOOST_AUTO_TEST_CASE(rlp_encoding_test)
RLPStream s; RLPStream s;
dev::test::buildRLP(o["in"], s); dev::test::buildRLP(o["in"], s);
std::string expectedText(o["out"].get_str()); std::string expectedText(o["out"].get_str());
std::transform(expectedText.begin(), expectedText.end(), expectedText.begin(), ::tolower ); std::transform(expectedText.begin(), expectedText.end(), expectedText.begin(), ::tolower );
const std::string& computedText = toHex(s.out()); const std::string& computedText = toHex(s.out());
std::stringstream msg; std::stringstream msg;
msg << "Encoding Failed: expected: " << expectedText << std::endl; msg << "Encoding Failed: expected: " << expectedText << std::endl;
msg << " But Computed: " << computedText; msg << " But Computed: " << computedText;
BOOST_CHECK_MESSAGE( BOOST_CHECK_MESSAGE(
expectedText == computedText, expectedText == computedText,
msg.str() msg.str()
); );
} }
} }
BOOST_AUTO_TEST_CASE(rlp_decoding_test) BOOST_AUTO_TEST_CASE(rlp_decoding_test)
{ {
cnote << "Testing RLP decoding..."; cnote << "Testing RLP decoding...";
// Uses the same test cases as encoding but in reverse. // Uses the same test cases as encoding but in reverse.
// We read into the string of hex values, convert to bytes, // We read into the string of hex values, convert to bytes,
// and then compare the output structure to the json of the // and then compare the output structure to the json of the
// input object. // input object.
js::mValue v; js::mValue v;
dev::test::getRLPTestCases(v); dev::test::getRLPTestCases(v);
for (auto& i: v.get_obj()) for (auto& i: v.get_obj())
@ -185,11 +187,11 @@ BOOST_AUTO_TEST_CASE(rlp_decoding_test)
js::mObject& o = i.second.get_obj(); js::mObject& o = i.second.get_obj();
cnote << i.first; cnote << i.first;
dev::test::checkRLPTestCase(o); dev::test::checkRLPTestCase(o);
js::mValue& inputData = o["in"]; js::mValue& inputData = o["in"];
bytes payloadToDecode = fromHex(o["out"].get_str()); bytes payloadToDecode = fromHex(o["out"].get_str());
RLP payload(payloadToDecode); RLP payload(payloadToDecode);
dev::test::checkRLPAgainstJson(inputData, payload); dev::test::checkRLPAgainstJson(inputData, payload);

1
test/state.cpp

@ -22,6 +22,7 @@
#include <boost/filesystem/operations.hpp> #include <boost/filesystem/operations.hpp>
#include <boost/test/unit_test.hpp> #include <boost/test/unit_test.hpp>
#include "JsonSpiritHeaders.h" #include "JsonSpiritHeaders.h"
#include <libdevcore/CommonIO.h> #include <libdevcore/CommonIO.h>
#include <libethereum/CanonBlockChain.h> #include <libethereum/CanonBlockChain.h>

4
test/trie.cpp

@ -22,12 +22,14 @@
#include <fstream> #include <fstream>
#include <random> #include <random>
#include <boost/test/unit_test.hpp>
#include "JsonSpiritHeaders.h" #include "JsonSpiritHeaders.h"
#include <libdevcore/CommonIO.h> #include <libdevcore/CommonIO.h>
#include <libdevcrypto/TrieDB.h> #include <libdevcrypto/TrieDB.h>
#include "TrieHash.h" #include "TrieHash.h"
#include "MemTrie.h" #include "MemTrie.h"
#include <boost/test/unit_test.hpp>
#include "TestHelper.h" #include "TestHelper.h"
using namespace std; using namespace std;

1
test/txTest.cpp

@ -22,6 +22,7 @@
#include <boost/test/unit_test.hpp> #include <boost/test/unit_test.hpp>
#include <boost/filesystem/operations.hpp> #include <boost/filesystem/operations.hpp>
#include <libethereum/Client.h> #include <libethereum/Client.h>
#include <libethereum/CanonBlockChain.h> #include <libethereum/CanonBlockChain.h>
#include <libethereum/EthereumHost.h> #include <libethereum/EthereumHost.h>

6
test/vm.cpp

@ -21,7 +21,9 @@
*/ */
#include <chrono> #include <chrono>
#include <boost/filesystem.hpp> #include <boost/filesystem.hpp>
#include <libethereum/Executive.h> #include <libethereum/Executive.h>
#include <libevm/VMFactory.h> #include <libevm/VMFactory.h>
#include "vm.h" #include "vm.h"
@ -286,7 +288,7 @@ eth::OnOpFunc FakeExtVM::simpleTrace()
/*add the storage*/ /*add the storage*/
Object storage; Object storage;
for (auto const& i: std::get<2>(ext.addresses.find(ext.myAddress)->second)) for (auto const& i: std::get<2>(ext.addresses.find(ext.myAddress)->second))
storage.push_back(Pair( (string)i.first , (string)i.second)); storage.push_back(Pair( (string)i.first , (string)i.second));
/*add all the other details*/ /*add all the other details*/
o_step.push_back(Pair("storage", storage)); o_step.push_back(Pair("storage", storage));
@ -365,7 +367,7 @@ void doVMTests(json_spirit::mValue& v, bool _fillin)
auto argc = boost::unit_test::framework::master_test_suite().argc; auto argc = boost::unit_test::framework::master_test_suite().argc;
auto argv = boost::unit_test::framework::master_test_suite().argv; auto argv = boost::unit_test::framework::master_test_suite().argv;
for (auto i = 0; i < argc; ++i) for (auto i = 0; i < argc; ++i)
{ {
if (std::string(argv[i]) == "--show-times") if (std::string(argv[i]) == "--show-times")
{ {
auto testDuration = endTime - startTime; auto testDuration = endTime - startTime;

2
test/vm.h

@ -25,7 +25,9 @@ along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
#include <fstream> #include <fstream>
#include <cstdint> #include <cstdint>
#include <boost/test/unit_test.hpp> #include <boost/test/unit_test.hpp>
#include <json_spirit/json_spirit.h> #include <json_spirit/json_spirit.h>
#include <libdevcore/Log.h> #include <libdevcore/Log.h>
#include <libdevcore/CommonIO.h> #include <libdevcore/CommonIO.h>

32
test/whisperTopic.cpp

@ -19,7 +19,9 @@
* @date 2014 * @date 2014
*/ */
#include <functional> #include <functional>
#include <boost/test/unit_test.hpp> #include <boost/test/unit_test.hpp>
#include <libp2p/Host.h> #include <libp2p/Host.h>
#include <libwhisper/WhisperPeer.h> #include <libwhisper/WhisperPeer.h>
#include <libwhisper/WhisperHost.h> #include <libwhisper/WhisperHost.h>
@ -40,10 +42,10 @@ BOOST_AUTO_TEST_CASE(topic)
Host host1("Test", NetworkPreferences(30303, "127.0.0.1", false, true)); Host host1("Test", NetworkPreferences(30303, "127.0.0.1", false, true));
auto whost1 = host1.registerCapability(new WhisperHost()); auto whost1 = host1.registerCapability(new WhisperHost());
host1.start(); host1.start();
while (!host1.isStarted()) while (!host1.isStarted())
this_thread::sleep_for(chrono::milliseconds(2)); this_thread::sleep_for(chrono::milliseconds(2));
bool started = false; bool started = false;
unsigned result = 0; unsigned result = 0;
std::thread listener([&]() std::thread listener([&]()
@ -71,19 +73,19 @@ BOOST_AUTO_TEST_CASE(topic)
} }
this_thread::sleep_for(chrono::milliseconds(50)); this_thread::sleep_for(chrono::milliseconds(50));
} }
}); });
Host host2("Test", NetworkPreferences(30300, "127.0.0.1", false, true)); Host host2("Test", NetworkPreferences(30300, "127.0.0.1", false, true));
auto whost2 = host2.registerCapability(new WhisperHost()); auto whost2 = host2.registerCapability(new WhisperHost());
host2.start(); host2.start();
while (!host2.isStarted()) while (!host2.isStarted())
this_thread::sleep_for(chrono::milliseconds(2)); this_thread::sleep_for(chrono::milliseconds(2));
this_thread::sleep_for(chrono::milliseconds(100)); this_thread::sleep_for(chrono::milliseconds(100));
host2.addNode(host1.id(), "127.0.0.1", 30303, 30303); host2.addNode(host1.id(), "127.0.0.1", 30303, 30303);
this_thread::sleep_for(chrono::milliseconds(500)); this_thread::sleep_for(chrono::milliseconds(500));
while (!started) while (!started)
@ -107,7 +109,7 @@ BOOST_AUTO_TEST_CASE(forwarding)
cnote << "Testing Whisper forwarding..."; cnote << "Testing Whisper forwarding...";
auto oldLogVerbosity = g_logVerbosity; auto oldLogVerbosity = g_logVerbosity;
g_logVerbosity = 0; g_logVerbosity = 0;
// Host must be configured not to share peers. // Host must be configured not to share peers.
Host host1("Listner", NetworkPreferences(30303, "", false, true)); Host host1("Listner", NetworkPreferences(30303, "", false, true));
host1.setIdealPeerCount(0); host1.setIdealPeerCount(0);
@ -115,7 +117,7 @@ BOOST_AUTO_TEST_CASE(forwarding)
host1.start(); host1.start();
while (!host1.isStarted()) while (!host1.isStarted())
this_thread::sleep_for(chrono::milliseconds(2)); this_thread::sleep_for(chrono::milliseconds(2));
unsigned result = 0; unsigned result = 0;
bool done = false; bool done = false;
@ -142,7 +144,7 @@ BOOST_AUTO_TEST_CASE(forwarding)
} }
}); });
// Host must be configured not to share peers. // Host must be configured not to share peers.
Host host2("Forwarder", NetworkPreferences(30305, "", false, true)); Host host2("Forwarder", NetworkPreferences(30305, "", false, true));
host2.setIdealPeerCount(1); host2.setIdealPeerCount(1);
@ -150,7 +152,7 @@ BOOST_AUTO_TEST_CASE(forwarding)
host2.start(); host2.start();
while (!host2.isStarted()) while (!host2.isStarted())
this_thread::sleep_for(chrono::milliseconds(2)); this_thread::sleep_for(chrono::milliseconds(2));
Public fwderid; Public fwderid;
bool startedForwarder = false; bool startedForwarder = false;
std::thread forwarder([&]() std::thread forwarder([&]()
@ -210,7 +212,7 @@ BOOST_AUTO_TEST_CASE(asyncforwarding)
unsigned result = 0; unsigned result = 0;
bool done = false; bool done = false;
// Host must be configured not to share peers. // Host must be configured not to share peers.
Host host1("Forwarder", NetworkPreferences(30305, "", false, true)); Host host1("Forwarder", NetworkPreferences(30305, "", false, true));
host1.setIdealPeerCount(1); host1.setIdealPeerCount(1);
@ -223,7 +225,7 @@ BOOST_AUTO_TEST_CASE(asyncforwarding)
std::thread forwarder([&]() std::thread forwarder([&]()
{ {
setThreadName("forwarder"); setThreadName("forwarder");
this_thread::sleep_for(chrono::milliseconds(500)); this_thread::sleep_for(chrono::milliseconds(500));
// ph.addNode("127.0.0.1", 30303, 30303); // ph.addNode("127.0.0.1", 30303, 30303);
@ -245,7 +247,7 @@ BOOST_AUTO_TEST_CASE(asyncforwarding)
while (!startedForwarder) while (!startedForwarder)
this_thread::sleep_for(chrono::milliseconds(2)); this_thread::sleep_for(chrono::milliseconds(2));
{ {
Host host2("Sender", NetworkPreferences(30300, "", false, true)); Host host2("Sender", NetworkPreferences(30300, "", false, true));
host2.setIdealPeerCount(1); host2.setIdealPeerCount(1);
@ -257,7 +259,7 @@ BOOST_AUTO_TEST_CASE(asyncforwarding)
while (!host2.peerCount()) while (!host2.peerCount())
this_thread::sleep_for(chrono::milliseconds(5)); this_thread::sleep_for(chrono::milliseconds(5));
KeyPair us = KeyPair::create(); KeyPair us = KeyPair::create();
whost2->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test")); whost2->post(us.sec(), RLPStream().append(1).out(), BuildTopic("test"));
this_thread::sleep_for(chrono::milliseconds(250)); this_thread::sleep_for(chrono::milliseconds(250));

1
third/CMakeLists.txt

@ -12,6 +12,7 @@ aux_source_directory(. SRC_LIST)
include_directories(BEFORE ..) include_directories(BEFORE ..)
include_directories(${JSON_RPC_CPP_INCLUDE_DIRS}) include_directories(${JSON_RPC_CPP_INCLUDE_DIRS})
include_directories(${Boost_INCLUDE_DIRS})
qt5_wrap_ui(ui_Main.h Main.ui) qt5_wrap_ui(ui_Main.h Main.ui)

16
third/MainWin.cpp

@ -20,6 +20,9 @@
*/ */
#include <fstream> #include <fstream>
#include <boost/algorithm/string.hpp>
#include <QtNetwork/QNetworkReply> #include <QtNetwork/QNetworkReply>
#include <QtWidgets/QFileDialog> #include <QtWidgets/QFileDialog>
#include <QtWidgets/QMessageBox> #include <QtWidgets/QMessageBox>
@ -27,7 +30,6 @@
#include <QtWebKitWidgets/QWebFrame> #include <QtWebKitWidgets/QWebFrame>
#include <QtGui/QClipboard> #include <QtGui/QClipboard>
#include <QtCore/QtCore> #include <QtCore/QtCore>
#include <boost/algorithm/string.hpp>
#include <libserpent/funcs.h> #include <libserpent/funcs.h>
#include <libserpent/util.h> #include <libserpent/util.h>
#include <libdevcrypto/FileSystem.h> #include <libdevcrypto/FileSystem.h>
@ -112,7 +114,7 @@ Main::Main(QWidget *parent) :
statusBar()->addPermanentWidget(ui->peerCount); statusBar()->addPermanentWidget(ui->peerCount);
statusBar()->addPermanentWidget(ui->mineStatus); statusBar()->addPermanentWidget(ui->mineStatus);
statusBar()->addPermanentWidget(ui->blockCount); statusBar()->addPermanentWidget(ui->blockCount);
connect(ui->ourAccounts->model(), SIGNAL(rowsMoved(const QModelIndex &, int, int, const QModelIndex &, int)), SLOT(ourAccountsRowsMoved())); connect(ui->ourAccounts->model(), SIGNAL(rowsMoved(const QModelIndex &, int, int, const QModelIndex &, int)), SLOT(ourAccountsRowsMoved()));
bytesConstRef networkConfig((byte*)m_networkConfig.data(), m_networkConfig.size()); bytesConstRef networkConfig((byte*)m_networkConfig.data(), m_networkConfig.size());
@ -124,7 +126,7 @@ Main::Main(QWidget *parent) :
// m_server = unique_ptr<WebThreeStubServer>(new WebThreeStubServer(m_httpConnector, *web3(), keysAsVector(m_myKeys))); // m_server = unique_ptr<WebThreeStubServer>(new WebThreeStubServer(m_httpConnector, *web3(), keysAsVector(m_myKeys)));
m_server->setIdentities(keysAsVector(owned())); m_server->setIdentities(keysAsVector(owned()));
m_server->StartListening(); m_server->StartListening();
connect(ui->webView, &QWebView::loadStarted, [this]() connect(ui->webView, &QWebView::loadStarted, [this]()
{ {
QWebFrame* f = ui->webView->page()->mainFrame(); QWebFrame* f = ui->webView->page()->mainFrame();
@ -138,16 +140,16 @@ Main::Main(QWidget *parent) :
f->evaluateJavaScript(contentsOfQResource(":/js/setup.js")); f->evaluateJavaScript(contentsOfQResource(":/js/setup.js"));
}); });
}); });
connect(ui->webView, &QWebView::loadFinished, [=]() connect(ui->webView, &QWebView::loadFinished, [=]()
{ {
}); });
connect(ui->webView, &QWebView::titleChanged, [=]() connect(ui->webView, &QWebView::titleChanged, [=]()
{ {
ui->tabWidget->setTabText(0, ui->webView->title()); ui->tabWidget->setTabText(0, ui->webView->title());
}); });
readSettings(); readSettings();
installWatches(); installWatches();
@ -521,7 +523,7 @@ void Main::timerEvent(QTimerEvent*)
// 7/18, Alex: aggregating timers, prelude to better threading? // 7/18, Alex: aggregating timers, prelude to better threading?
// Runs much faster on slower dual-core processors // Runs much faster on slower dual-core processors
static int interval = 100; static int interval = 100;
// refresh mining every 200ms // refresh mining every 200ms
if (interval / 100 % 2 == 0) if (interval / 100 % 2 == 0)
refreshMining(); refreshMining();

Loading…
Cancel
Save