Browse Source

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

cl-refactor
Gav Wood 10 years ago
parent
commit
286ea2b109
  1. 4
      alethzero/CMakeLists.txt
  2. 10
      getcoverage.sh
  3. 5
      libethereum/BlockChainSync.h
  4. 4
      libethereum/Client.cpp
  5. 2
      libethereum/Executive.cpp
  6. 2
      libjsengine/JSEngine.h
  7. 48
      libjsengine/JSV8Engine.cpp
  8. 2
      libjsengine/JSV8Engine.h
  9. 4
      libp2p/Common.h
  10. 23
      libp2p/Host.cpp
  11. 4
      libp2p/Host.h
  12. 5
      libp2p/HostCapability.h
  13. 7
      libp2p/Network.cpp
  14. 22
      libp2p/NodeTable.cpp
  15. 2
      libp2p/NodeTable.h
  16. 7
      libp2p/RLPxHandshake.cpp
  17. 4
      libp2p/RLPxHandshake.h
  18. 5
      libp2p/Session.cpp
  19. 4
      libp2p/Session.h
  20. 4
      libp2p/UPnP.cpp
  21. 4
      libp2p/UPnP.h
  22. 2
      libwebthree/WebThree.cpp
  23. 2
      mix/CMakeLists.txt
  24. 4
      secp256k1/libsecp256k1-config.h
  25. 59
      test/TestHelper.cpp
  26. 8
      test/TestHelper.h
  27. 144
      test/libethereum/AccountDiff.cpp
  28. 7
      test/libethereum/transactionTests.cpp
  29. 4
      test/libp2p/capability.cpp
  30. 8
      test/libwhisper/shhrpc.cpp
  31. 12
      test/libwhisper/whisperDB.cpp
  32. 22
      test/libwhisper/whisperTopic.cpp

4
alethzero/CMakeLists.txt

@ -64,8 +64,8 @@ target_link_libraries(${EXECUTABLE} Qt5::Core)
target_link_libraries(${EXECUTABLE} Qt5::Widgets) target_link_libraries(${EXECUTABLE} Qt5::Widgets)
target_link_libraries(${EXECUTABLE} Qt5::WebEngine) target_link_libraries(${EXECUTABLE} Qt5::WebEngine)
target_link_libraries(${EXECUTABLE} Qt5::WebEngineWidgets) target_link_libraries(${EXECUTABLE} Qt5::WebEngineWidgets)
if (APPLE) if (APPLE AND (NOT "${Qt5Core_VERSION_STRING}" VERSION_LESS "5.5"))
target_link_libraries(${EXECUTABLE} Qt5::WebEngineCore) target_link_libraries(${EXECUTABLE} Qt5::WebEngineCore)
target_link_libraries(${EXECUTABLE} Qt5::DBus) target_link_libraries(${EXECUTABLE} Qt5::DBus)
target_link_libraries(${EXECUTABLE} Qt5::PrintSupport) target_link_libraries(${EXECUTABLE} Qt5::PrintSupport)
endif() endif()

10
getcoverage.sh

@ -17,6 +17,10 @@ case $i in
TEST_MODE="--all" TEST_MODE="--all"
shift shift
;; ;;
--filltests)
TEST_FILL="--filltests"
shift
;;
esac esac
done done
@ -39,9 +43,9 @@ if which lcov >/dev/null; then
lcov --capture --initial --directory $BUILD_DIR --output-file $OUTPUT_DIR/coverage_base.info lcov --capture --initial --directory $BUILD_DIR --output-file $OUTPUT_DIR/coverage_base.info
echo Running testeth... echo Running testeth...
$CPP_ETHEREUM_PATH/build/test/testeth $TEST_MODE $BUILD_DIR/test/testeth $TEST_MODE $TEST_FILL
$CPP_ETHEREUM_PATH/build/test/testeth -t StateTests --jit $TEST_MODE $BUILD_DIR/test/testeth -t StateTests --jit $TEST_MODE
$CPP_ETHEREUM_PATH/build/test/testeth -t VMTests --jit $TEST_MODE $BUILD_DIR/test/testeth -t VMTests --jit $TEST_MODE
echo Prepearing coverage info... echo Prepearing coverage info...
lcov --capture --directory $BUILD_DIR --output-file $OUTPUT_DIR/coverage_test.info lcov --capture --directory $BUILD_DIR --output-file $OUTPUT_DIR/coverage_test.info

5
libethereum/BlockChainSync.h

@ -113,6 +113,9 @@ protected:
/// Request blocks from peer if needed /// Request blocks from peer if needed
void requestBlocks(std::shared_ptr<EthereumPeer> _peer); void requestBlocks(std::shared_ptr<EthereumPeer> _peer);
private:
EthereumHost& m_host;
protected: protected:
Handler<> m_bqRoomAvailable; ///< Triggered once block queue Handler<> m_bqRoomAvailable; ///< Triggered once block queue
mutable RecursiveMutex x_sync; mutable RecursiveMutex x_sync;
@ -124,8 +127,6 @@ private:
static char const* const s_stateNames[static_cast<int>(SyncState::Size)]; static char const* const s_stateNames[static_cast<int>(SyncState::Size)];
bool invariants() const override = 0; bool invariants() const override = 0;
void logNewBlock(h256 const& _h); void logNewBlock(h256 const& _h);
EthereumHost& m_host;
}; };

4
libethereum/Client.cpp

@ -116,9 +116,9 @@ void Client::init(p2p::Host* _extNet, std::string const& _dbPath, WithExisting _
m_gp->update(bc()); m_gp->update(bc());
auto host = _extNet->registerCapability(new EthereumHost(bc(), m_tq, m_bq, _networkId)); auto host = _extNet->registerCapability(make_shared<EthereumHost>(bc(), m_tq, m_bq, _networkId));
m_host = host; m_host = host;
_extNet->addCapability(host, EthereumHost::staticName(), EthereumHost::c_oldProtocolVersion); //TODO: remove this one v61+ protocol is common _extNet->addCapability(host, EthereumHost::staticName(), EthereumHost::c_oldProtocolVersion); //TODO: remove this once v61+ protocol is common
if (_dbPath.size()) if (_dbPath.size())
Defaults::setDBPath(_dbPath); Defaults::setDBPath(_dbPath);

2
libethereum/Executive.cpp

@ -39,7 +39,7 @@ const char* VMTraceChannel::name() { return "EVM"; }
const char* ExecutiveWarnChannel::name() { return WarnChannel::name(); } const char* ExecutiveWarnChannel::name() { return WarnChannel::name(); }
StandardTrace::StandardTrace(): StandardTrace::StandardTrace():
m_trace(new Json::Value(Json::arrayValue)) m_trace(make_shared<Json::Value>(Json::arrayValue))
{} {}
bool changesMemory(Instruction _inst) bool changesMemory(Instruction _inst)

2
libjsengine/JSEngine.h

@ -59,7 +59,7 @@ class JSEngine
{ {
public: public:
// should be used to evalute javascript expression // should be used to evalute javascript expression
virtual T eval(char const* _cstr) const = 0; virtual T eval(char const* _cstr, char const* _origin = "(shell)") const = 0;
}; };
} }

48
libjsengine/JSV8Engine.cpp

@ -21,6 +21,8 @@
*/ */
#include <memory> #include <memory>
#include <iostream>
#include <fstream>
#include "JSV8Engine.h" #include "JSV8Engine.h"
#include "JSV8Printer.h" #include "JSV8Printer.h"
#include "libjsengine/JSEngineResources.hpp" #include "libjsengine/JSEngineResources.hpp"
@ -93,7 +95,7 @@ void reportException(TryCatch* _tryCatch)
} }
} }
Handle<Value> ConsoleLog(Arguments const& _args) Handle<Value> consoleLog(Arguments const& _args)
{ {
Local<External> wrap = Local<External>::Cast(_args.Data()); Local<External> wrap = Local<External>::Cast(_args.Data());
auto engine = reinterpret_cast<JSV8Engine const*>(wrap->Value()); auto engine = reinterpret_cast<JSV8Engine const*>(wrap->Value());
@ -103,6 +105,35 @@ Handle<Value> ConsoleLog(Arguments const& _args)
return Undefined(); return Undefined();
} }
Handle<Value> loadScript(Arguments const& _args)
{
Local<External> wrap = Local<External>::Cast(_args.Data());
auto engine = reinterpret_cast<JSV8Engine const*>(wrap->Value());
if (_args.Length() < 1)
return v8::ThrowException(v8::String::New("Missing file name."));
if (_args[0].IsEmpty() || _args[0]->IsUndefined())
return v8::ThrowException(v8::String::New("Invalid file name."));
v8::String::Utf8Value fileName(_args[0]);
if (fileName.length() == 0)
return v8::ThrowException(v8::String::New("Invalid file name."));
std::ifstream is(*fileName, std::ifstream::binary);
if (!is)
return v8::ThrowException(v8::String::New("Error opening file."));
string contents;
is.seekg(0, is.end);
streamoff length = is.tellg();
if (length > 0)
{
is.seekg(0, is.beg);
contents.resize(length);
is.read(const_cast<char*>(contents.data()), length);
}
return engine->eval(contents.data(), *fileName).value();
}
class JSV8Scope class JSV8Scope
{ {
@ -158,11 +189,14 @@ JSV8Engine::JSV8Engine(): m_scope(new JSV8Scope())
auto consoleTemplate = ObjectTemplate::New(); auto consoleTemplate = ObjectTemplate::New();
Local<FunctionTemplate> function = FunctionTemplate::New(ConsoleLog, External::New(this)); Local<FunctionTemplate> consoleLogFunction = FunctionTemplate::New(consoleLog, External::New(this));
consoleTemplate->Set(String::New("debug"), function); consoleTemplate->Set(String::New("debug"), consoleLogFunction);
consoleTemplate->Set(String::New("log"), function); consoleTemplate->Set(String::New("log"), consoleLogFunction);
consoleTemplate->Set(String::New("error"), function); consoleTemplate->Set(String::New("error"), consoleLogFunction);
context()->Global()->Set(String::New("console"), consoleTemplate->NewInstance()); context()->Global()->Set(String::New("console"), consoleTemplate->NewInstance());
Local<FunctionTemplate> loadScriptFunction = FunctionTemplate::New(loadScript, External::New(this));
context()->Global()->Set(String::New("loadScript"), loadScriptFunction->GetFunction());
} }
JSV8Engine::~JSV8Engine() JSV8Engine::~JSV8Engine()
@ -170,11 +204,11 @@ JSV8Engine::~JSV8Engine()
delete m_scope; delete m_scope;
} }
JSV8Value JSV8Engine::eval(char const* _cstr) const JSV8Value JSV8Engine::eval(char const* _cstr, char const* _origin) const
{ {
TryCatch tryCatch; TryCatch tryCatch;
Local<String> source = String::New(_cstr); Local<String> source = String::New(_cstr);
Local<String> name(String::New("(shell)")); Local<String> name(String::New(_origin));
ScriptOrigin origin(name); ScriptOrigin origin(name);
Handle<Script> script = Script::Compile(source, &origin); Handle<Script> script = Script::Compile(source, &origin);

2
libjsengine/JSV8Engine.h

@ -54,7 +54,7 @@ class JSV8Engine: public JSEngine<JSV8Value>
public: public:
JSV8Engine(); JSV8Engine();
virtual ~JSV8Engine(); virtual ~JSV8Engine();
JSV8Value eval(char const* _cstr) const; JSV8Value eval(char const* _cstr, char const* _origin = "(shell)") const;
v8::Handle<v8::Context> const& context() const; v8::Handle<v8::Context> const& context() const;
private: private:

4
libp2p/Common.h

@ -221,7 +221,7 @@ class DeadlineOps
{ {
public: public:
DeadlineOp(ba::io_service& _io, unsigned _msInFuture, std::function<void(boost::system::error_code const&)> const& _f): m_timer(new ba::deadline_timer(_io)) { m_timer->expires_from_now(boost::posix_time::milliseconds(_msInFuture)); m_timer->async_wait(_f); } DeadlineOp(ba::io_service& _io, unsigned _msInFuture, std::function<void(boost::system::error_code const&)> const& _f): m_timer(new ba::deadline_timer(_io)) { m_timer->expires_from_now(boost::posix_time::milliseconds(_msInFuture)); m_timer->async_wait(_f); }
~DeadlineOp() {} ~DeadlineOp() { if (m_timer) m_timer->cancel(); }
DeadlineOp(DeadlineOp&& _s): m_timer(_s.m_timer.release()) {} DeadlineOp(DeadlineOp&& _s): m_timer(_s.m_timer.release()) {}
DeadlineOp& operator=(DeadlineOp&& _s) DeadlineOp& operator=(DeadlineOp&& _s)
@ -247,6 +247,8 @@ public:
void schedule(unsigned _msInFuture, std::function<void(boost::system::error_code const&)> const& _f) { if (m_stopped) return; DEV_GUARDED(x_timers) m_timers.emplace_back(m_io, _msInFuture, _f); } void schedule(unsigned _msInFuture, std::function<void(boost::system::error_code const&)> const& _f) { if (m_stopped) return; DEV_GUARDED(x_timers) m_timers.emplace_back(m_io, _msInFuture, _f); }
void stop() { m_stopped = true; DEV_GUARDED(x_timers) m_timers.clear(); } void stop() { m_stopped = true; DEV_GUARDED(x_timers) m_timers.clear(); }
bool isStopped() const { return m_stopped; }
protected: protected:
void reap(); void reap();

23
libp2p/Host.cpp

@ -225,7 +225,7 @@ void Host::doneWorking()
m_sessions.clear(); m_sessions.clear();
} }
void Host::startPeerSession(Public const& _id, RLP const& _rlp, RLPXFrameCoder* _io, std::shared_ptr<RLPXSocket> const& _s) void Host::startPeerSession(Public const& _id, RLP const& _rlp, unique_ptr<RLPXFrameCoder>&& _io, std::shared_ptr<RLPXSocket> const& _s)
{ {
// session maybe ingress or egress so m_peers and node table entries may not exist // session maybe ingress or egress so m_peers and node table entries may not exist
shared_ptr<Peer> p; shared_ptr<Peer> p;
@ -237,9 +237,9 @@ void Host::startPeerSession(Public const& _id, RLP const& _rlp, RLPXFrameCoder*
{ {
// peer doesn't exist, try to get port info from node table // peer doesn't exist, try to get port info from node table
if (Node n = m_nodeTable->node(_id)) if (Node n = m_nodeTable->node(_id))
p.reset(new Peer(n)); p = make_shared<Peer>(n);
else else
p.reset(new Peer(Node(_id, UnspecifiedNodeIPEndpoint))); p = make_shared<Peer>(Node(_id, UnspecifiedNodeIPEndpoint));
m_peers[_id] = p; m_peers[_id] = p;
} }
} }
@ -264,7 +264,7 @@ void Host::startPeerSession(Public const& _id, RLP const& _rlp, RLPXFrameCoder*
clog(NetMessageSummary) << "Hello: " << clientVersion << "V[" << protocolVersion << "]" << _id << showbase << capslog.str() << dec << listenPort; clog(NetMessageSummary) << "Hello: " << clientVersion << "V[" << protocolVersion << "]" << _id << showbase << capslog.str() << dec << listenPort;
// create session so disconnects are managed // create session so disconnects are managed
auto ps = make_shared<Session>(this, _io, _s, p, PeerSessionInfo({_id, clientVersion, p->endpoint.address.to_string(), listenPort, chrono::steady_clock::duration(), _rlp[2].toSet<CapDesc>(), 0, map<string, string>(), protocolVersion})); auto ps = make_shared<Session>(this, move(_io), _s, p, PeerSessionInfo({_id, clientVersion, p->endpoint.address.to_string(), listenPort, chrono::steady_clock::duration(), _rlp[2].toSet<CapDesc>(), 0, map<string, string>(), protocolVersion}));
if (protocolVersion < dev::p2p::c_protocolVersion - 1) if (protocolVersion < dev::p2p::c_protocolVersion - 1)
{ {
ps->disconnect(IncompatibleProtocol); ps->disconnect(IncompatibleProtocol);
@ -294,7 +294,7 @@ void Host::startPeerSession(Public const& _id, RLP const& _rlp, RLPXFrameCoder*
for (auto const& i: caps) for (auto const& i: caps)
if (haveCapability(i)) if (haveCapability(i))
{ {
ps->m_capabilities[i] = shared_ptr<Capability>(m_capabilities[i]->newPeerCapability(ps, o, i)); ps->m_capabilities[i] = m_capabilities[i]->newPeerCapability(ps, o, i);
o += m_capabilities[i]->messageCount(); o += m_capabilities[i]->messageCount();
} }
ps->start(); ps->start();
@ -323,7 +323,7 @@ void Host::onNodeTableEvent(NodeId const& _n, NodeTableEventType const& _e)
} }
else else
{ {
p.reset(new Peer(n)); p = make_shared<Peer>(n);
m_peers[_n] = p; m_peers[_n] = p;
clog(NetP2PNote) << "p2p.host.peers.events.peerAdded " << _n << p->endpoint; clog(NetP2PNote) << "p2p.host.peers.events.peerAdded " << _n << p->endpoint;
} }
@ -491,14 +491,14 @@ void Host::requirePeer(NodeId const& _n, NodeIPEndpoint const& _endpoint)
} }
else else
{ {
p.reset(new Peer(node)); p = make_shared<Peer>(node);
m_peers[_n] = p; m_peers[_n] = p;
} }
} }
else if (m_nodeTable) else if (m_nodeTable)
{ {
m_nodeTable->addNode(node); m_nodeTable->addNode(node);
shared_ptr<boost::asio::deadline_timer> t(new boost::asio::deadline_timer(m_ioService)); auto t = make_shared<boost::asio::deadline_timer>(m_ioService);
t->expires_from_now(boost::posix_time::milliseconds(600)); t->expires_from_now(boost::posix_time::milliseconds(600));
t->async_wait([this, _n](boost::system::error_code const& _ec) t->async_wait([this, _n](boost::system::error_code const& _ec)
{ {
@ -712,7 +712,12 @@ void Host::startedWorking()
else else
clog(NetP2PNote) << "p2p.start.notice id:" << id() << "TCP Listen port is invalid or unavailable."; clog(NetP2PNote) << "p2p.start.notice id:" << id() << "TCP Listen port is invalid or unavailable.";
shared_ptr<NodeTable> nodeTable(new NodeTable(m_ioService, m_alias, NodeIPEndpoint(bi::address::from_string(listenAddress()), listenPort(), listenPort()), m_netPrefs.discovery)); auto nodeTable = make_shared<NodeTable>(
m_ioService,
m_alias,
NodeIPEndpoint(bi::address::from_string(listenAddress()), listenPort(), listenPort()),
m_netPrefs.discovery
);
nodeTable->setEventHandler(new HostNodeTableHandler(*this)); nodeTable->setEventHandler(new HostNodeTableHandler(*this));
m_nodeTable = nodeTable; m_nodeTable = nodeTable;
restoreNetwork(&m_restoreNetwork); restoreNetwork(&m_restoreNetwork);

4
libp2p/Host.h

@ -161,7 +161,7 @@ public:
static std::unordered_map<Public, std::string> const& pocHosts(); static std::unordered_map<Public, std::string> const& pocHosts();
/// Register a peer-capability; all new peer connections will have this capability. /// Register a peer-capability; all new peer connections will have this capability.
template <class T> std::shared_ptr<T> registerCapability(T* _t) { _t->m_host = this; std::shared_ptr<T> ret(_t); m_capabilities[std::make_pair(T::staticName(), T::staticVersion())] = ret; return ret; } template <class T> std::shared_ptr<T> registerCapability(std::shared_ptr<T> const& _t) { _t->m_host = this; m_capabilities[std::make_pair(T::staticName(), T::staticVersion())] = _t; return _t; }
template <class T> void addCapability(std::shared_ptr<T> const & _p, std::string const& _name, u256 const& _version) { m_capabilities[std::make_pair(_name, _version)] = _p; } template <class T> void addCapability(std::shared_ptr<T> const & _p, std::string const& _name, u256 const& _version) { m_capabilities[std::make_pair(_name, _version)] = _p; }
bool haveCapability(CapDesc const& _name) const { return m_capabilities.count(_name) != 0; } bool haveCapability(CapDesc const& _name) const { return m_capabilities.count(_name) != 0; }
@ -225,7 +225,7 @@ public:
bool haveNetwork() const { return m_run && !!m_nodeTable; } bool haveNetwork() const { return m_run && !!m_nodeTable; }
/// Validates and starts peer session, taking ownership of _io. Disconnects and returns false upon error. /// Validates and starts peer session, taking ownership of _io. Disconnects and returns false upon error.
void startPeerSession(Public const& _id, RLP const& _hello, RLPXFrameCoder* _io, std::shared_ptr<RLPXSocket> const& _s); void startPeerSession(Public const& _id, RLP const& _hello, std::unique_ptr<RLPXFrameCoder>&& _io, std::shared_ptr<RLPXSocket> const& _s);
/// Get session by id /// Get session by id
std::shared_ptr<Session> peerSession(NodeId const& _id) { RecursiveGuard l(x_sessions); return m_sessions.count(_id) ? m_sessions[_id].lock() : std::shared_ptr<Session>(); } std::shared_ptr<Session> peerSession(NodeId const& _id) { RecursiveGuard l(x_sessions); return m_sessions.count(_id) ? m_sessions[_id].lock() : std::shared_ptr<Session>(); }

5
libp2p/HostCapability.h

@ -23,6 +23,7 @@
#pragma once #pragma once
#include <memory>
#include "Peer.h" #include "Peer.h"
#include "Common.h" #include "Common.h"
@ -53,7 +54,7 @@ protected:
virtual u256 version() const = 0; virtual u256 version() const = 0;
CapDesc capDesc() const { return std::make_pair(name(), version()); } CapDesc capDesc() const { return std::make_pair(name(), version()); }
virtual unsigned messageCount() const = 0; virtual unsigned messageCount() const = 0;
virtual Capability* newPeerCapability(std::shared_ptr<Session> _s, unsigned _idOffset, CapDesc const& _cap) = 0; virtual std::shared_ptr<Capability> newPeerCapability(std::shared_ptr<Session> const& _s, unsigned _idOffset, CapDesc const& _cap) = 0;
virtual void onStarting() {} virtual void onStarting() {}
virtual void onStopping() {} virtual void onStopping() {}
@ -77,7 +78,7 @@ protected:
virtual std::string name() const { return PeerCap::name(); } virtual std::string name() const { return PeerCap::name(); }
virtual u256 version() const { return PeerCap::version(); } virtual u256 version() const { return PeerCap::version(); }
virtual unsigned messageCount() const { return PeerCap::messageCount(); } virtual unsigned messageCount() const { return PeerCap::messageCount(); }
virtual Capability* newPeerCapability(std::shared_ptr<Session> _s, unsigned _idOffset, CapDesc const& _cap) { return new PeerCap(_s, this, _idOffset, _cap); } virtual std::shared_ptr<Capability> newPeerCapability(std::shared_ptr<Session> const& _s, unsigned _idOffset, CapDesc const& _cap) { return std::make_shared<PeerCap>(_s, this, _idOffset, _cap); }
}; };
} }

7
libp2p/Network.cpp

@ -169,10 +169,10 @@ bi::tcp::endpoint Network::traverseNAT(std::set<bi::address> const& _ifAddresses
{ {
asserts(_listenPort != 0); asserts(_listenPort != 0);
UPnP* upnp = nullptr; unique_ptr<UPnP> upnp;
try try
{ {
upnp = new UPnP; upnp.reset(new UPnP);
} }
// let m_upnp continue as null - we handle it properly. // let m_upnp continue as null - we handle it properly.
catch (...) {} catch (...) {}
@ -200,9 +200,6 @@ bi::tcp::endpoint Network::traverseNAT(std::set<bi::address> const& _ifAddresses
} }
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)
delete upnp;
} }
return upnpEP; return upnpEP;

22
libp2p/NodeTable.cpp

@ -43,7 +43,7 @@ NodeEntry::NodeEntry(NodeId const& _src, Public const& _pubk, NodeIPEndpoint con
NodeTable::NodeTable(ba::io_service& _io, KeyPair const& _alias, NodeIPEndpoint const& _endpoint, bool _enabled): NodeTable::NodeTable(ba::io_service& _io, KeyPair const& _alias, NodeIPEndpoint const& _endpoint, bool _enabled):
m_node(Node(_alias.pub(), _endpoint)), m_node(Node(_alias.pub(), _endpoint)),
m_secret(_alias.sec()), m_secret(_alias.sec()),
m_socket(new NodeSocket(_io, *this, (bi::udp::endpoint)m_node.endpoint)), m_socket(make_shared<NodeSocket>(_io, *reinterpret_cast<UDPSocketEvents*>(this), (bi::udp::endpoint)m_node.endpoint)),
m_socketPointer(m_socket.get()), m_socketPointer(m_socket.get()),
m_timers(_io) m_timers(_io)
{ {
@ -67,8 +67,8 @@ NodeTable::NodeTable(ba::io_service& _io, KeyPair const& _alias, NodeIPEndpoint
NodeTable::~NodeTable() NodeTable::~NodeTable()
{ {
m_timers.stop();
m_socketPointer->disconnect(); m_socketPointer->disconnect();
m_timers.stop();
} }
void NodeTable::processEvents() void NodeTable::processEvents()
@ -81,7 +81,7 @@ shared_ptr<NodeEntry> NodeTable::addNode(Node const& _node, NodeRelation _relati
{ {
if (_relation == Known) if (_relation == Known)
{ {
shared_ptr<NodeEntry> ret(new NodeEntry(m_node.id, _node.id, _node.endpoint)); auto ret = make_shared<NodeEntry>(m_node.id, _node.id, _node.endpoint);
ret->pending = false; ret->pending = false;
DEV_GUARDED(x_nodes) DEV_GUARDED(x_nodes)
m_nodes[_node.id] = ret; m_nodes[_node.id] = ret;
@ -107,7 +107,7 @@ shared_ptr<NodeEntry> NodeTable::addNode(Node const& _node, NodeRelation _relati
if (m_nodes.count(_node.id)) if (m_nodes.count(_node.id))
return m_nodes[_node.id]; return m_nodes[_node.id];
shared_ptr<NodeEntry> ret(new NodeEntry(m_node.id, _node.id, _node.endpoint)); auto ret = make_shared<NodeEntry>(m_node.id, _node.id, _node.endpoint);
DEV_GUARDED(x_nodes) DEV_GUARDED(x_nodes)
m_nodes[_node.id] = ret; m_nodes[_node.id] = ret;
clog(NodeTableConnect) << "addNode pending for" << _node.endpoint; clog(NodeTableConnect) << "addNode pending for" << _node.endpoint;
@ -167,7 +167,7 @@ void NodeTable::doDiscover(NodeId _node, unsigned _round, shared_ptr<set<shared_
} }
else if (!_round && !_tried) else if (!_round && !_tried)
// initialized _tried on first round // initialized _tried on first round
_tried.reset(new set<shared_ptr<NodeEntry>>()); _tried = make_shared<set<shared_ptr<NodeEntry>>>();
auto nearest = nearestNodeEntries(_node); auto nearest = nearestNodeEntries(_node);
list<shared_ptr<NodeEntry>> tried; list<shared_ptr<NodeEntry>> tried;
@ -199,7 +199,17 @@ void NodeTable::doDiscover(NodeId _node, unsigned _round, shared_ptr<set<shared_
m_timers.schedule(c_reqTimeout.count() * 2, [this, _node, _round, _tried](boost::system::error_code const& _ec) m_timers.schedule(c_reqTimeout.count() * 2, [this, _node, _round, _tried](boost::system::error_code const& _ec)
{ {
if (_ec) if (_ec)
clog(NodeTableWarn) << "Discovery timer canceled!"; clog(NodeTableMessageDetail) << "Discovery timer canceled: " << _ec.value() << _ec.message();
if (_ec.value() == boost::asio::error::operation_aborted || m_timers.isStopped())
return;
// error::operation_aborted means that the timer was probably aborted.
// It usually happens when "this" object is deallocated, in which case
// subsequent call to doDiscover() would cause a crash. We can not rely on
// m_timers.isStopped(), because "this" pointer was captured by the lambda,
// and therefore, in case of deallocation m_timers object no longer exists.
doDiscover(_node, _round + 1, _tried); doDiscover(_node, _round + 1, _tried);
}); });
} }

2
libp2p/NodeTable.h

@ -264,7 +264,7 @@ private:
std::shared_ptr<NodeSocket> m_socket; ///< Shared pointer for our UDPSocket; ASIO requires shared_ptr. std::shared_ptr<NodeSocket> m_socket; ///< Shared pointer for our UDPSocket; ASIO requires shared_ptr.
NodeSocket* m_socketPointer; ///< Set to m_socket.get(). Socket is created in constructor and disconnected in destructor to ensure access to pointer is safe. NodeSocket* m_socketPointer; ///< Set to m_socket.get(). Socket is created in constructor and disconnected in destructor to ensure access to pointer is safe.
DeadlineOps m_timers; DeadlineOps m_timers; ///< this should be the last member - it must be destroyed first
}; };
inline std::ostream& operator<<(std::ostream& _out, NodeTable const& _nodeTable) inline std::ostream& operator<<(std::ostream& _out, NodeTable const& _nodeTable)

7
libp2p/RLPxHandshake.cpp

@ -143,8 +143,7 @@ void RLPXHandshake::error()
clog(NetP2PConnect) << "Handshake Failed (Connection reset by peer)"; clog(NetP2PConnect) << "Handshake Failed (Connection reset by peer)";
m_socket->close(); m_socket->close();
if (m_io != nullptr) m_io.reset();
delete m_io;
} }
void RLPXHandshake::transition(boost::system::error_code _ech) void RLPXHandshake::transition(boost::system::error_code _ech)
@ -194,7 +193,7 @@ void RLPXHandshake::transition(boost::system::error_code _ech)
/// This pointer will be freed if there is an error otherwise /// This pointer will be freed if there is an error otherwise
/// it will be passed to Host which will take ownership. /// it will be passed to Host which will take ownership.
m_io = new RLPXFrameCoder(*this); m_io.reset(new RLPXFrameCoder(*this));
// old packet format // old packet format
// 5 arguments, HelloPacket // 5 arguments, HelloPacket
@ -286,7 +285,7 @@ void RLPXHandshake::transition(boost::system::error_code _ech)
try try
{ {
RLP rlp(frame.cropped(1), RLP::ThrowOnFail | RLP::FailIfTooSmall); RLP rlp(frame.cropped(1), RLP::ThrowOnFail | RLP::FailIfTooSmall);
m_host->startPeerSession(m_remote, rlp, m_io, m_socket); m_host->startPeerSession(m_remote, rlp, move(m_io), m_socket);
} }
catch (std::exception const& _e) catch (std::exception const& _e)
{ {

4
libp2p/RLPxHandshake.h

@ -123,11 +123,11 @@ protected:
/// Used to read and write RLPx encrypted frames for last step of handshake authentication. /// Used to read and write RLPx encrypted frames for last step of handshake authentication.
/// Passed onto Host which will take ownership. /// Passed onto Host which will take ownership.
RLPXFrameCoder* m_io = nullptr; std::unique_ptr<RLPXFrameCoder> m_io;
std::shared_ptr<RLPXSocket> m_socket; ///< Socket. std::shared_ptr<RLPXSocket> m_socket; ///< Socket.
boost::asio::deadline_timer m_idleTimer; ///< Timer which enforces c_timeout. boost::asio::deadline_timer m_idleTimer; ///< Timer which enforces c_timeout.
}; };
} }
} }

5
libp2p/Session.cpp

@ -33,9 +33,9 @@ using namespace std;
using namespace dev; using namespace dev;
using namespace dev::p2p; using namespace dev::p2p;
Session::Session(Host* _h, RLPXFrameCoder* _io, std::shared_ptr<RLPXSocket> const& _s, std::shared_ptr<Peer> const& _n, PeerSessionInfo _info): Session::Session(Host* _h, unique_ptr<RLPXFrameCoder>&& _io, std::shared_ptr<RLPXSocket> const& _s, std::shared_ptr<Peer> const& _n, PeerSessionInfo _info):
m_server(_h), m_server(_h),
m_io(_io), m_io(move(_io)),
m_socket(_s), m_socket(_s),
m_peer(_n), m_peer(_n),
m_info(_info), m_info(_info),
@ -69,7 +69,6 @@ Session::~Session()
} }
} }
catch (...){} catch (...){}
delete m_io;
} }
ReputationManager& Session::repMan() const ReputationManager& Session::repMan() const

4
libp2p/Session.h

@ -55,7 +55,7 @@ class Session: public std::enable_shared_from_this<Session>
friend class HostCapabilityFace; friend class HostCapabilityFace;
public: public:
Session(Host* _server, RLPXFrameCoder* _io, std::shared_ptr<RLPXSocket> const& _s, std::shared_ptr<Peer> const& _n, PeerSessionInfo _info); Session(Host* _server, std::unique_ptr<RLPXFrameCoder>&& _io, std::shared_ptr<RLPXSocket> const& _s, std::shared_ptr<Peer> const& _n, PeerSessionInfo _info);
virtual ~Session(); virtual ~Session();
void start(); void start();
@ -113,7 +113,7 @@ private:
Host* m_server; ///< The host that owns us. Never null. Host* m_server; ///< The host that owns us. Never null.
RLPXFrameCoder* m_io; ///< Transport over which packets are sent. std::unique_ptr<RLPXFrameCoder> m_io; ///< Transport over which packets are sent.
std::shared_ptr<RLPXSocket> m_socket; ///< Socket of peer's connection. std::shared_ptr<RLPXSocket> m_socket; ///< Socket of peer's connection.
Mutex x_writeQueue; ///< Mutex for the write queue. Mutex x_writeQueue; ///< Mutex for the write queue.
std::deque<bytes> m_writeQueue; ///< The write queue. std::deque<bytes> m_writeQueue; ///< The write queue.

4
libp2p/UPnP.cpp

@ -40,8 +40,8 @@ using namespace dev::p2p;
UPnP::UPnP() UPnP::UPnP()
{ {
#if ETH_MINIUPNPC #if ETH_MINIUPNPC
m_urls.reset(new UPNPUrls); m_urls = make_shared<UPNPUrls>();
m_data.reset(new IGDdatas); m_data = make_shared<IGDdatas>();
m_ok = false; m_ok = false;

4
libp2p/UPnP.h

@ -50,8 +50,8 @@ public:
private: private:
std::set<int> m_reg; std::set<int> m_reg;
bool m_ok; bool m_ok;
std::shared_ptr<struct UPNPUrls> m_urls; std::shared_ptr<UPNPUrls> m_urls;
std::shared_ptr<struct IGDdatas> m_data; std::shared_ptr<IGDdatas> m_data;
}; };
} }

2
libwebthree/WebThree.cpp

@ -64,7 +64,7 @@ WebThreeDirect::WebThreeDirect(
} }
if (_interfaces.count("shh")) if (_interfaces.count("shh"))
m_whisper = m_net.registerCapability<WhisperHost>(new WhisperHost); m_whisper = m_net.registerCapability(make_shared<WhisperHost>());
} }
WebThreeDirect::~WebThreeDirect() WebThreeDirect::~WebThreeDirect()

2
mix/CMakeLists.txt

@ -21,7 +21,7 @@ if (("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") AND NOT (CMAKE_CXX_COMPILER_VER
endif () endif ()
find_package (Qt5WebEngine) find_package (Qt5WebEngine)
if (APPLE) if (APPLE AND (NOT "${Qt5Core_VERSION_STRING}" VERSION_LESS "5.5"))
# TODO: remove indirect dependencies once macdeployqt is fixed # TODO: remove indirect dependencies once macdeployqt is fixed
find_package (Qt5WebEngineCore) find_package (Qt5WebEngineCore)
find_package (Qt5DBus) find_package (Qt5DBus)

4
secp256k1/libsecp256k1-config.h

@ -90,7 +90,7 @@
#if defined(__x86_64__) || defined(_M_X64) #if defined(__x86_64__) || defined(_M_X64)
#define USE_FIELD_5X52 1 #define USE_FIELD_5X52 1
#elif defined(__i386) || defined(_M_IX86) #elif defined(__i386) || defined(_M_IX86) || defined(__arm__) || defined(__M_ARM)
#define USE_FIELD_10X26 1 #define USE_FIELD_10X26 1
#endif #endif
@ -108,7 +108,7 @@
#if defined(__x86_64__) || defined(_M_X64) #if defined(__x86_64__) || defined(_M_X64)
#define USE_SCALAR_4X64 1 #define USE_SCALAR_4X64 1
#elif defined(__i386) || defined(_M_IX86) #elif defined(__i386) || defined(_M_IX86) || defined(__arm__) || defined(__M_ARM)
#define USE_SCALAR_8X32 1 #define USE_SCALAR_8X32 1
#endif #endif

59
test/TestHelper.cpp

@ -191,7 +191,7 @@ void ImportTest::importState(json_spirit::mObject& _o, State& _state)
BOOST_THROW_EXCEPTION(MissingFields() << errinfo_comment("Import State: Missing state fields!")); BOOST_THROW_EXCEPTION(MissingFields() << errinfo_comment("Import State: Missing state fields!"));
} }
void ImportTest::importTransaction(json_spirit::mObject& _o) void ImportTest::importTransaction (json_spirit::mObject const& _o, eth::Transaction& o_tr)
{ {
if (_o.count("secretKey") > 0) if (_o.count("secretKey") > 0)
{ {
@ -202,18 +202,18 @@ void ImportTest::importTransaction(json_spirit::mObject& _o)
assert(_o.count("value") > 0); assert(_o.count("value") > 0);
assert(_o.count("data") > 0); assert(_o.count("data") > 0);
if (bigint(_o["nonce"].get_str()) >= c_max256plus1) if (bigint(_o.at("nonce").get_str()) >= c_max256plus1)
BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'nonce' is equal or greater than 2**256") ); BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'nonce' is equal or greater than 2**256") );
if (bigint(_o["gasPrice"].get_str()) >= c_max256plus1) if (bigint(_o.at("gasPrice").get_str()) >= c_max256plus1)
BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'gasPrice' is equal or greater than 2**256") ); BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'gasPrice' is equal or greater than 2**256") );
if (bigint(_o["gasLimit"].get_str()) >= c_max256plus1) if (bigint(_o.at("gasLimit").get_str()) >= c_max256plus1)
BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'gasLimit' is equal or greater than 2**256") ); BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'gasLimit' is equal or greater than 2**256") );
if (bigint(_o["value"].get_str()) >= c_max256plus1) if (bigint(_o.at("value").get_str()) >= c_max256plus1)
BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'value' is equal or greater than 2**256") ); BOOST_THROW_EXCEPTION(ValueTooLarge() << errinfo_comment("Transaction 'value' is equal or greater than 2**256") );
m_transaction = _o["to"].get_str().empty() ? o_tr = _o.at("to").get_str().empty() ?
Transaction(toInt(_o["value"]), toInt(_o["gasPrice"]), toInt(_o["gasLimit"]), importData(_o), toInt(_o["nonce"]), Secret(_o["secretKey"].get_str())) : Transaction(toInt(_o.at("value")), toInt(_o.at("gasPrice")), toInt(_o.at("gasLimit")), importData(_o), toInt(_o.at("nonce")), Secret(_o.at("secretKey").get_str())) :
Transaction(toInt(_o["value"]), toInt(_o["gasPrice"]), toInt(_o["gasLimit"]), Address(_o["to"].get_str()), importData(_o), toInt(_o["nonce"]), Secret(_o["secretKey"].get_str())); Transaction(toInt(_o.at("value")), toInt(_o.at("gasPrice")), toInt(_o.at("gasLimit")), Address(_o.at("to").get_str()), importData(_o), toInt(_o.at("nonce")), Secret(_o.at("secretKey").get_str()));
} }
else else
{ {
@ -221,14 +221,14 @@ void ImportTest::importTransaction(json_spirit::mObject& _o)
RLP transactionRLP(transactionRLPStream.out()); RLP transactionRLP(transactionRLPStream.out());
try try
{ {
m_transaction = Transaction(transactionRLP.data(), CheckTransaction::Everything); o_tr = Transaction(transactionRLP.data(), CheckTransaction::Everything);
} }
catch (InvalidSignature) catch (InvalidSignature)
{ {
// create unsigned transaction // create unsigned transaction
m_transaction = _o["to"].get_str().empty() ? o_tr = _o.at("to").get_str().empty() ?
Transaction(toInt(_o["value"]), toInt(_o["gasPrice"]), toInt(_o["gasLimit"]), importData(_o), toInt(_o["nonce"])) : Transaction(toInt(_o.at("value")), toInt(_o.at("gasPrice")), toInt(_o.at("gasLimit")), importData(_o), toInt(_o.at("nonce"))) :
Transaction(toInt(_o["value"]), toInt(_o["gasPrice"]), toInt(_o["gasLimit"]), Address(_o["to"].get_str()), importData(_o), toInt(_o["nonce"])); Transaction(toInt(_o.at("value")), toInt(_o.at("gasPrice")), toInt(_o.at("gasLimit")), Address(_o.at("to").get_str()), importData(_o), toInt(_o.at("nonce")));
} }
catch (Exception& _e) catch (Exception& _e)
{ {
@ -237,6 +237,11 @@ void ImportTest::importTransaction(json_spirit::mObject& _o)
} }
} }
void ImportTest::importTransaction(json_spirit::mObject const& o_tr)
{
importTransaction(o_tr, m_transaction);
}
void ImportTest::compareStates(State const& _stateExpect, State const& _statePost, AccountMaskMap const _expectedStateOptions, WhenError _throw) void ImportTest::compareStates(State const& _stateExpect, State const& _statePost, AccountMaskMap const _expectedStateOptions, WhenError _throw)
{ {
#define CHECK(a,b) \ #define CHECK(a,b) \
@ -421,13 +426,13 @@ bytes importByteArray(std::string const& _str)
return fromHex(_str.substr(0, 2) == "0x" ? _str.substr(2) : _str, WhenError::Throw); return fromHex(_str.substr(0, 2) == "0x" ? _str.substr(2) : _str, WhenError::Throw);
} }
bytes importData(json_spirit::mObject& _o) bytes importData(json_spirit::mObject const& _o)
{ {
bytes data; bytes data;
if (_o["data"].type() == json_spirit::str_type) if (_o.at("data").type() == json_spirit::str_type)
data = importByteArray(_o["data"].get_str()); data = importByteArray(_o.at("data").get_str());
else else
for (auto const& j: _o["data"].get_array()) for (auto const& j: _o.at("data").get_array())
data.push_back(toByte(j)); data.push_back(toByte(j));
return data; return data;
} }
@ -633,46 +638,46 @@ void executeTests(const string& _name, const string& _testPathAppendix, const bo
} }
} }
RLPStream createRLPStreamFromTransactionFields(json_spirit::mObject& _tObj) RLPStream createRLPStreamFromTransactionFields(json_spirit::mObject const& _tObj)
{ {
//Construct Rlp of the given transaction //Construct Rlp of the given transaction
RLPStream rlpStream; RLPStream rlpStream;
rlpStream.appendList(_tObj.size()); rlpStream.appendList(_tObj.size());
if (_tObj.count("nonce")) if (_tObj.count("nonce"))
rlpStream << bigint(_tObj["nonce"].get_str()); rlpStream << bigint(_tObj.at("nonce").get_str());
if (_tObj.count("gasPrice")) if (_tObj.count("gasPrice"))
rlpStream << bigint(_tObj["gasPrice"].get_str()); rlpStream << bigint(_tObj.at("gasPrice").get_str());
if (_tObj.count("gasLimit")) if (_tObj.count("gasLimit"))
rlpStream << bigint(_tObj["gasLimit"].get_str()); rlpStream << bigint(_tObj.at("gasLimit").get_str());
if (_tObj.count("to")) if (_tObj.count("to"))
{ {
if (_tObj["to"].get_str().empty()) if (_tObj.at("to").get_str().empty())
rlpStream << ""; rlpStream << "";
else else
rlpStream << importByteArray(_tObj["to"].get_str()); rlpStream << importByteArray(_tObj.at("to").get_str());
} }
if (_tObj.count("value")) if (_tObj.count("value"))
rlpStream << bigint(_tObj["value"].get_str()); rlpStream << bigint(_tObj.at("value").get_str());
if (_tObj.count("data")) if (_tObj.count("data"))
rlpStream << importData(_tObj); rlpStream << importData(_tObj);
if (_tObj.count("v")) if (_tObj.count("v"))
rlpStream << bigint(_tObj["v"].get_str()); rlpStream << bigint(_tObj.at("v").get_str());
if (_tObj.count("r")) if (_tObj.count("r"))
rlpStream << bigint(_tObj["r"].get_str()); rlpStream << bigint(_tObj.at("r").get_str());
if (_tObj.count("s")) if (_tObj.count("s"))
rlpStream << bigint(_tObj["s"].get_str()); rlpStream << bigint(_tObj.at("s").get_str());
if (_tObj.count("extrafield")) if (_tObj.count("extrafield"))
rlpStream << bigint(_tObj["extrafield"].get_str()); rlpStream << bigint(_tObj.at("extrafield").get_str());
return rlpStream; return rlpStream;
} }

8
test/TestHelper.h

@ -32,7 +32,6 @@
#include <libevm/ExtVMFace.h> #include <libevm/ExtVMFace.h>
#include <libtestutils/Common.h> #include <libtestutils/Common.h>
#ifdef NOBOOST #ifdef NOBOOST
#define TBOOST_REQUIRE(arg) if(arg == false) throw dev::Exception(); #define TBOOST_REQUIRE(arg) if(arg == false) throw dev::Exception();
#define TBOOST_REQUIRE_EQUAL(arg1, arg2) if(arg1 != arg2) throw dev::Exception(); #define TBOOST_REQUIRE_EQUAL(arg1, arg2) if(arg1 != arg2) throw dev::Exception();
@ -139,7 +138,8 @@ public:
void importEnv(json_spirit::mObject& _o); void importEnv(json_spirit::mObject& _o);
static void importState(json_spirit::mObject& _o, eth::State& _state); static void importState(json_spirit::mObject& _o, eth::State& _state);
static void importState(json_spirit::mObject& _o, eth::State& _state, eth::AccountMaskMap& o_mask); static void importState(json_spirit::mObject& _o, eth::State& _state, eth::AccountMaskMap& o_mask);
void importTransaction(json_spirit::mObject& _o); static void importTransaction (json_spirit::mObject const& _o, eth::Transaction& o_tr);
void importTransaction(json_spirit::mObject const& _o);
static json_spirit::mObject& makeAllFieldsHex(json_spirit::mObject& _o); static json_spirit::mObject& makeAllFieldsHex(json_spirit::mObject& _o);
bytes executeTest(); bytes executeTest();
@ -168,7 +168,7 @@ protected:
u256 toInt(json_spirit::mValue const& _v); u256 toInt(json_spirit::mValue const& _v);
byte toByte(json_spirit::mValue const& _v); byte toByte(json_spirit::mValue const& _v);
bytes importCode(json_spirit::mObject& _o); bytes importCode(json_spirit::mObject& _o);
bytes importData(json_spirit::mObject& _o); bytes importData(json_spirit::mObject const& _o);
bytes importByteArray(std::string const& _str); bytes importByteArray(std::string const& _str);
eth::LogEntries importLog(json_spirit::mArray& _o); eth::LogEntries importLog(json_spirit::mArray& _o);
json_spirit::mArray exportLog(eth::LogEntries _logs); json_spirit::mArray exportLog(eth::LogEntries _logs);
@ -193,7 +193,7 @@ dev::eth::Ethash::BlockHeader constructHeader(
void updateEthashSeal(dev::eth::Ethash::BlockHeader& _header, h256 const& _mixHash, dev::eth::Nonce const& _nonce); void updateEthashSeal(dev::eth::Ethash::BlockHeader& _header, h256 const& _mixHash, dev::eth::Nonce const& _nonce);
void executeTests(const std::string& _name, const std::string& _testPathAppendix, const boost::filesystem::path _pathToFiller, std::function<void(json_spirit::mValue&, bool)> doTests); void executeTests(const std::string& _name, const std::string& _testPathAppendix, const boost::filesystem::path _pathToFiller, std::function<void(json_spirit::mValue&, bool)> doTests);
void userDefinedTest(std::function<void(json_spirit::mValue&, bool)> doTests); void userDefinedTest(std::function<void(json_spirit::mValue&, bool)> doTests);
RLPStream createRLPStreamFromTransactionFields(json_spirit::mObject& _tObj); RLPStream createRLPStreamFromTransactionFields(json_spirit::mObject const& _tObj);
eth::LastHashes lastHashes(u256 _currentBlockNumber); eth::LastHashes lastHashes(u256 _currentBlockNumber);
json_spirit::mObject fillJsonWithState(eth::State _state); json_spirit::mObject fillJsonWithState(eth::State _state);
json_spirit::mObject fillJsonWithTransaction(eth::Transaction _txn); json_spirit::mObject fillJsonWithTransaction(eth::Transaction _txn);

144
test/libethereum/AccountDiff.cpp

@ -0,0 +1,144 @@
/*
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 AccountDiff.cpp
* @author Dimitry Khokhlov <Dimitry@ethdev.com>
* @date 2015
* libethereum unit test functions coverage.
*/
#include <boost/filesystem/operations.hpp>
#include <boost/test/unit_test.hpp>
#include <test/TestHelper.h>
#include "../JsonSpiritHeaders.h"
#include <libdevcore/TransientDirectory.h>
#include <libethereum/Defaults.h>
#include <libethereum/AccountDiff.h>
#include <libethereum/BlockChain.h>
#include <libethereum/BlockQueue.h>
using namespace dev;
using namespace eth;
BOOST_AUTO_TEST_SUITE(libethereum)
BOOST_AUTO_TEST_CASE(AccountDiff)
{
dev::eth::AccountDiff accDiff;
// Testing changeType
// exist = true exist_from = true AccountChange::Deletion
accDiff.exist = dev::Diff<bool>(true, false);
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::Deletion, "Account change type expected to be Deletion!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), "XXX") == 0, "Deletion lead expected to be 'XXX'!");
// exist = true exist_from = false AccountChange::Creation
accDiff.exist = dev::Diff<bool>(false, true);
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::Creation, "Account change type expected to be Creation!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), "+++") == 0, "Creation lead expected to be '+++'!");
// exist = false bn = true sc = true AccountChange::All
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 2);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("01"));
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::All, "Account change type expected to be All!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), "***") == 0, "All lead expected to be '***'!");
// exist = false bn = true sc = false AccountChange::Intrinsic
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 2);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("00"));
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::Intrinsic, "Account change type expected to be Intrinsic!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), " * ") == 0, "Intrinsic lead expected to be ' * '!");
// exist = false bn = false sc = true AccountChange::CodeStorage
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 1);
accDiff.balance = dev::Diff<dev::u256>(1, 1);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("01"));
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::CodeStorage, "Account change type expected to be CodeStorage!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), "* *") == 0, "CodeStorage lead expected to be '* *'!");
// exist = false bn = false sc = false AccountChange::None
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 1);
accDiff.balance = dev::Diff<dev::u256>(1, 1);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("00"));
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::None, "Account change type expected to be None!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), " ") == 0, "None lead expected to be ' '!");
//ofstream
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 2);
accDiff.balance = dev::Diff<dev::u256>(1, 2);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("01"));
std::map<dev::u256, dev::Diff<dev::u256>> storage;
storage[1] = accDiff.nonce;
accDiff.storage = storage;
std::stringstream buffer;
//if (!_s.exist.to())
buffer << accDiff;
BOOST_CHECK_MESSAGE(buffer.str() == "", "Not expected output: '" + buffer.str() + "'");
buffer.str(std::string());
accDiff.exist = dev::Diff<bool>(false, true);
buffer << accDiff;
BOOST_CHECK_MESSAGE(buffer.str() == "#2 (+1) 2 (+1) $[1] ([0]) \n * 0000000000000000000000000000000000000000000000000000000000000001: 2 (1)", "Not expected output: '" + buffer.str() + "'");
buffer.str(std::string());
storage[1] = dev::Diff<dev::u256>(0, 0);
accDiff.storage = storage;
buffer << accDiff;
BOOST_CHECK_MESSAGE(buffer.str() == "#2 (+1) 2 (+1) $[1] ([0]) \n + 0000000000000000000000000000000000000000000000000000000000000001: 0", "Not expected output: '" + buffer.str() + "'");
buffer.str(std::string());
storage[1] = dev::Diff<dev::u256>(1, 0);
accDiff.storage = storage;
buffer << accDiff;
BOOST_CHECK_MESSAGE(buffer.str() == "#2 (+1) 2 (+1) $[1] ([0]) \nXXX 0000000000000000000000000000000000000000000000000000000000000001 (1)", "Not expected output: '" + buffer.str() + "'");
buffer.str(std::string());
BOOST_CHECK_MESSAGE(accDiff.changed() == true, "dev::eth::AccountDiff::changed(): incorrect return value");
//unexpected value
//BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead((dev::eth::AccountChange)123), "") != 0, "Not expected output when dev::eth::lead on unexpected value");
}
BOOST_AUTO_TEST_CASE(StateDiff)
{
dev::eth::StateDiff stateDiff;
dev::eth::AccountDiff accDiff;
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 2);
accDiff.balance = dev::Diff<dev::u256>(1, 2);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("01"));
std::map<dev::u256, dev::Diff<dev::u256>> storage;
storage[1] = accDiff.nonce;
accDiff.storage = storage;
std::stringstream buffer;
dev::Address address("001122334455667788991011121314151617181920");
stateDiff.accounts[address] = accDiff;
buffer << stateDiff;
BOOST_CHECK_MESSAGE(buffer.str() == "1 accounts changed:\n*** 0000000000000000000000000000000000000000: \n", "Not expected output: '" + buffer.str() + "'");
}
BOOST_AUTO_TEST_SUITE_END()

7
test/libethereum/transactionTests.cpp

@ -34,9 +34,14 @@ void doTransactionTests(json_spirit::mValue& _v, bool _fillin)
{ {
for (auto& i: _v.get_obj()) for (auto& i: _v.get_obj())
{ {
cerr << i.first << endl;
mObject& o = i.second.get_obj(); mObject& o = i.second.get_obj();
if (test::Options::get().singleTest && test::Options::get().singleTestName != i.first)
{
o.clear();
continue;
}
cerr << i.first << endl;
if (_fillin) if (_fillin)
{ {
TBOOST_REQUIRE((o.count("transaction") > 0)); TBOOST_REQUIRE((o.count("transaction") > 0));

4
test/libp2p/capability.cpp

@ -110,11 +110,11 @@ BOOST_AUTO_TEST_CASE(capability)
NetworkPreferences prefs2(localhost, 30302, false); NetworkPreferences prefs2(localhost, 30302, false);
Host host1("Test", prefs1); Host host1("Test", prefs1);
auto thc1 = host1.registerCapability(new TestHostCapability()); auto thc1 = host1.registerCapability(make_shared<TestHostCapability>());
host1.start(); host1.start();
Host host2("Test", prefs2); Host host2("Test", prefs2);
auto thc2 = host2.registerCapability(new TestHostCapability()); auto thc2 = host2.registerCapability(make_shared<TestHostCapability>());
host2.start(); host2.start();
int const step = 10; int const step = 10;

8
test/libwhisper/shhrpc.cpp

@ -121,7 +121,7 @@ BOOST_AUTO_TEST_CASE(basic)
NetworkPreferences prefs2("127.0.0.1", port2, false); NetworkPreferences prefs2("127.0.0.1", port2, false);
string const version2 = "shhrpc-host2"; string const version2 = "shhrpc-host2";
Host host2(version2, prefs2); Host host2(version2, prefs2);
auto whost2 = host2.registerCapability(new WhisperHost()); auto whost2 = host2.registerCapability(make_shared<WhisperHost>());
host2.start(); host2.start();
for (unsigned i = 0; i < 3000 && !host2.haveNetwork(); i += step) for (unsigned i = 0; i < 3000 && !host2.haveNetwork(); i += step)
@ -169,7 +169,7 @@ BOOST_AUTO_TEST_CASE(send)
Host host2("shhrpc-host2", NetworkPreferences("127.0.0.1", port2, false)); Host host2("shhrpc-host2", NetworkPreferences("127.0.0.1", port2, false));
host2.setIdealPeerCount(1); host2.setIdealPeerCount(1);
auto whost2 = host2.registerCapability(new WhisperHost()); auto whost2 = host2.registerCapability(make_shared<WhisperHost>());
host2.start(); host2.start();
web3->startNetwork(); web3->startNetwork();
@ -239,7 +239,7 @@ BOOST_AUTO_TEST_CASE(receive)
uint16_t port2 = 30338; uint16_t port2 = 30338;
Host host2("shhrpc-host2", NetworkPreferences("127.0.0.1", port2, false)); Host host2("shhrpc-host2", NetworkPreferences("127.0.0.1", port2, false));
host2.setIdealPeerCount(1); host2.setIdealPeerCount(1);
auto whost2 = host2.registerCapability(new WhisperHost()); auto whost2 = host2.registerCapability(make_shared<WhisperHost>());
host2.start(); host2.start();
web3->startNetwork(); web3->startNetwork();
@ -379,7 +379,7 @@ BOOST_AUTO_TEST_CASE(server)
uint16_t port2 = 30339; uint16_t port2 = 30339;
Host host2("shhrpc-host2", NetworkPreferences("127.0.0.1", port2, false)); Host host2("shhrpc-host2", NetworkPreferences("127.0.0.1", port2, false));
host2.setIdealPeerCount(1); host2.setIdealPeerCount(1);
auto whost2 = host2.registerCapability(new WhisperHost()); auto whost2 = host2.registerCapability(make_shared<WhisperHost>());
host2.start(); host2.start();
b = jsonrpcServer->admin_net_start(sess2); b = jsonrpcServer->admin_net_start(sess2);

12
test/libwhisper/whisperDB.cpp

@ -143,7 +143,7 @@ BOOST_AUTO_TEST_CASE(messages)
{ {
p2p::Host h("Test"); p2p::Host h("Test");
auto wh = h.registerCapability(new WhisperHost(true)); auto wh = h.registerCapability(make_shared<WhisperHost>(true));
preexisting = wh->all(); preexisting = wh->all();
cnote << preexisting.size() << "preexisting messages in DB"; cnote << preexisting.size() << "preexisting messages in DB";
wh->installWatch(BuildTopic("test")); wh->installWatch(BuildTopic("test"));
@ -156,7 +156,7 @@ BOOST_AUTO_TEST_CASE(messages)
{ {
p2p::Host h("Test"); p2p::Host h("Test");
auto wh = h.registerCapability(new WhisperHost(true)); auto wh = h.registerCapability(make_shared<WhisperHost>(true));
map<h256, Envelope> m2 = wh->all(); map<h256, Envelope> m2 = wh->all();
wh->installWatch(BuildTopic("test")); wh->installWatch(BuildTopic("test"));
BOOST_REQUIRE_EQUAL(m1.size(), m2.size()); BOOST_REQUIRE_EQUAL(m1.size(), m2.size());
@ -204,7 +204,7 @@ BOOST_AUTO_TEST_CASE(corruptedData)
{ {
p2p::Host h("Test"); p2p::Host h("Test");
auto wh = h.registerCapability(new WhisperHost(true)); auto wh = h.registerCapability(make_shared<WhisperHost>(true));
m = wh->all(); m = wh->all();
BOOST_REQUIRE(m.end() == m.find(x)); BOOST_REQUIRE(m.end() == m.find(x));
} }
@ -228,7 +228,7 @@ BOOST_AUTO_TEST_CASE(filters)
{ {
WhisperFiltersDB db; WhisperFiltersDB db;
p2p::Host h("Test"); p2p::Host h("Test");
auto wh = h.registerCapability(new WhisperHost()); auto wh = h.registerCapability(make_shared<WhisperHost>());
wh->installWatch(BuildTopic("t1")); wh->installWatch(BuildTopic("t1"));
wh->installWatch(BuildTopic("t2")); wh->installWatch(BuildTopic("t2"));
db.saveTopicsToDB(*wh, persistID); db.saveTopicsToDB(*wh, persistID);
@ -243,7 +243,7 @@ BOOST_AUTO_TEST_CASE(filters)
Host host1("Test", NetworkPreferences("127.0.0.1", port1, false)); Host host1("Test", NetworkPreferences("127.0.0.1", port1, false));
host1.setIdealPeerCount(1); host1.setIdealPeerCount(1);
auto whost1 = host1.registerCapability(new WhisperHost()); auto whost1 = host1.registerCapability(make_shared<WhisperHost>());
host1.start(); host1.start();
WhisperFiltersDB db; WhisperFiltersDB db;
auto watches = db.restoreTopicsFromDB(whost1.get(), persistID); auto watches = db.restoreTopicsFromDB(whost1.get(), persistID);
@ -277,7 +277,7 @@ BOOST_AUTO_TEST_CASE(filters)
Host host2("Test", NetworkPreferences("127.0.0.1", 30309, false)); Host host2("Test", NetworkPreferences("127.0.0.1", 30309, false));
host2.setIdealPeerCount(1); host2.setIdealPeerCount(1);
auto whost2 = host2.registerCapability(new WhisperHost()); auto whost2 = host2.registerCapability(make_shared<WhisperHost>());
host2.start(); host2.start();
for (unsigned i = 0; i < 3000 && !host1.haveNetwork(); i += step) for (unsigned i = 0; i < 3000 && !host1.haveNetwork(); i += step)

22
test/libwhisper/whisperTopic.cpp

@ -52,7 +52,7 @@ BOOST_AUTO_TEST_CASE(topic)
uint16_t port1 = 30311; uint16_t port1 = 30311;
Host host1("Test", NetworkPreferences("127.0.0.1", port1, false)); Host host1("Test", NetworkPreferences("127.0.0.1", port1, false));
host1.setIdealPeerCount(1); host1.setIdealPeerCount(1);
auto whost1 = host1.registerCapability(new WhisperHost()); auto whost1 = host1.registerCapability(make_shared<WhisperHost>());
host1.start(); host1.start();
bool host1Ready = false; bool host1Ready = false;
@ -85,7 +85,7 @@ BOOST_AUTO_TEST_CASE(topic)
Host host2("Test", NetworkPreferences("127.0.0.1", 30310, false)); Host host2("Test", NetworkPreferences("127.0.0.1", 30310, false));
host2.setIdealPeerCount(1); host2.setIdealPeerCount(1);
auto whost2 = host2.registerCapability(new WhisperHost()); auto whost2 = host2.registerCapability(make_shared<WhisperHost>());
host2.start(); host2.start();
for (unsigned i = 0; i < 3000 && (!host1.haveNetwork() || !host2.haveNetwork()); i += step) for (unsigned i = 0; i < 3000 && (!host1.haveNetwork() || !host2.haveNetwork()); i += step)
@ -130,7 +130,7 @@ BOOST_AUTO_TEST_CASE(forwarding)
uint16_t port1 = 30312; uint16_t port1 = 30312;
Host host1("Listner", NetworkPreferences("127.0.0.1", port1, false)); Host host1("Listner", NetworkPreferences("127.0.0.1", port1, false));
host1.setIdealPeerCount(1); host1.setIdealPeerCount(1);
auto whost1 = host1.registerCapability(new WhisperHost()); auto whost1 = host1.registerCapability(make_shared<WhisperHost>());
host1.start(); host1.start();
while (!host1.haveNetwork()) while (!host1.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2)); this_thread::sleep_for(chrono::milliseconds(2));
@ -165,7 +165,7 @@ BOOST_AUTO_TEST_CASE(forwarding)
uint16_t port2 = 30313; uint16_t port2 = 30313;
Host host2("Forwarder", NetworkPreferences("127.0.0.1", port2, false)); Host host2("Forwarder", NetworkPreferences("127.0.0.1", port2, false));
host2.setIdealPeerCount(1); host2.setIdealPeerCount(1);
auto whost2 = host2.registerCapability(new WhisperHost()); auto whost2 = host2.registerCapability(make_shared<WhisperHost>());
host2.start(); host2.start();
while (!host2.haveNetwork()) while (!host2.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2)); this_thread::sleep_for(chrono::milliseconds(2));
@ -203,7 +203,7 @@ BOOST_AUTO_TEST_CASE(forwarding)
Host ph("Sender", NetworkPreferences("127.0.0.1", 30314, false)); Host ph("Sender", NetworkPreferences("127.0.0.1", 30314, false));
ph.setIdealPeerCount(1); ph.setIdealPeerCount(1);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost()); shared_ptr<WhisperHost> wh = ph.registerCapability(make_shared<WhisperHost>());
ph.start(); ph.start();
ph.addNode(host2.id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), port2, port2)); ph.addNode(host2.id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), port2, port2));
while (!ph.haveNetwork()) while (!ph.haveNetwork())
@ -237,7 +237,7 @@ BOOST_AUTO_TEST_CASE(asyncforwarding)
uint16_t port1 = 30315; uint16_t port1 = 30315;
Host host1("Forwarder", NetworkPreferences("127.0.0.1", port1, false)); Host host1("Forwarder", NetworkPreferences("127.0.0.1", port1, false));
host1.setIdealPeerCount(1); host1.setIdealPeerCount(1);
auto whost1 = host1.registerCapability(new WhisperHost()); auto whost1 = host1.registerCapability(make_shared<WhisperHost>());
host1.start(); host1.start();
while (!host1.haveNetwork()) while (!host1.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2)); this_thread::sleep_for(chrono::milliseconds(2));
@ -266,7 +266,7 @@ BOOST_AUTO_TEST_CASE(asyncforwarding)
{ {
Host host2("Sender", NetworkPreferences("127.0.0.1", 30316, false)); Host host2("Sender", NetworkPreferences("127.0.0.1", 30316, false));
host2.setIdealPeerCount(1); host2.setIdealPeerCount(1);
shared_ptr<WhisperHost> whost2 = host2.registerCapability(new WhisperHost()); shared_ptr<WhisperHost> whost2 = host2.registerCapability(make_shared<WhisperHost>());
host2.start(); host2.start();
while (!host2.haveNetwork()) while (!host2.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2)); this_thread::sleep_for(chrono::milliseconds(2));
@ -283,7 +283,7 @@ BOOST_AUTO_TEST_CASE(asyncforwarding)
{ {
Host ph("Listener", NetworkPreferences("127.0.0.1", 30317, false)); Host ph("Listener", NetworkPreferences("127.0.0.1", 30317, false));
ph.setIdealPeerCount(1); ph.setIdealPeerCount(1);
shared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost()); shared_ptr<WhisperHost> wh = ph.registerCapability(make_shared<WhisperHost>());
ph.start(); ph.start();
while (!ph.haveNetwork()) while (!ph.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(2)); this_thread::sleep_for(chrono::milliseconds(2));
@ -319,7 +319,7 @@ BOOST_AUTO_TEST_CASE(topicAdvertising)
Host host1("first", NetworkPreferences("127.0.0.1", 30319, false)); Host host1("first", NetworkPreferences("127.0.0.1", 30319, false));
host1.setIdealPeerCount(1); host1.setIdealPeerCount(1);
auto whost1 = host1.registerCapability(new WhisperHost()); auto whost1 = host1.registerCapability(make_shared<WhisperHost>());
host1.start(); host1.start();
while (!host1.haveNetwork()) while (!host1.haveNetwork())
this_thread::sleep_for(chrono::milliseconds(10)); this_thread::sleep_for(chrono::milliseconds(10));
@ -328,7 +328,7 @@ BOOST_AUTO_TEST_CASE(topicAdvertising)
uint16_t port2 = 30318; uint16_t port2 = 30318;
Host host2("second", NetworkPreferences("127.0.0.1", port2, false)); Host host2("second", NetworkPreferences("127.0.0.1", port2, false));
host2.setIdealPeerCount(1); host2.setIdealPeerCount(1);
auto whost2 = host2.registerCapability(new WhisperHost()); auto whost2 = host2.registerCapability(make_shared<WhisperHost>());
unsigned w2 = whost2->installWatch(BuildTopicMask("test2")); unsigned w2 = whost2->installWatch(BuildTopicMask("test2"));
host2.start(); host2.start();
@ -399,7 +399,7 @@ BOOST_AUTO_TEST_CASE(selfAddressed)
BuildTopicMask mask(text); BuildTopicMask mask(text);
Host host("first", NetworkPreferences("127.0.0.1", 30320, false)); Host host("first", NetworkPreferences("127.0.0.1", 30320, false));
auto wh = host.registerCapability(new WhisperHost()); auto wh = host.registerCapability(make_shared<WhisperHost>());
auto watch = wh->installWatch(BuildTopicMask(text)); auto watch = wh->installWatch(BuildTopicMask(text));
unsigned const sample = 0xFEED; unsigned const sample = 0xFEED;

Loading…
Cancel
Save