1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #if defined(HAVE_CONFIG_H)
7 #include "config/bitcoin-config.h"
13 #include "chainparams.h"
14 #include "clientversion.h"
15 #include "primitives/transaction.h"
16 #include "scheduler.h"
17 #include "ui_interface.h"
18 #include "crypto/common.h"
27 #include <miniupnpc/miniupnpc.h>
28 #include <miniupnpc/miniwget.h>
29 #include <miniupnpc/upnpcommands.h>
30 #include <miniupnpc/upnperrors.h>
33 #include <boost/filesystem.hpp>
34 #include <boost/thread.hpp>
36 // Dump addresses to peers.dat every 15 minutes (900s)
37 #define DUMP_ADDRESSES_INTERVAL 900
39 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
40 #define MSG_NOSIGNAL 0
43 // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
44 // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
46 #ifndef PROTECTION_LEVEL_UNRESTRICTED
47 #define PROTECTION_LEVEL_UNRESTRICTED 10
49 #ifndef IPV6_PROTECTION_LEVEL
50 #define IPV6_PROTECTION_LEVEL 23
57 const int MAX_OUTBOUND_CONNECTIONS = 8;
63 ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {}
68 // Global state variables
70 bool fDiscover = true;
72 uint64_t nLocalServices = NODE_NETWORK;
73 CCriticalSection cs_mapLocalHost;
74 map<CNetAddr, LocalServiceInfo> mapLocalHost;
75 static bool vfReachable[NET_MAX] = {};
76 static bool vfLimited[NET_MAX] = {};
77 static CNode* pnodeLocalHost = NULL;
78 uint64_t nLocalHostNonce = 0;
79 static std::vector<ListenSocket> vhListenSocket;
81 int nMaxConnections = 125;
82 bool fAddressesInitialized = false;
84 vector<CNode*> vNodes;
85 CCriticalSection cs_vNodes;
86 map<CInv, CDataStream> mapRelay;
87 deque<pair<int64_t, CInv> > vRelayExpiration;
88 CCriticalSection cs_mapRelay;
89 limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
91 static deque<string> vOneShots;
92 CCriticalSection cs_vOneShots;
94 set<CNetAddr> setservAddNodeAddresses;
95 CCriticalSection cs_setservAddNodeAddresses;
97 vector<std::string> vAddedNodes;
98 CCriticalSection cs_vAddedNodes;
100 NodeId nLastNodeId = 0;
101 CCriticalSection cs_nLastNodeId;
103 static CSemaphore *semOutbound = NULL;
104 boost::condition_variable messageHandlerCondition;
106 // Signals for message handling
107 static CNodeSignals g_signals;
108 CNodeSignals& GetNodeSignals() { return g_signals; }
110 void AddOneShot(string strDest)
113 vOneShots.push_back(strDest);
116 unsigned short GetListenPort()
118 return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
121 // find 'best' local address for a particular peer
122 bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
128 int nBestReachability = -1;
130 LOCK(cs_mapLocalHost);
131 for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
133 int nScore = (*it).second.nScore;
134 int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
135 if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
137 addr = CService((*it).first, (*it).second.nPort);
138 nBestReachability = nReachability;
143 return nBestScore >= 0;
146 //! Convert the pnSeeds6 array into usable address objects.
147 static std::vector<CAddress> convertSeed6(const std::vector<SeedSpec6> &vSeedsIn)
149 // It'll only connect to one or two seed nodes because once it connects,
150 // it'll get a pile of addresses with newer timestamps.
151 // Seed nodes are given a random 'last seen time' of between one and two
153 const int64_t nOneWeek = 7*24*60*60;
154 std::vector<CAddress> vSeedsOut;
155 vSeedsOut.reserve(vSeedsIn.size());
156 for (std::vector<SeedSpec6>::const_iterator i(vSeedsIn.begin()); i != vSeedsIn.end(); ++i)
159 memcpy(&ip, i->addr, sizeof(ip));
160 CAddress addr(CService(ip, i->port));
161 addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
162 vSeedsOut.push_back(addr);
167 // get best local address for a particular peer as a CAddress
168 // Otherwise, return the unroutable 0.0.0.0 but filled in with
169 // the normal parameters, since the IP may be changed to a useful
171 CAddress GetLocalAddress(const CNetAddr *paddrPeer)
173 CAddress ret(CService("0.0.0.0",GetListenPort()),0);
175 if (GetLocal(addr, paddrPeer))
177 ret = CAddress(addr);
179 ret.nServices = nLocalServices;
180 ret.nTime = GetAdjustedTime();
184 int GetnScore(const CService& addr)
186 LOCK(cs_mapLocalHost);
187 if (mapLocalHost.count(addr) == LOCAL_NONE)
189 return mapLocalHost[addr].nScore;
192 // Is our peer's addrLocal potentially useful as an external IP source?
193 bool IsPeerAddrLocalGood(CNode *pnode)
195 return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() &&
196 !IsLimited(pnode->addrLocal.GetNetwork());
199 // pushes our own address to a peer
200 void AdvertizeLocal(CNode *pnode)
202 if (fListen && pnode->fSuccessfullyConnected)
204 CAddress addrLocal = GetLocalAddress(&pnode->addr);
205 // If discovery is enabled, sometimes give our peer the address it
206 // tells us that it sees us as in case it has a better idea of our
207 // address than we do.
208 if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
209 GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0))
211 addrLocal.SetIP(pnode->addrLocal);
213 if (addrLocal.IsRoutable())
215 pnode->PushAddress(addrLocal);
220 void SetReachable(enum Network net, bool fFlag)
222 LOCK(cs_mapLocalHost);
223 vfReachable[net] = fFlag;
224 if (net == NET_IPV6 && fFlag)
225 vfReachable[NET_IPV4] = true;
228 // learn a new local address
229 bool AddLocal(const CService& addr, int nScore)
231 if (!addr.IsRoutable())
234 if (!fDiscover && nScore < LOCAL_MANUAL)
240 LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
243 LOCK(cs_mapLocalHost);
244 bool fAlready = mapLocalHost.count(addr) > 0;
245 LocalServiceInfo &info = mapLocalHost[addr];
246 if (!fAlready || nScore >= info.nScore) {
247 info.nScore = nScore + (fAlready ? 1 : 0);
248 info.nPort = addr.GetPort();
250 SetReachable(addr.GetNetwork());
256 bool AddLocal(const CNetAddr &addr, int nScore)
258 return AddLocal(CService(addr, GetListenPort()), nScore);
261 /** Make a particular network entirely off-limits (no automatic connects to it) */
262 void SetLimited(enum Network net, bool fLimited)
264 if (net == NET_UNROUTABLE)
266 LOCK(cs_mapLocalHost);
267 vfLimited[net] = fLimited;
270 bool IsLimited(enum Network net)
272 LOCK(cs_mapLocalHost);
273 return vfLimited[net];
276 bool IsLimited(const CNetAddr &addr)
278 return IsLimited(addr.GetNetwork());
281 /** vote for a local address */
282 bool SeenLocal(const CService& addr)
285 LOCK(cs_mapLocalHost);
286 if (mapLocalHost.count(addr) == 0)
288 mapLocalHost[addr].nScore++;
294 /** check whether a given address is potentially local */
295 bool IsLocal(const CService& addr)
297 LOCK(cs_mapLocalHost);
298 return mapLocalHost.count(addr) > 0;
301 /** check whether a given network is one we can probably connect to */
302 bool IsReachable(enum Network net)
304 LOCK(cs_mapLocalHost);
305 return vfReachable[net] && !vfLimited[net];
308 /** check whether a given address is in a network we can probably connect to */
309 bool IsReachable(const CNetAddr& addr)
311 enum Network net = addr.GetNetwork();
312 return IsReachable(net);
315 void AddressCurrentlyConnected(const CService& addr)
317 addrman.Connected(addr);
321 uint64_t CNode::nTotalBytesRecv = 0;
322 uint64_t CNode::nTotalBytesSent = 0;
323 CCriticalSection CNode::cs_totalBytesRecv;
324 CCriticalSection CNode::cs_totalBytesSent;
326 CNode* FindNode(const CNetAddr& ip)
329 BOOST_FOREACH(CNode* pnode, vNodes)
330 if ((CNetAddr)pnode->addr == ip)
335 CNode* FindNode(const std::string& addrName)
338 BOOST_FOREACH(CNode* pnode, vNodes)
339 if (pnode->addrName == addrName)
344 CNode* FindNode(const CService& addr)
347 BOOST_FOREACH(CNode* pnode, vNodes)
348 if ((CService)pnode->addr == addr)
353 CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
355 if (pszDest == NULL) {
356 if (IsLocal(addrConnect))
359 // Look for an existing connection
360 CNode* pnode = FindNode((CService)addrConnect);
369 LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
370 pszDest ? pszDest : addrConnect.ToString(),
371 pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
375 bool proxyConnectionFailed = false;
376 if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) :
377 ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed))
379 addrman.Attempt(addrConnect);
382 CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
387 vNodes.push_back(pnode);
390 pnode->nTimeConnected = GetTime();
393 } else if (!proxyConnectionFailed) {
394 // If connecting to the node failed, and failure is not caused by a problem connecting to
395 // the proxy, mark this as an attempt.
396 addrman.Attempt(addrConnect);
402 void CNode::CloseSocketDisconnect()
405 if (hSocket != INVALID_SOCKET)
407 LogPrint("net", "disconnecting peer=%d\n", id);
408 CloseSocket(hSocket);
411 // in case this fails, we'll empty the recv buffer when the CNode is deleted
412 TRY_LOCK(cs_vRecvMsg, lockRecv);
417 void CNode::PushVersion()
419 int nBestHeight = g_signals.GetHeight().get_value_or(0);
421 int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
422 CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
423 CAddress addrMe = GetLocalAddress(&addr);
424 GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
426 LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id);
428 LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id);
429 PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
430 nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true);
437 std::map<CNetAddr, int64_t> CNode::setBanned;
438 CCriticalSection CNode::cs_setBanned;
440 void CNode::ClearBanned()
445 bool CNode::IsBanned(CNetAddr ip)
447 bool fResult = false;
450 std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip);
451 if (i != setBanned.end())
453 int64_t t = (*i).second;
461 bool CNode::Ban(const CNetAddr &addr) {
462 int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
465 if (setBanned[addr] < banTime)
466 setBanned[addr] = banTime;
472 std::vector<CSubNet> CNode::vWhitelistedRange;
473 CCriticalSection CNode::cs_vWhitelistedRange;
475 bool CNode::IsWhitelistedRange(const CNetAddr &addr) {
476 LOCK(cs_vWhitelistedRange);
477 BOOST_FOREACH(const CSubNet& subnet, vWhitelistedRange) {
478 if (subnet.Match(addr))
484 void CNode::AddWhitelistedRange(const CSubNet &subnet) {
485 LOCK(cs_vWhitelistedRange);
486 vWhitelistedRange.push_back(subnet);
490 #define X(name) stats.name = name
491 void CNode::copyStats(CNodeStats &stats)
493 stats.nodeid = this->GetId();
508 // It is common for nodes with good ping times to suddenly become lagged,
509 // due to a new block arriving or other large transfer.
510 // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
511 // since pingtime does not update until the ping is complete, which might take a while.
512 // So, if a ping is taking an unusually long time in flight,
513 // the caller can immediately detect that this is happening.
514 int64_t nPingUsecWait = 0;
515 if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
516 nPingUsecWait = GetTimeMicros() - nPingUsecStart;
519 // Raw ping time is in microseconds, but show it to user as whole seconds (Bitcoin users should be well used to small numbers with many decimal places by now :)
520 stats.dPingTime = (((double)nPingUsecTime) / 1e6);
521 stats.dPingWait = (((double)nPingUsecWait) / 1e6);
523 // Leave string empty if addrLocal invalid (not filled in yet)
524 stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
528 // requires LOCK(cs_vRecvMsg)
529 bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
533 // get current incomplete message, or create a new one
534 if (vRecvMsg.empty() ||
535 vRecvMsg.back().complete())
536 vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, nRecvVersion));
538 CNetMessage& msg = vRecvMsg.back();
540 // absorb network data
543 handled = msg.readHeader(pch, nBytes);
545 handled = msg.readData(pch, nBytes);
550 if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
551 LogPrint("net", "Oversized message from peer=%i, disconnecting", GetId());
558 if (msg.complete()) {
559 msg.nTime = GetTimeMicros();
560 messageHandlerCondition.notify_one();
567 int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
569 // copy data to temporary parsing buffer
570 unsigned int nRemaining = 24 - nHdrPos;
571 unsigned int nCopy = std::min(nRemaining, nBytes);
573 memcpy(&hdrbuf[nHdrPos], pch, nCopy);
576 // if header incomplete, exit
580 // deserialize to CMessageHeader
584 catch (const std::exception&) {
588 // reject messages larger than MAX_SIZE
589 if (hdr.nMessageSize > MAX_SIZE)
592 // switch state to reading message data
598 int CNetMessage::readData(const char *pch, unsigned int nBytes)
600 unsigned int nRemaining = hdr.nMessageSize - nDataPos;
601 unsigned int nCopy = std::min(nRemaining, nBytes);
603 if (vRecv.size() < nDataPos + nCopy) {
604 // Allocate up to 256 KiB ahead, but never more than the total message size.
605 vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
608 memcpy(&vRecv[nDataPos], pch, nCopy);
622 // requires LOCK(cs_vSend)
623 void SocketSendData(CNode *pnode)
625 std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
627 while (it != pnode->vSendMsg.end()) {
628 const CSerializeData &data = *it;
629 assert(data.size() > pnode->nSendOffset);
630 int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
632 pnode->nLastSend = GetTime();
633 pnode->nSendBytes += nBytes;
634 pnode->nSendOffset += nBytes;
635 pnode->RecordBytesSent(nBytes);
636 if (pnode->nSendOffset == data.size()) {
637 pnode->nSendOffset = 0;
638 pnode->nSendSize -= data.size();
641 // could not send full message; stop sending more
647 int nErr = WSAGetLastError();
648 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
650 LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
651 pnode->CloseSocketDisconnect();
654 // couldn't send anything at all
659 if (it == pnode->vSendMsg.end()) {
660 assert(pnode->nSendOffset == 0);
661 assert(pnode->nSendSize == 0);
663 pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
666 static list<CNode*> vNodesDisconnected;
668 void ThreadSocketHandler()
670 unsigned int nPrevNodeCount = 0;
678 // Disconnect unused nodes
679 vector<CNode*> vNodesCopy = vNodes;
680 BOOST_FOREACH(CNode* pnode, vNodesCopy)
682 if (pnode->fDisconnect ||
683 (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
685 // remove from vNodes
686 vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
688 // release outbound grant (if any)
689 pnode->grantOutbound.Release();
691 // close socket and cleanup
692 pnode->CloseSocketDisconnect();
694 // hold in disconnected pool until all refs are released
695 if (pnode->fNetworkNode || pnode->fInbound)
697 vNodesDisconnected.push_back(pnode);
702 // Delete disconnected nodes
703 list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
704 BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
706 // wait until threads are done using it
707 if (pnode->GetRefCount() <= 0)
709 bool fDelete = false;
711 TRY_LOCK(pnode->cs_vSend, lockSend);
714 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
717 TRY_LOCK(pnode->cs_inventory, lockInv);
725 vNodesDisconnected.remove(pnode);
731 if(vNodes.size() != nPrevNodeCount) {
732 nPrevNodeCount = vNodes.size();
733 uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
737 // Find which sockets have data to receive
739 struct timeval timeout;
741 timeout.tv_usec = 50000; // frequency to poll pnode->vSend
748 FD_ZERO(&fdsetError);
749 SOCKET hSocketMax = 0;
750 bool have_fds = false;
752 BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) {
753 FD_SET(hListenSocket.socket, &fdsetRecv);
754 hSocketMax = max(hSocketMax, hListenSocket.socket);
760 BOOST_FOREACH(CNode* pnode, vNodes)
762 if (pnode->hSocket == INVALID_SOCKET)
764 FD_SET(pnode->hSocket, &fdsetError);
765 hSocketMax = max(hSocketMax, pnode->hSocket);
768 // Implement the following logic:
769 // * If there is data to send, select() for sending data. As this only
770 // happens when optimistic write failed, we choose to first drain the
771 // write buffer in this case before receiving more. This avoids
772 // needlessly queueing received data, if the remote peer is not themselves
773 // receiving data. This means properly utilizing TCP flow control signalling.
774 // * Otherwise, if there is no (complete) message in the receive buffer,
775 // or there is space left in the buffer, select() for receiving data.
776 // * (if neither of the above applies, there is certainly one message
777 // in the receiver buffer ready to be processed).
778 // Together, that means that at least one of the following is always possible,
779 // so we don't deadlock:
780 // * We send some data.
781 // * We wait for data to be received (and disconnect after timeout).
782 // * We process a message in the buffer (message handler thread).
784 TRY_LOCK(pnode->cs_vSend, lockSend);
785 if (lockSend && !pnode->vSendMsg.empty()) {
786 FD_SET(pnode->hSocket, &fdsetSend);
791 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
793 pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
794 pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
795 FD_SET(pnode->hSocket, &fdsetRecv);
800 int nSelect = select(have_fds ? hSocketMax + 1 : 0,
801 &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
802 boost::this_thread::interruption_point();
804 if (nSelect == SOCKET_ERROR)
808 int nErr = WSAGetLastError();
809 LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
810 for (unsigned int i = 0; i <= hSocketMax; i++)
811 FD_SET(i, &fdsetRecv);
814 FD_ZERO(&fdsetError);
815 MilliSleep(timeout.tv_usec/1000);
819 // Accept new connections
821 BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket)
823 if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv))
825 struct sockaddr_storage sockaddr;
826 socklen_t len = sizeof(sockaddr);
827 SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
831 if (hSocket != INVALID_SOCKET)
832 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
833 LogPrintf("Warning: Unknown socket family\n");
835 bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr);
838 BOOST_FOREACH(CNode* pnode, vNodes)
843 if (hSocket == INVALID_SOCKET)
845 int nErr = WSAGetLastError();
846 if (nErr != WSAEWOULDBLOCK)
847 LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
849 else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS)
851 CloseSocket(hSocket);
853 else if (CNode::IsBanned(addr) && !whitelisted)
855 LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
856 CloseSocket(hSocket);
860 CNode* pnode = new CNode(hSocket, addr, "", true);
862 pnode->fWhitelisted = whitelisted;
866 vNodes.push_back(pnode);
873 // Service each socket
875 vector<CNode*> vNodesCopy;
879 BOOST_FOREACH(CNode* pnode, vNodesCopy)
882 BOOST_FOREACH(CNode* pnode, vNodesCopy)
884 boost::this_thread::interruption_point();
889 if (pnode->hSocket == INVALID_SOCKET)
891 if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
893 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
897 // typical socket buffer is 8K-64K
898 char pchBuf[0x10000];
899 int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
902 if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
903 pnode->CloseSocketDisconnect();
904 pnode->nLastRecv = GetTime();
905 pnode->nRecvBytes += nBytes;
906 pnode->RecordBytesRecv(nBytes);
908 else if (nBytes == 0)
910 // socket closed gracefully
911 if (!pnode->fDisconnect)
912 LogPrint("net", "socket closed\n");
913 pnode->CloseSocketDisconnect();
918 int nErr = WSAGetLastError();
919 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
921 if (!pnode->fDisconnect)
922 LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
923 pnode->CloseSocketDisconnect();
933 if (pnode->hSocket == INVALID_SOCKET)
935 if (FD_ISSET(pnode->hSocket, &fdsetSend))
937 TRY_LOCK(pnode->cs_vSend, lockSend);
939 SocketSendData(pnode);
943 // Inactivity checking
945 int64_t nTime = GetTime();
946 if (nTime - pnode->nTimeConnected > 60)
948 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
950 LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id);
951 pnode->fDisconnect = true;
953 else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL)
955 LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
956 pnode->fDisconnect = true;
958 else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60))
960 LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
961 pnode->fDisconnect = true;
963 else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros())
965 LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
966 pnode->fDisconnect = true;
972 BOOST_FOREACH(CNode* pnode, vNodesCopy)
989 std::string port = strprintf("%u", GetListenPort());
990 const char * multicastif = 0;
991 const char * minissdpdpath = 0;
992 struct UPNPDev * devlist = 0;
995 #ifndef UPNPDISCOVER_SUCCESS
997 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1001 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1004 struct UPNPUrls urls;
1005 struct IGDdatas data;
1008 r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1012 char externalIPAddress[40];
1013 r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1014 if(r != UPNPCOMMAND_SUCCESS)
1015 LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
1018 if(externalIPAddress[0])
1020 LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
1021 AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
1024 LogPrintf("UPnP: GetExternalIPAddress failed.\n");
1028 string strDesc = "Bitcoin " + FormatFullVersion();
1032 #ifndef UPNPDISCOVER_SUCCESS
1034 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1035 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1038 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1039 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1042 if(r!=UPNPCOMMAND_SUCCESS)
1043 LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1044 port, port, lanaddr, r, strupnperror(r));
1046 LogPrintf("UPnP Port Mapping successful.\n");;
1048 MilliSleep(20*60*1000); // Refresh every 20 minutes
1051 catch (const boost::thread_interrupted&)
1053 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1054 LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
1055 freeUPNPDevlist(devlist); devlist = 0;
1056 FreeUPNPUrls(&urls);
1060 LogPrintf("No valid UPnP IGDs found\n");
1061 freeUPNPDevlist(devlist); devlist = 0;
1063 FreeUPNPUrls(&urls);
1067 void MapPort(bool fUseUPnP)
1069 static boost::thread* upnp_thread = NULL;
1074 upnp_thread->interrupt();
1075 upnp_thread->join();
1078 upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
1080 else if (upnp_thread) {
1081 upnp_thread->interrupt();
1082 upnp_thread->join();
1091 // Intentionally left blank.
1100 void ThreadDNSAddressSeed()
1102 // goal: only query DNS seeds if address need is acute
1103 if ((addrman.size() > 0) &&
1104 (!GetBoolArg("-forcednsseed", false))) {
1105 MilliSleep(11 * 1000);
1108 if (vNodes.size() >= 2) {
1109 LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1114 const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
1117 LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
1119 BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) {
1120 if (HaveNameProxy()) {
1121 AddOneShot(seed.host);
1123 vector<CNetAddr> vIPs;
1124 vector<CAddress> vAdd;
1125 if (LookupHost(seed.host.c_str(), vIPs))
1127 BOOST_FOREACH(CNetAddr& ip, vIPs)
1129 int nOneDay = 24*3600;
1130 CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
1131 addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1132 vAdd.push_back(addr);
1136 addrman.Add(vAdd, CNetAddr(seed.name, true));
1140 LogPrintf("%d addresses found from DNS seeds\n", found);
1154 void DumpAddresses()
1156 int64_t nStart = GetTimeMillis();
1161 LogPrint("net", "Flushed %d addresses to peers.dat %dms\n",
1162 addrman.size(), GetTimeMillis() - nStart);
1165 void static ProcessOneShot()
1170 if (vOneShots.empty())
1172 strDest = vOneShots.front();
1173 vOneShots.pop_front();
1176 CSemaphoreGrant grant(*semOutbound, true);
1178 if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
1179 AddOneShot(strDest);
1183 void ThreadOpenConnections()
1185 // Connect to specific addresses
1186 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
1188 for (int64_t nLoop = 0;; nLoop++)
1191 BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
1194 OpenNetworkConnection(addr, NULL, strAddr.c_str());
1195 for (int i = 0; i < 10 && i < nLoop; i++)
1204 // Initiate network connections
1205 int64_t nStart = GetTime();
1212 CSemaphoreGrant grant(*semOutbound);
1213 boost::this_thread::interruption_point();
1215 // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1216 if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
1217 static bool done = false;
1219 LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1220 addrman.Add(convertSeed6(Params().FixedSeeds()), CNetAddr("127.0.0.1"));
1226 // Choose an address to connect to based on most recently seen
1228 CAddress addrConnect;
1230 // Only connect out to one peer per network group (/16 for IPv4).
1231 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1233 set<vector<unsigned char> > setConnected;
1236 BOOST_FOREACH(CNode* pnode, vNodes) {
1237 if (!pnode->fInbound) {
1238 setConnected.insert(pnode->addr.GetGroup());
1244 int64_t nANow = GetAdjustedTime();
1249 CAddrInfo addr = addrman.Select();
1251 // if we selected an invalid address, restart
1252 if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1255 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1256 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1257 // already-connected network ranges, ...) before trying new addrman addresses.
1262 if (IsLimited(addr))
1265 // only consider very recently tried nodes after 30 failed attempts
1266 if (nANow - addr.nLastTry < 600 && nTries < 30)
1269 // do not allow non-default ports, unless after 50 invalid addresses selected already
1270 if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
1277 if (addrConnect.IsValid())
1278 OpenNetworkConnection(addrConnect, &grant);
1282 void ThreadOpenAddedConnections()
1285 LOCK(cs_vAddedNodes);
1286 vAddedNodes = mapMultiArgs["-addnode"];
1289 if (HaveNameProxy()) {
1291 list<string> lAddresses(0);
1293 LOCK(cs_vAddedNodes);
1294 BOOST_FOREACH(string& strAddNode, vAddedNodes)
1295 lAddresses.push_back(strAddNode);
1297 BOOST_FOREACH(string& strAddNode, lAddresses) {
1299 CSemaphoreGrant grant(*semOutbound);
1300 OpenNetworkConnection(addr, &grant, strAddNode.c_str());
1303 MilliSleep(120000); // Retry every 2 minutes
1307 for (unsigned int i = 0; true; i++)
1309 list<string> lAddresses(0);
1311 LOCK(cs_vAddedNodes);
1312 BOOST_FOREACH(string& strAddNode, vAddedNodes)
1313 lAddresses.push_back(strAddNode);
1316 list<vector<CService> > lservAddressesToAdd(0);
1317 BOOST_FOREACH(string& strAddNode, lAddresses)
1319 vector<CService> vservNode(0);
1320 if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0))
1322 lservAddressesToAdd.push_back(vservNode);
1324 LOCK(cs_setservAddNodeAddresses);
1325 BOOST_FOREACH(CService& serv, vservNode)
1326 setservAddNodeAddresses.insert(serv);
1330 // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
1331 // (keeping in mind that addnode entries can have many IPs if fNameLookup)
1334 BOOST_FOREACH(CNode* pnode, vNodes)
1335 for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
1336 BOOST_FOREACH(CService& addrNode, *(it))
1337 if (pnode->addr == addrNode)
1339 it = lservAddressesToAdd.erase(it);
1344 BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd)
1346 CSemaphoreGrant grant(*semOutbound);
1347 OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
1350 MilliSleep(120000); // Retry every 2 minutes
1354 // if successful, this moves the passed grant to the constructed node
1355 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot)
1358 // Initiate outbound network connection
1360 boost::this_thread::interruption_point();
1362 if (IsLocal(addrConnect) ||
1363 FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
1364 FindNode(addrConnect.ToStringIPPort()))
1366 } else if (FindNode(pszDest))
1369 CNode* pnode = ConnectNode(addrConnect, pszDest);
1370 boost::this_thread::interruption_point();
1375 grantOutbound->MoveTo(pnode->grantOutbound);
1376 pnode->fNetworkNode = true;
1378 pnode->fOneShot = true;
1384 void ThreadMessageHandler()
1386 boost::mutex condition_mutex;
1387 boost::unique_lock<boost::mutex> lock(condition_mutex);
1389 SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1392 vector<CNode*> vNodesCopy;
1395 vNodesCopy = vNodes;
1396 BOOST_FOREACH(CNode* pnode, vNodesCopy) {
1401 // Poll the connected nodes for messages
1402 CNode* pnodeTrickle = NULL;
1403 if (!vNodesCopy.empty())
1404 pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1408 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1410 if (pnode->fDisconnect)
1415 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
1418 if (!g_signals.ProcessMessages(pnode))
1419 pnode->CloseSocketDisconnect();
1421 if (pnode->nSendSize < SendBufferSize())
1423 if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete()))
1430 boost::this_thread::interruption_point();
1434 TRY_LOCK(pnode->cs_vSend, lockSend);
1436 g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted);
1438 boost::this_thread::interruption_point();
1443 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1448 messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100));
1457 bool BindListenPort(const CService &addrBind, string& strError, bool fWhitelisted)
1462 // Create socket for listening for incoming connections
1463 struct sockaddr_storage sockaddr;
1464 socklen_t len = sizeof(sockaddr);
1465 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
1467 strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
1468 LogPrintf("%s\n", strError);
1472 SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
1473 if (hListenSocket == INVALID_SOCKET)
1475 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
1476 LogPrintf("%s\n", strError);
1482 // Different way of disabling SIGPIPE on BSD
1483 setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1485 // Allow binding if the port is still in TIME_WAIT state after
1486 // the program was closed and restarted. Not an issue on windows!
1487 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1490 // Set to non-blocking, incoming connections will also inherit this
1491 if (!SetSocketNonBlocking(hListenSocket, true)) {
1492 strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
1493 LogPrintf("%s\n", strError);
1497 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
1498 // and enable it by default or not. Try to enable it, if possible.
1499 if (addrBind.IsIPv6()) {
1502 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
1504 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
1508 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
1509 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
1513 if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
1515 int nErr = WSAGetLastError();
1516 if (nErr == WSAEADDRINUSE)
1517 strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin Core is probably already running."), addrBind.ToString());
1519 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
1520 LogPrintf("%s\n", strError);
1521 CloseSocket(hListenSocket);
1524 LogPrintf("Bound to %s\n", addrBind.ToString());
1526 // Listen for incoming connections
1527 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1529 strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
1530 LogPrintf("%s\n", strError);
1531 CloseSocket(hListenSocket);
1535 vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
1537 if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
1538 AddLocal(addrBind, LOCAL_BIND);
1543 void static Discover(boost::thread_group& threadGroup)
1549 // Get local host IP
1550 char pszHostName[256] = "";
1551 if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1553 vector<CNetAddr> vaddr;
1554 if (LookupHost(pszHostName, vaddr))
1556 BOOST_FOREACH (const CNetAddr &addr, vaddr)
1558 if (AddLocal(addr, LOCAL_IF))
1559 LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
1564 // Get local host ip
1565 struct ifaddrs* myaddrs;
1566 if (getifaddrs(&myaddrs) == 0)
1568 for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1570 if (ifa->ifa_addr == NULL) continue;
1571 if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1572 if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1573 if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1574 if (ifa->ifa_addr->sa_family == AF_INET)
1576 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1577 CNetAddr addr(s4->sin_addr);
1578 if (AddLocal(addr, LOCAL_IF))
1579 LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
1581 else if (ifa->ifa_addr->sa_family == AF_INET6)
1583 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1584 CNetAddr addr(s6->sin6_addr);
1585 if (AddLocal(addr, LOCAL_IF))
1586 LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
1589 freeifaddrs(myaddrs);
1594 void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler)
1596 uiInterface.InitMessage(_("Loading addresses..."));
1597 // Load addresses for peers.dat
1598 int64_t nStart = GetTimeMillis();
1601 if (!adb.Read(addrman))
1602 LogPrintf("Invalid or missing peers.dat; recreating\n");
1604 LogPrintf("Loaded %i addresses from peers.dat %dms\n",
1605 addrman.size(), GetTimeMillis() - nStart);
1606 fAddressesInitialized = true;
1608 if (semOutbound == NULL) {
1609 // initialize semaphore
1610 int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
1611 semOutbound = new CSemaphore(nMaxOutbound);
1614 if (pnodeLocalHost == NULL)
1615 pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
1617 Discover(threadGroup);
1623 if (!GetBoolArg("-dnsseed", true))
1624 LogPrintf("DNS seeding disabled\n");
1626 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
1628 // Map ports with UPnP
1629 MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
1631 // Send and receive from sockets, accept connections
1632 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
1634 // Initiate outbound connections from -addnode
1635 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
1637 // Initiate outbound connections
1638 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
1641 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
1643 // Dump network addresses
1644 scheduler.scheduleEvery(&DumpAddresses, DUMP_ADDRESSES_INTERVAL);
1649 LogPrintf("StopNode()\n");
1652 for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
1653 semOutbound->post();
1655 if (fAddressesInitialized)
1658 fAddressesInitialized = false;
1672 BOOST_FOREACH(CNode* pnode, vNodes)
1673 if (pnode->hSocket != INVALID_SOCKET)
1674 CloseSocket(pnode->hSocket);
1675 BOOST_FOREACH(ListenSocket& hListenSocket, vhListenSocket)
1676 if (hListenSocket.socket != INVALID_SOCKET)
1677 if (!CloseSocket(hListenSocket.socket))
1678 LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
1680 // clean up some globals (to help leak detection)
1681 BOOST_FOREACH(CNode *pnode, vNodes)
1683 BOOST_FOREACH(CNode *pnode, vNodesDisconnected)
1686 vNodesDisconnected.clear();
1687 vhListenSocket.clear();
1690 delete pnodeLocalHost;
1691 pnodeLocalHost = NULL;
1694 // Shutdown Windows Sockets
1699 instance_of_cnetcleanup;
1707 void RelayTransaction(const CTransaction& tx)
1709 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1712 RelayTransaction(tx, ss);
1715 void RelayTransaction(const CTransaction& tx, const CDataStream& ss)
1717 CInv inv(MSG_TX, tx.GetHash());
1720 // Expire old relay messages
1721 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
1723 mapRelay.erase(vRelayExpiration.front().second);
1724 vRelayExpiration.pop_front();
1727 // Save original serialized message so newer versions are preserved
1728 mapRelay.insert(std::make_pair(inv, ss));
1729 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
1732 BOOST_FOREACH(CNode* pnode, vNodes)
1734 if(!pnode->fRelayTxes)
1736 LOCK(pnode->cs_filter);
1739 if (pnode->pfilter->IsRelevantAndUpdate(tx))
1740 pnode->PushInventory(inv);
1742 pnode->PushInventory(inv);
1746 void CNode::RecordBytesRecv(uint64_t bytes)
1748 LOCK(cs_totalBytesRecv);
1749 nTotalBytesRecv += bytes;
1752 void CNode::RecordBytesSent(uint64_t bytes)
1754 LOCK(cs_totalBytesSent);
1755 nTotalBytesSent += bytes;
1758 uint64_t CNode::GetTotalBytesRecv()
1760 LOCK(cs_totalBytesRecv);
1761 return nTotalBytesRecv;
1764 uint64_t CNode::GetTotalBytesSent()
1766 LOCK(cs_totalBytesSent);
1767 return nTotalBytesSent;
1770 void CNode::Fuzz(int nChance)
1772 if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
1773 if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
1778 // xor a random byte with a random value:
1779 if (!ssSend.empty()) {
1780 CDataStream::size_type pos = GetRand(ssSend.size());
1781 ssSend[pos] ^= (unsigned char)(GetRand(256));
1785 // delete a random byte:
1786 if (!ssSend.empty()) {
1787 CDataStream::size_type pos = GetRand(ssSend.size());
1788 ssSend.erase(ssSend.begin()+pos);
1792 // insert a random byte at a random position
1794 CDataStream::size_type pos = GetRand(ssSend.size());
1795 char ch = (char)GetRand(256);
1796 ssSend.insert(ssSend.begin()+pos, ch);
1800 // Chance of more than one change half the time:
1801 // (more changes exponentially less likely):
1811 pathAddr = GetDataDir() / "peers.dat";
1814 bool CAddrDB::Write(const CAddrMan& addr)
1816 // Generate random temporary filename
1817 unsigned short randv = 0;
1818 GetRandBytes((unsigned char*)&randv, sizeof(randv));
1819 std::string tmpfn = strprintf("peers.dat.%04x", randv);
1821 // serialize addresses, checksum data up to that point, then append csum
1822 CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
1823 ssPeers << FLATDATA(Params().MessageStart());
1825 uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
1828 // open temp output file, and associate with CAutoFile
1829 boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
1830 FILE *file = fopen(pathTmp.string().c_str(), "wb");
1831 CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
1832 if (fileout.IsNull())
1833 return error("%s: Failed to open file %s", __func__, pathTmp.string());
1835 // Write and commit header, data
1839 catch (const std::exception& e) {
1840 return error("%s: Serialize or I/O error - %s", __func__, e.what());
1842 FileCommit(fileout.Get());
1845 // replace existing peers.dat, if any, with new peers.dat.XXXX
1846 if (!RenameOver(pathTmp, pathAddr))
1847 return error("%s: Rename-into-place failed", __func__);
1852 bool CAddrDB::Read(CAddrMan& addr)
1854 // open input file, and associate with CAutoFile
1855 FILE *file = fopen(pathAddr.string().c_str(), "rb");
1856 CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
1857 if (filein.IsNull())
1858 return error("%s: Failed to open file %s", __func__, pathAddr.string());
1860 // use file size to size memory buffer
1861 int fileSize = boost::filesystem::file_size(pathAddr);
1862 int dataSize = fileSize - sizeof(uint256);
1863 // Don't try to resize to a negative number if file is small
1866 vector<unsigned char> vchData;
1867 vchData.resize(dataSize);
1870 // read data and checksum from file
1872 filein.read((char *)&vchData[0], dataSize);
1875 catch (const std::exception& e) {
1876 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1880 CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
1882 // verify stored checksum matches input data
1883 uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
1884 if (hashIn != hashTmp)
1885 return error("%s: Checksum mismatch, data corrupted", __func__);
1887 unsigned char pchMsgTmp[4];
1889 // de-serialize file header (network specific magic number) and ..
1890 ssPeers >> FLATDATA(pchMsgTmp);
1892 // ... verify the network matches ours
1893 if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
1894 return error("%s: Invalid network magic number", __func__);
1896 // de-serialize address data into one CAddrMan object
1899 catch (const std::exception& e) {
1900 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
1906 unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
1907 unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
1909 CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) :
1910 ssSend(SER_NETWORK, INIT_PROTO_VERSION),
1911 addrKnown(5000, 0.001, insecure_rand()),
1912 setInventoryKnown(SendBufferSize() / 1000)
1915 hSocket = hSocketIn;
1916 nRecvVersion = INIT_PROTO_VERSION;
1921 nTimeConnected = GetTime();
1924 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
1927 fWhitelisted = false;
1929 fClient = false; // set by version message
1930 fInbound = fInboundIn;
1931 fNetworkNode = false;
1932 fSuccessfullyConnected = false;
1933 fDisconnect = false;
1937 hashContinue = uint256();
1938 nStartingHeight = -1;
1941 pfilter = new CBloomFilter();
1945 fPingQueued = false;
1948 LOCK(cs_nLastNodeId);
1953 LogPrint("net", "Added connection to %s peer=%d\n", addrName, id);
1955 LogPrint("net", "Added connection peer=%d\n", id);
1957 // Be shy and don't send version until we hear
1958 if (hSocket != INVALID_SOCKET && !fInbound)
1961 GetNodeSignals().InitializeNode(GetId(), this);
1966 CloseSocket(hSocket);
1971 GetNodeSignals().FinalizeNode(GetId());
1974 void CNode::AskFor(const CInv& inv)
1976 if (mapAskFor.size() > MAPASKFOR_MAX_SZ)
1978 // We're using mapAskFor as a priority queue,
1979 // the key is the earliest time the request can be sent
1980 int64_t nRequestTime;
1981 limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv);
1982 if (it != mapAlreadyAskedFor.end())
1983 nRequestTime = it->second;
1986 LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id);
1988 // Make sure not to reuse time indexes to keep things in the same order
1989 int64_t nNow = GetTimeMicros() - 1000000;
1990 static int64_t nLastTime;
1992 nNow = std::max(nNow, nLastTime);
1995 // Each retry is 2 minutes after the last
1996 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
1997 if (it != mapAlreadyAskedFor.end())
1998 mapAlreadyAskedFor.update(it, nRequestTime);
2000 mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
2001 mapAskFor.insert(std::make_pair(nRequestTime, inv));
2004 void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
2006 ENTER_CRITICAL_SECTION(cs_vSend);
2007 assert(ssSend.size() == 0);
2008 ssSend << CMessageHeader(Params().MessageStart(), pszCommand, 0);
2009 LogPrint("net", "sending: %s ", SanitizeString(pszCommand));
2012 void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend)
2016 LEAVE_CRITICAL_SECTION(cs_vSend);
2018 LogPrint("net", "(aborted)\n");
2021 void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend)
2023 // The -*messagestest options are intentionally not documented in the help message,
2024 // since they are only used during development to debug the networking code and are
2025 // not intended for end-users.
2026 if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0)
2028 LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
2032 if (mapArgs.count("-fuzzmessagestest"))
2033 Fuzz(GetArg("-fuzzmessagestest", 10));
2035 if (ssSend.size() == 0)
2039 unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
2040 WriteLE32((uint8_t*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], nSize);
2043 uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
2044 unsigned int nChecksum = 0;
2045 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2046 assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
2047 memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
2049 LogPrint("net", "(%d bytes) peer=%d\n", nSize, id);
2051 std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
2052 ssSend.GetAndClear(*it);
2053 nSendSize += (*it).size();
2055 // If write queue empty, attempt "optimistic write"
2056 if (it == vSendMsg.begin())
2057 SocketSendData(this);
2059 LEAVE_CRITICAL_SECTION(cs_vSend);