From a9d771e49729ba89f7047963ce3d2fd4d0750211 Mon Sep 17 00:00:00 2001
From: Oleg Girko
Date: Fri, 21 Jul 2017 10:35:19 +0100
Subject: [PATCH] Backport Bitcoin PR#8085: p2p: Begin encapsulation (#1537)
* net: move CBanDB and CAddrDB out of net.h/cpp
This will eventually solve a circular dependency
* net: Create CConnman to encapsulate p2p connections
* net: Move socket binding into CConnman
* net: move OpenNetworkConnection into CConnman
* net: move ban and addrman functions into CConnman
* net: Add oneshot functions to CConnman
* net: move added node functions to CConnman
* net: Add most functions needed for vNodes to CConnman
* net: handle nodesignals in CConnman
* net: Pass CConnection to wallet rather than using the global
* net: Add rpc error for missing/disabled p2p functionality
* net: Pass CConnman around as needed
* gui: add NodeID to the peer table
* net: create generic functor accessors and move vNodes to CConnman
* net: move whitelist functions into CConnman
* net: move nLastNodeId to CConnman
* net: move nLocalHostNonce to CConnman
This behavior seems to have been quite racy and broken.
Move nLocalHostNonce into CNode, and check received nonces against all
non-fully-connected nodes. If there's a match, assume we've connected
to ourself.
* net: move messageHandlerCondition to CConnman
* net: move send/recv statistics to CConnman
* net: move SendBufferSize/ReceiveFloodSize to CConnman
* net: move nLocalServices/nRelevantServices to CConnman
These are in-turn passed to CNode at connection time. This allows us to offer
different services to different peers (or test the effects of doing so).
* net: move semOutbound and semMasternodeOutbound to CConnman
* net: SocketSendData returns written size
* net: move max/max-outbound to CConnman
* net: Pass best block known height into CConnman
CConnman then passes the current best height into CNode at creation time.
This way CConnman/CNode have no dependency on main for height, and the signals
only move in one direction.
This also helps to prevent identity leakage a tiny bit. Before this change, an
attacker could theoretically make 2 connections on different interfaces. They
would connect fully on one, and only establish the initial connection on the
other. Once they receive a new block, they would relay it to your first
connection, and immediately commence the version handshake on the second. Since
the new block height is reflected immediately, they could attempt to learn
whether the two connections were correlated.
This is, of course, incredibly unlikely to work due to the small timings
involved and receipt from other senders. But it doesn't hurt to lock-in
nBestHeight at the time of connection, rather than letting the remote choose
the time.
* net: pass CClientUIInterface into CConnman
* net: Drop StartNode/StopNode and use CConnman directly
* net: Introduce CConnection::Options to avoid passing so many params
* net: add nSendBufferMaxSize/nReceiveFloodSize to CConnection::Options
* net: move vNodesDisconnected into CConnman
* Made the ForEachNode* functions in src/net.cpp more pragmatic and self documenting
* Convert ForEachNode* functions to take a templated function argument rather than a std::function to eliminate std::function overhead
* net: move MAX_FEELER_CONNECTIONS into connman
---
src/Makefile.am | 2 +
src/activemasternode.cpp | 41 +-
src/addrdb.cpp | 218 ++++++++++
src/addrdb.h | 103 +++++
src/darksend-relay.cpp | 3 +-
src/governance-object.cpp | 2 +-
src/governance-vote.cpp | 2 +-
src/governance.cpp | 4 +-
src/init.cpp | 64 ++-
src/instantx.cpp | 4 +-
src/main.cpp | 157 +++----
src/main.h | 10 +-
src/masternode-payments.cpp | 2 +-
src/masternode-sync.cpp | 59 +--
src/masternode.cpp | 4 +-
src/masternode.h | 2 +-
src/masternodeman.cpp | 12 +-
src/miner.cpp | 20 +-
src/miner.h | 3 +-
src/net.cpp | 845 +++++++++++++++++-------------------
src/net.h | 568 ++++++++++++++----------
src/privatesend-client.cpp | 84 ++--
src/privatesend-client.h | 13 +-
src/privatesend-server.cpp | 18 +-
src/privatesend.cpp | 4 +-
src/qt/bantablemodel.cpp | 3 +-
src/qt/clientmodel.cpp | 26 +-
src/qt/guiutil.cpp | 8 +-
src/qt/guiutil.h | 2 +-
src/qt/overviewpage.cpp | 2 +-
src/qt/peertablemodel.cpp | 21 +-
src/qt/peertablemodel.h | 7 +-
src/qt/rpcconsole.cpp | 35 +-
src/qt/walletmodel.cpp | 2 +-
src/rpc/blockchain.cpp | 4 +-
src/rpc/governance.cpp | 2 +-
src/rpc/masternode.cpp | 5 +-
src/rpc/mining.cpp | 11 +-
src/rpc/misc.cpp | 11 +-
src/rpc/net.cpp | 108 +++--
src/rpc/protocol.h | 1 +
src/rpc/rawtransaction.cpp | 8 +-
src/sendalert.cpp | 10 +-
src/spork.cpp | 2 +-
src/test/DoS_tests.cpp | 56 +--
src/test/miner_tests.cpp | 2 +-
src/test/net_tests.cpp | 6 +-
src/test/test_dash.cpp | 7 +-
src/test/test_dash.h | 2 +
src/validationinterface.cpp | 4 +-
src/validationinterface.h | 5 +-
src/wallet/rpcwallet.cpp | 15 +-
src/wallet/wallet.cpp | 20 +-
src/wallet/wallet.h | 8 +-
54 files changed, 1567 insertions(+), 1070 deletions(-)
create mode 100644 src/addrdb.cpp
create mode 100644 src/addrdb.h
diff --git a/src/Makefile.am b/src/Makefile.am
index 37a4ffa06..65fc7662b 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -70,6 +70,7 @@ endif
.PHONY: FORCE check-symbols check-security
# dash core #
BITCOIN_CORE_H = \
+ addrdb.h \
activemasternode.h \
addressindex.h \
spentindex.h \
@@ -207,6 +208,7 @@ libbitcoin_server_a_CPPFLAGS = $(AM_CPPFLAGS) $(BITCOIN_INCLUDES) $(MINIUPNPC_CP
libbitcoin_server_a_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS)
libbitcoin_server_a_SOURCES = \
addrman.cpp \
+ addrdb.cpp \
alert.cpp \
bloom.cpp \
chain.cpp \
diff --git a/src/activemasternode.cpp b/src/activemasternode.cpp
index ff51ce066..1d953f26f 100644
--- a/src/activemasternode.cpp
+++ b/src/activemasternode.cpp
@@ -151,27 +151,23 @@ void CActiveMasternode::ManageStateInitial()
return;
}
- bool fFoundLocal = false;
- {
- LOCK(cs_vNodes);
-
- // First try to find whatever local address is specified by externalip option
- fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service);
- if(!fFoundLocal) {
- // nothing and no live connections, can't do anything for now
- if (vNodes.empty()) {
- nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
- strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available.";
- LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
- return;
- }
- // We have some peers, let's try to find our local address from one of them
- BOOST_FOREACH(CNode* pnode, vNodes) {
- if (pnode->fSuccessfullyConnected && pnode->addr.IsIPv4()) {
- fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service);
- if(fFoundLocal) break;
- }
- }
+ // First try to find whatever local address is specified by externalip option
+ bool fFoundLocal = GetLocal(service) && CMasternode::IsValidNetAddr(service);
+ if(!fFoundLocal) {
+ bool empty = true;
+ // If we have some peers, let's try to find our local address from one of them
+ g_connman->ForEachNodeContinueIf([&fFoundLocal, &empty, this](CNode* pnode) {
+ empty = false;
+ if (pnode->fSuccessfullyConnected && pnode->addr.IsIPv4())
+ fFoundLocal = GetLocal(service, &pnode->addr) && CMasternode::IsValidNetAddr(service);
+ return !fFoundLocal;
+ });
+ // nothing and no live connections, can't do anything for now
+ if (empty) {
+ nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
+ strNotCapableReason = "Can't detect valid external address. Will retry when there are some connections available.";
+ LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
+ return;
}
}
@@ -199,7 +195,8 @@ void CActiveMasternode::ManageStateInitial()
LogPrintf("CActiveMasternode::ManageStateInitial -- Checking inbound connection to '%s'\n", service.ToString());
- if(!ConnectNode(CAddress(service, NODE_NETWORK), NULL, true)) {
+ // TODO: Pass CConnman instance somehow and don't use global variable.
+ if(!g_connman->ConnectNode(CAddress(service, NODE_NETWORK), NULL, true)) {
nState = ACTIVE_MASTERNODE_NOT_CAPABLE;
strNotCapableReason = "Could not connect to " + service.ToString();
LogPrintf("CActiveMasternode::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason);
diff --git a/src/addrdb.cpp b/src/addrdb.cpp
new file mode 100644
index 000000000..ddf41f92d
--- /dev/null
+++ b/src/addrdb.cpp
@@ -0,0 +1,218 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#include "addrdb.h"
+
+#include "addrman.h"
+#include "chainparams.h"
+#include "clientversion.h"
+#include "hash.h"
+#include "random.h"
+#include "streams.h"
+#include "tinyformat.h"
+#include "util.h"
+
+#include
+
+CBanDB::CBanDB()
+{
+ pathBanlist = GetDataDir() / "banlist.dat";
+}
+
+bool CBanDB::Write(const banmap_t& banSet)
+{
+ // Generate random temporary filename
+ unsigned short randv = 0;
+ GetRandBytes((unsigned char*)&randv, sizeof(randv));
+ std::string tmpfn = strprintf("banlist.dat.%04x", randv);
+
+ // serialize banlist, checksum data up to that point, then append csum
+ CDataStream ssBanlist(SER_DISK, CLIENT_VERSION);
+ ssBanlist << FLATDATA(Params().MessageStart());
+ ssBanlist << banSet;
+ uint256 hash = Hash(ssBanlist.begin(), ssBanlist.end());
+ ssBanlist << hash;
+
+ // open temp output file, and associate with CAutoFile
+ boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
+ FILE *file = fopen(pathTmp.string().c_str(), "wb");
+ CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
+ if (fileout.IsNull())
+ return error("%s: Failed to open file %s", __func__, pathTmp.string());
+
+ // Write and commit header, data
+ try {
+ fileout << ssBanlist;
+ }
+ catch (const std::exception& e) {
+ return error("%s: Serialize or I/O error - %s", __func__, e.what());
+ }
+ FileCommit(fileout.Get());
+ fileout.fclose();
+
+ // replace existing banlist.dat, if any, with new banlist.dat.XXXX
+ if (!RenameOver(pathTmp, pathBanlist))
+ return error("%s: Rename-into-place failed", __func__);
+
+ return true;
+}
+
+bool CBanDB::Read(banmap_t& banSet)
+{
+ // open input file, and associate with CAutoFile
+ FILE *file = fopen(pathBanlist.string().c_str(), "rb");
+ CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
+ if (filein.IsNull())
+ return error("%s: Failed to open file %s", __func__, pathBanlist.string());
+
+ // use file size to size memory buffer
+ uint64_t fileSize = boost::filesystem::file_size(pathBanlist);
+ uint64_t dataSize = 0;
+ // Don't try to resize to a negative number if file is small
+ if (fileSize >= sizeof(uint256))
+ dataSize = fileSize - sizeof(uint256);
+ std::vector vchData;
+ vchData.resize(dataSize);
+ uint256 hashIn;
+
+ // read data and checksum from file
+ try {
+ filein.read((char *)&vchData[0], dataSize);
+ filein >> hashIn;
+ }
+ catch (const std::exception& e) {
+ return error("%s: Deserialize or I/O error - %s", __func__, e.what());
+ }
+ filein.fclose();
+
+ CDataStream ssBanlist(vchData, SER_DISK, CLIENT_VERSION);
+
+ // verify stored checksum matches input data
+ uint256 hashTmp = Hash(ssBanlist.begin(), ssBanlist.end());
+ if (hashIn != hashTmp)
+ return error("%s: Checksum mismatch, data corrupted", __func__);
+
+ unsigned char pchMsgTmp[4];
+ try {
+ // de-serialize file header (network specific magic number) and ..
+ ssBanlist >> FLATDATA(pchMsgTmp);
+
+ // ... verify the network matches ours
+ if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
+ return error("%s: Invalid network magic number", __func__);
+
+ // de-serialize address data into one CAddrMan object
+ ssBanlist >> banSet;
+ }
+ catch (const std::exception& e) {
+ return error("%s: Deserialize or I/O error - %s", __func__, e.what());
+ }
+
+ return true;
+}
+
+CAddrDB::CAddrDB()
+{
+ pathAddr = GetDataDir() / "peers.dat";
+}
+
+bool CAddrDB::Write(const CAddrMan& addr)
+{
+ // Generate random temporary filename
+ unsigned short randv = 0;
+ GetRandBytes((unsigned char*)&randv, sizeof(randv));
+ std::string tmpfn = strprintf("peers.dat.%04x", randv);
+
+ // serialize addresses, checksum data up to that point, then append csum
+ CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
+ ssPeers << FLATDATA(Params().MessageStart());
+ ssPeers << addr;
+ uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
+ ssPeers << hash;
+
+ // open temp output file, and associate with CAutoFile
+ boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
+ FILE *file = fopen(pathTmp.string().c_str(), "wb");
+ CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
+ if (fileout.IsNull())
+ return error("%s: Failed to open file %s", __func__, pathTmp.string());
+
+ // Write and commit header, data
+ try {
+ fileout << ssPeers;
+ }
+ catch (const std::exception& e) {
+ return error("%s: Serialize or I/O error - %s", __func__, e.what());
+ }
+ FileCommit(fileout.Get());
+ fileout.fclose();
+
+ // replace existing peers.dat, if any, with new peers.dat.XXXX
+ if (!RenameOver(pathTmp, pathAddr))
+ return error("%s: Rename-into-place failed", __func__);
+
+ return true;
+}
+
+bool CAddrDB::Read(CAddrMan& addr)
+{
+ // open input file, and associate with CAutoFile
+ FILE *file = fopen(pathAddr.string().c_str(), "rb");
+ CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
+ if (filein.IsNull())
+ return error("%s: Failed to open file %s", __func__, pathAddr.string());
+
+ // use file size to size memory buffer
+ uint64_t fileSize = boost::filesystem::file_size(pathAddr);
+ uint64_t dataSize = 0;
+ // Don't try to resize to a negative number if file is small
+ if (fileSize >= sizeof(uint256))
+ dataSize = fileSize - sizeof(uint256);
+ std::vector vchData;
+ vchData.resize(dataSize);
+ uint256 hashIn;
+
+ // read data and checksum from file
+ try {
+ filein.read((char *)&vchData[0], dataSize);
+ filein >> hashIn;
+ }
+ catch (const std::exception& e) {
+ return error("%s: Deserialize or I/O error - %s", __func__, e.what());
+ }
+ filein.fclose();
+
+ CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
+
+ // verify stored checksum matches input data
+ uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
+ if (hashIn != hashTmp)
+ return error("%s: Checksum mismatch, data corrupted", __func__);
+
+ return Read(addr, ssPeers);
+}
+
+bool CAddrDB::Read(CAddrMan& addr, CDataStream& ssPeers)
+{
+ unsigned char pchMsgTmp[4];
+ try {
+ // de-serialize file header (network specific magic number) and ..
+ ssPeers >> FLATDATA(pchMsgTmp);
+
+ // ... verify the network matches ours
+ if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
+ return error("%s: Invalid network magic number", __func__);
+
+ // de-serialize address data into one CAddrMan object
+ ssPeers >> addr;
+ }
+ catch (const std::exception& e) {
+ // de-serialization has failed, ensure addrman is left in a clean state
+ addr.Clear();
+ return error("%s: Deserialize or I/O error - %s", __func__, e.what());
+ }
+
+ return true;
+}
diff --git a/src/addrdb.h b/src/addrdb.h
new file mode 100644
index 000000000..d8c66d872
--- /dev/null
+++ b/src/addrdb.h
@@ -0,0 +1,103 @@
+// Copyright (c) 2009-2010 Satoshi Nakamoto
+// Copyright (c) 2009-2015 The Bitcoin Core developers
+// Distributed under the MIT software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
+
+#ifndef BITCOIN_ADDRDB_H
+#define BITCOIN_ADDRDB_H
+
+#include "serialize.h"
+
+#include
+#include