1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 The Bitcoin developers
3 // Distributed under the MIT/X11 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 "bitcoin-config.h"
13 #include "chainparams.h"
15 #include "ui_interface.h"
24 #include <miniupnpc/miniupnpc.h>
25 #include <miniupnpc/miniwget.h>
26 #include <miniupnpc/upnpcommands.h>
27 #include <miniupnpc/upnperrors.h>
30 // Dump addresses to peers.dat every 15 minutes (900s)
31 #define DUMP_ADDRESSES_INTERVAL 900
33 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
34 #define MSG_NOSIGNAL 0
38 using namespace boost;
40 static const int MAX_OUTBOUND_CONNECTIONS = 8;
42 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
45 struct LocalServiceInfo {
51 // Global state variables
53 bool fDiscover = true;
54 uint64_t nLocalServices = NODE_NETWORK;
55 static CCriticalSection cs_mapLocalHost;
56 static map<CNetAddr, LocalServiceInfo> mapLocalHost;
57 static bool vfReachable[NET_MAX] = {};
58 static bool vfLimited[NET_MAX] = {};
59 static CNode* pnodeLocalHost = NULL;
60 static CNode* pnodeSync = NULL;
61 uint64_t nLocalHostNonce = 0;
62 static std::vector<SOCKET> vhListenSocket;
64 int nMaxConnections = 125;
66 vector<CNode*> vNodes;
67 CCriticalSection cs_vNodes;
68 map<CInv, CDataStream> mapRelay;
69 deque<pair<int64_t, CInv> > vRelayExpiration;
70 CCriticalSection cs_mapRelay;
71 limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
73 static deque<string> vOneShots;
74 CCriticalSection cs_vOneShots;
76 set<CNetAddr> setservAddNodeAddresses;
77 CCriticalSection cs_setservAddNodeAddresses;
79 vector<std::string> vAddedNodes;
80 CCriticalSection cs_vAddedNodes;
82 NodeId nLastNodeId = 0;
83 CCriticalSection cs_nLastNodeId;
85 static CSemaphore *semOutbound = NULL;
87 // Signals for message handling
88 static CNodeSignals g_signals;
89 CNodeSignals& GetNodeSignals() { return g_signals; }
91 void AddOneShot(string strDest)
94 vOneShots.push_back(strDest);
97 unsigned short GetListenPort()
99 return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
102 // find 'best' local address for a particular peer
103 bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
109 int nBestReachability = -1;
111 LOCK(cs_mapLocalHost);
112 for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
114 int nScore = (*it).second.nScore;
115 int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
116 if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
118 addr = CService((*it).first, (*it).second.nPort);
119 nBestReachability = nReachability;
124 return nBestScore >= 0;
127 // get best local address for a particular peer as a CAddress
128 CAddress GetLocalAddress(const CNetAddr *paddrPeer)
130 CAddress ret(CService("0.0.0.0",0),0);
132 if (GetLocal(addr, paddrPeer))
134 ret = CAddress(addr);
135 ret.nServices = nLocalServices;
136 ret.nTime = GetAdjustedTime();
141 bool RecvLine(SOCKET hSocket, string& strLine)
147 int nBytes = recv(hSocket, &c, 1, 0);
155 if (strLine.size() >= 9000)
158 else if (nBytes <= 0)
160 boost::this_thread::interruption_point();
163 int nErr = WSAGetLastError();
164 if (nErr == WSAEMSGSIZE)
166 if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
172 if (!strLine.empty())
177 LogPrint("net", "socket closed\n");
183 int nErr = WSAGetLastError();
184 LogPrint("net", "recv failed: %d\n", nErr);
191 // used when scores of local addresses may have changed
192 // pushes better local address to peers
193 void static AdvertizeLocal()
196 BOOST_FOREACH(CNode* pnode, vNodes)
198 if (pnode->fSuccessfullyConnected)
200 CAddress addrLocal = GetLocalAddress(&pnode->addr);
201 if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
203 pnode->PushAddress(addrLocal);
204 pnode->addrLocal = addrLocal;
210 void SetReachable(enum Network net, bool fFlag)
212 LOCK(cs_mapLocalHost);
213 vfReachable[net] = fFlag;
214 if (net == NET_IPV6 && fFlag)
215 vfReachable[NET_IPV4] = true;
218 // learn a new local address
219 bool AddLocal(const CService& addr, int nScore)
221 if (!addr.IsRoutable())
224 if (!fDiscover && nScore < LOCAL_MANUAL)
230 LogPrintf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
233 LOCK(cs_mapLocalHost);
234 bool fAlready = mapLocalHost.count(addr) > 0;
235 LocalServiceInfo &info = mapLocalHost[addr];
236 if (!fAlready || nScore >= info.nScore) {
237 info.nScore = nScore + (fAlready ? 1 : 0);
238 info.nPort = addr.GetPort();
240 SetReachable(addr.GetNetwork());
248 bool AddLocal(const CNetAddr &addr, int nScore)
250 return AddLocal(CService(addr, GetListenPort()), nScore);
253 /** Make a particular network entirely off-limits (no automatic connects to it) */
254 void SetLimited(enum Network net, bool fLimited)
256 if (net == NET_UNROUTABLE)
258 LOCK(cs_mapLocalHost);
259 vfLimited[net] = fLimited;
262 bool IsLimited(enum Network net)
264 LOCK(cs_mapLocalHost);
265 return vfLimited[net];
268 bool IsLimited(const CNetAddr &addr)
270 return IsLimited(addr.GetNetwork());
273 /** vote for a local address */
274 bool SeenLocal(const CService& addr)
277 LOCK(cs_mapLocalHost);
278 if (mapLocalHost.count(addr) == 0)
280 mapLocalHost[addr].nScore++;
288 /** check whether a given address is potentially local */
289 bool IsLocal(const CService& addr)
291 LOCK(cs_mapLocalHost);
292 return mapLocalHost.count(addr) > 0;
295 /** check whether a given address is in a network we can probably connect to */
296 bool IsReachable(const CNetAddr& addr)
298 LOCK(cs_mapLocalHost);
299 enum Network net = addr.GetNetwork();
300 return vfReachable[net] && !vfLimited[net];
303 bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
306 if (!ConnectSocket(addrConnect, hSocket))
307 return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
309 send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
312 while (RecvLine(hSocket, strLine))
314 if (strLine.empty()) // HTTP response is separated from headers by blank line
318 if (!RecvLine(hSocket, strLine))
320 closesocket(hSocket);
323 if (pszKeyword == NULL)
325 if (strLine.find(pszKeyword) != string::npos)
327 strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
331 closesocket(hSocket);
332 if (strLine.find("<") != string::npos)
333 strLine = strLine.substr(0, strLine.find("<"));
334 strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
335 while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
336 strLine.resize(strLine.size()-1);
337 CService addr(strLine,0,true);
338 LogPrintf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
339 if (!addr.IsValid() || !addr.IsRoutable())
345 closesocket(hSocket);
346 return error("GetMyExternalIP() : connection closed");
349 bool GetMyExternalIP(CNetAddr& ipRet)
351 CService addrConnect;
353 const char* pszKeyword;
355 for (int nLookup = 0; nLookup <= 1; nLookup++)
356 for (int nHost = 1; nHost <= 2; nHost++)
358 // We should be phasing out our use of sites like these. If we need
359 // replacements, we should ask for volunteers to put this simple
360 // php file on their web server that prints the client IP:
361 // <?php echo $_SERVER["REMOTE_ADDR"]; ?>
364 addrConnect = CService("91.198.22.70", 80); // checkip.dyndns.org
368 CService addrIP("checkip.dyndns.org", 80, true);
369 if (addrIP.IsValid())
370 addrConnect = addrIP;
373 pszGet = "GET / HTTP/1.1\r\n"
374 "Host: checkip.dyndns.org\r\n"
375 "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
376 "Connection: close\r\n"
379 pszKeyword = "Address:";
383 addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
387 CService addrIP("www.showmyip.com", 80, true);
388 if (addrIP.IsValid())
389 addrConnect = addrIP;
392 pszGet = "GET /simple/ HTTP/1.1\r\n"
393 "Host: www.showmyip.com\r\n"
394 "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
395 "Connection: close\r\n"
398 pszKeyword = NULL; // Returns just IP address
401 if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
408 void ThreadGetMyExternalIP()
410 CNetAddr addrLocalHost;
411 if (GetMyExternalIP(addrLocalHost))
413 LogPrintf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
414 AddLocal(addrLocalHost, LOCAL_HTTP);
422 void AddressCurrentlyConnected(const CService& addr)
424 addrman.Connected(addr);
430 uint64_t CNode::nTotalBytesRecv = 0;
431 uint64_t CNode::nTotalBytesSent = 0;
432 CCriticalSection CNode::cs_totalBytesRecv;
433 CCriticalSection CNode::cs_totalBytesSent;
435 CNode* FindNode(const CNetAddr& ip)
438 BOOST_FOREACH(CNode* pnode, vNodes)
439 if ((CNetAddr)pnode->addr == ip)
444 CNode* FindNode(std::string addrName)
447 BOOST_FOREACH(CNode* pnode, vNodes)
448 if (pnode->addrName == addrName)
453 CNode* FindNode(const CService& addr)
456 BOOST_FOREACH(CNode* pnode, vNodes)
457 if ((CService)pnode->addr == addr)
462 CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
464 if (pszDest == NULL) {
465 if (IsLocal(addrConnect))
468 // Look for an existing connection
469 CNode* pnode = FindNode((CService)addrConnect);
479 LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
480 pszDest ? pszDest : addrConnect.ToString().c_str(),
481 pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
485 if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
487 addrman.Attempt(addrConnect);
489 LogPrint("net", "connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
491 // Set to non-blocking
494 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
495 LogPrintf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
497 if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
498 LogPrintf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
502 CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
507 vNodes.push_back(pnode);
510 pnode->nTimeConnected = GetTime();
519 void CNode::CloseSocketDisconnect()
522 if (hSocket != INVALID_SOCKET)
524 LogPrint("net", "disconnecting node %s\n", addrName.c_str());
525 closesocket(hSocket);
526 hSocket = INVALID_SOCKET;
529 // in case this fails, we'll empty the recv buffer when the CNode is deleted
530 TRY_LOCK(cs_vRecvMsg, lockRecv);
534 // if this was the sync node, we'll need a new one
535 if (this == pnodeSync)
539 void CNode::Cleanup()
544 void CNode::PushVersion()
546 int nBestHeight = g_signals.GetHeight().get_value_or(0);
548 /// when NTP implemented, change to just nTime = GetAdjustedTime()
549 int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
550 CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
551 CAddress addrMe = GetLocalAddress(&addr);
552 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
553 LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
554 PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
555 nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true);
562 std::map<CNetAddr, int64_t> CNode::setBanned;
563 CCriticalSection CNode::cs_setBanned;
565 void CNode::ClearBanned()
570 bool CNode::IsBanned(CNetAddr ip)
572 bool fResult = false;
575 std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip);
576 if (i != setBanned.end())
578 int64_t t = (*i).second;
586 bool CNode::Ban(const CNetAddr &addr) {
587 int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
590 if (setBanned[addr] < banTime)
591 setBanned[addr] = banTime;
597 #define X(name) stats.name = name
598 void CNode::copyStats(CNodeStats &stats)
600 stats.nodeid = this->GetId();
612 stats.fSyncNode = (this == pnodeSync);
614 // It is common for nodes with good ping times to suddenly become lagged,
615 // due to a new block arriving or other large transfer.
616 // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
617 // since pingtime does not update until the ping is complete, which might take a while.
618 // So, if a ping is taking an unusually long time in flight,
619 // the caller can immediately detect that this is happening.
620 int64_t nPingUsecWait = 0;
621 if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
622 nPingUsecWait = GetTimeMicros() - nPingUsecStart;
625 // 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 :)
626 stats.dPingTime = (((double)nPingUsecTime) / 1e6);
627 stats.dPingWait = (((double)nPingUsecWait) / 1e6);
629 // Leave string empty if addrLocal invalid (not filled in yet)
630 stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
634 // requires LOCK(cs_vRecvMsg)
635 bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
639 // get current incomplete message, or create a new one
640 if (vRecvMsg.empty() ||
641 vRecvMsg.back().complete())
642 vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
644 CNetMessage& msg = vRecvMsg.back();
646 // absorb network data
649 handled = msg.readHeader(pch, nBytes);
651 handled = msg.readData(pch, nBytes);
663 int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
665 // copy data to temporary parsing buffer
666 unsigned int nRemaining = 24 - nHdrPos;
667 unsigned int nCopy = std::min(nRemaining, nBytes);
669 memcpy(&hdrbuf[nHdrPos], pch, nCopy);
672 // if header incomplete, exit
676 // deserialize to CMessageHeader
680 catch (std::exception &e) {
684 // reject messages larger than MAX_SIZE
685 if (hdr.nMessageSize > MAX_SIZE)
688 // switch state to reading message data
690 vRecv.resize(hdr.nMessageSize);
695 int CNetMessage::readData(const char *pch, unsigned int nBytes)
697 unsigned int nRemaining = hdr.nMessageSize - nDataPos;
698 unsigned int nCopy = std::min(nRemaining, nBytes);
700 memcpy(&vRecv[nDataPos], pch, nCopy);
714 // requires LOCK(cs_vSend)
715 void SocketSendData(CNode *pnode)
717 std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
719 while (it != pnode->vSendMsg.end()) {
720 const CSerializeData &data = *it;
721 assert(data.size() > pnode->nSendOffset);
722 int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
724 pnode->nLastSend = GetTime();
725 pnode->nSendBytes += nBytes;
726 pnode->nSendOffset += nBytes;
727 pnode->RecordBytesSent(nBytes);
728 if (pnode->nSendOffset == data.size()) {
729 pnode->nSendOffset = 0;
730 pnode->nSendSize -= data.size();
733 // could not send full message; stop sending more
739 int nErr = WSAGetLastError();
740 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
742 LogPrintf("socket send error %d\n", nErr);
743 pnode->CloseSocketDisconnect();
746 // couldn't send anything at all
751 if (it == pnode->vSendMsg.end()) {
752 assert(pnode->nSendOffset == 0);
753 assert(pnode->nSendSize == 0);
755 pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
758 static list<CNode*> vNodesDisconnected;
760 void ThreadSocketHandler()
762 unsigned int nPrevNodeCount = 0;
770 // Disconnect unused nodes
771 vector<CNode*> vNodesCopy = vNodes;
772 BOOST_FOREACH(CNode* pnode, vNodesCopy)
774 if (pnode->fDisconnect ||
775 (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
777 // remove from vNodes
778 vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
780 // release outbound grant (if any)
781 pnode->grantOutbound.Release();
783 // close socket and cleanup
784 pnode->CloseSocketDisconnect();
787 // hold in disconnected pool until all refs are released
788 if (pnode->fNetworkNode || pnode->fInbound)
790 vNodesDisconnected.push_back(pnode);
795 // Delete disconnected nodes
796 list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
797 BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
799 // wait until threads are done using it
800 if (pnode->GetRefCount() <= 0)
802 bool fDelete = false;
804 TRY_LOCK(pnode->cs_vSend, lockSend);
807 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
810 TRY_LOCK(pnode->cs_inventory, lockInv);
818 vNodesDisconnected.remove(pnode);
824 if(vNodes.size() != nPrevNodeCount) {
825 nPrevNodeCount = vNodes.size();
826 uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
831 // Find which sockets have data to receive
833 struct timeval timeout;
835 timeout.tv_usec = 50000; // frequency to poll pnode->vSend
842 FD_ZERO(&fdsetError);
843 SOCKET hSocketMax = 0;
844 bool have_fds = false;
846 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
847 FD_SET(hListenSocket, &fdsetRecv);
848 hSocketMax = max(hSocketMax, hListenSocket);
853 BOOST_FOREACH(CNode* pnode, vNodes)
855 if (pnode->hSocket == INVALID_SOCKET)
857 FD_SET(pnode->hSocket, &fdsetError);
858 hSocketMax = max(hSocketMax, pnode->hSocket);
861 // Implement the following logic:
862 // * If there is data to send, select() for sending data. As this only
863 // happens when optimistic write failed, we choose to first drain the
864 // write buffer in this case before receiving more. This avoids
865 // needlessly queueing received data, if the remote peer is not themselves
866 // receiving data. This means properly utilizing TCP flow control signalling.
867 // * Otherwise, if there is no (complete) message in the receive buffer,
868 // or there is space left in the buffer, select() for receiving data.
869 // * (if neither of the above applies, there is certainly one message
870 // in the receiver buffer ready to be processed).
871 // Together, that means that at least one of the following is always possible,
872 // so we don't deadlock:
873 // * We send some data.
874 // * We wait for data to be received (and disconnect after timeout).
875 // * We process a message in the buffer (message handler thread).
877 TRY_LOCK(pnode->cs_vSend, lockSend);
878 if (lockSend && !pnode->vSendMsg.empty()) {
879 FD_SET(pnode->hSocket, &fdsetSend);
884 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
886 pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
887 pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
888 FD_SET(pnode->hSocket, &fdsetRecv);
893 int nSelect = select(have_fds ? hSocketMax + 1 : 0,
894 &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
895 boost::this_thread::interruption_point();
897 if (nSelect == SOCKET_ERROR)
901 int nErr = WSAGetLastError();
902 LogPrintf("socket select error %d\n", nErr);
903 for (unsigned int i = 0; i <= hSocketMax; i++)
904 FD_SET(i, &fdsetRecv);
907 FD_ZERO(&fdsetError);
908 MilliSleep(timeout.tv_usec/1000);
913 // Accept new connections
915 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
916 if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
919 struct sockaddr_storage sockaddr;
921 struct sockaddr sockaddr;
923 socklen_t len = sizeof(sockaddr);
924 SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
928 if (hSocket != INVALID_SOCKET)
929 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
930 LogPrintf("Warning: Unknown socket family\n");
934 BOOST_FOREACH(CNode* pnode, vNodes)
939 if (hSocket == INVALID_SOCKET)
941 int nErr = WSAGetLastError();
942 if (nErr != WSAEWOULDBLOCK)
943 LogPrintf("socket error accept failed: %d\n", nErr);
945 else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS)
948 LOCK(cs_setservAddNodeAddresses);
949 if (!setservAddNodeAddresses.count(addr))
950 closesocket(hSocket);
953 else if (CNode::IsBanned(addr))
955 LogPrintf("connection from %s dropped (banned)\n", addr.ToString().c_str());
956 closesocket(hSocket);
960 LogPrint("net", "accepted connection %s\n", addr.ToString().c_str());
961 CNode* pnode = new CNode(hSocket, addr, "", true);
965 vNodes.push_back(pnode);
972 // Service each socket
974 vector<CNode*> vNodesCopy;
978 BOOST_FOREACH(CNode* pnode, vNodesCopy)
981 BOOST_FOREACH(CNode* pnode, vNodesCopy)
983 boost::this_thread::interruption_point();
988 if (pnode->hSocket == INVALID_SOCKET)
990 if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
992 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
996 // typical socket buffer is 8K-64K
997 char pchBuf[0x10000];
998 int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1001 if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
1002 pnode->CloseSocketDisconnect();
1003 pnode->nLastRecv = GetTime();
1004 pnode->nRecvBytes += nBytes;
1005 pnode->RecordBytesRecv(nBytes);
1007 else if (nBytes == 0)
1009 // socket closed gracefully
1010 if (!pnode->fDisconnect)
1011 LogPrint("net", "socket closed\n");
1012 pnode->CloseSocketDisconnect();
1014 else if (nBytes < 0)
1017 int nErr = WSAGetLastError();
1018 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
1020 if (!pnode->fDisconnect)
1021 LogPrintf("socket recv error %d\n", nErr);
1022 pnode->CloseSocketDisconnect();
1032 if (pnode->hSocket == INVALID_SOCKET)
1034 if (FD_ISSET(pnode->hSocket, &fdsetSend))
1036 TRY_LOCK(pnode->cs_vSend, lockSend);
1038 SocketSendData(pnode);
1042 // Inactivity checking
1044 if (pnode->vSendMsg.empty())
1045 pnode->nLastSendEmpty = GetTime();
1046 if (GetTime() - pnode->nTimeConnected > 60)
1048 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
1050 LogPrint("net", "socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
1051 pnode->fDisconnect = true;
1053 else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
1055 LogPrintf("socket not sending\n");
1056 pnode->fDisconnect = true;
1058 else if (GetTime() - pnode->nLastRecv > 90*60)
1060 LogPrintf("socket inactivity timeout\n");
1061 pnode->fDisconnect = true;
1067 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1084 void ThreadMapPort()
1086 std::string port = strprintf("%u", GetListenPort());
1087 const char * multicastif = 0;
1088 const char * minissdpdpath = 0;
1089 struct UPNPDev * devlist = 0;
1092 #ifndef UPNPDISCOVER_SUCCESS
1094 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1098 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1101 struct UPNPUrls urls;
1102 struct IGDdatas data;
1105 r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1109 char externalIPAddress[40];
1110 r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1111 if(r != UPNPCOMMAND_SUCCESS)
1112 LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
1115 if(externalIPAddress[0])
1117 LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
1118 AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
1121 LogPrintf("UPnP: GetExternalIPAddress failed.\n");
1125 string strDesc = "Bitcoin " + FormatFullVersion();
1129 #ifndef UPNPDISCOVER_SUCCESS
1131 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1132 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1135 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1136 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1139 if(r!=UPNPCOMMAND_SUCCESS)
1140 LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1141 port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1143 LogPrintf("UPnP Port Mapping successful.\n");;
1145 MilliSleep(20*60*1000); // Refresh every 20 minutes
1148 catch (boost::thread_interrupted)
1150 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1151 LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r);
1152 freeUPNPDevlist(devlist); devlist = 0;
1153 FreeUPNPUrls(&urls);
1157 LogPrintf("No valid UPnP IGDs found\n");
1158 freeUPNPDevlist(devlist); devlist = 0;
1160 FreeUPNPUrls(&urls);
1164 void MapPort(bool fUseUPnP)
1166 static boost::thread* upnp_thread = NULL;
1171 upnp_thread->interrupt();
1172 upnp_thread->join();
1175 upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
1177 else if (upnp_thread) {
1178 upnp_thread->interrupt();
1179 upnp_thread->join();
1188 // Intentionally left blank.
1197 void ThreadDNSAddressSeed()
1199 const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
1202 LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
1204 BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) {
1205 if (HaveNameProxy()) {
1206 AddOneShot(seed.host);
1208 vector<CNetAddr> vIPs;
1209 vector<CAddress> vAdd;
1210 if (LookupHost(seed.host.c_str(), vIPs))
1212 BOOST_FOREACH(CNetAddr& ip, vIPs)
1214 int nOneDay = 24*3600;
1215 CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
1216 addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1217 vAdd.push_back(addr);
1221 addrman.Add(vAdd, CNetAddr(seed.name, true));
1225 LogPrintf("%d addresses found from DNS seeds\n", found);
1239 void DumpAddresses()
1241 int64_t nStart = GetTimeMillis();
1246 LogPrint("net", "Flushed %d addresses to peers.dat %"PRId64"ms\n",
1247 addrman.size(), GetTimeMillis() - nStart);
1250 void static ProcessOneShot()
1255 if (vOneShots.empty())
1257 strDest = vOneShots.front();
1258 vOneShots.pop_front();
1261 CSemaphoreGrant grant(*semOutbound, true);
1263 if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
1264 AddOneShot(strDest);
1268 void ThreadOpenConnections()
1270 // Connect to specific addresses
1271 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
1273 for (int64_t nLoop = 0;; nLoop++)
1276 BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
1279 OpenNetworkConnection(addr, NULL, strAddr.c_str());
1280 for (int i = 0; i < 10 && i < nLoop; i++)
1289 // Initiate network connections
1290 int64_t nStart = GetTime();
1297 CSemaphoreGrant grant(*semOutbound);
1298 boost::this_thread::interruption_point();
1300 // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1301 if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
1302 static bool done = false;
1304 LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1305 addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1"));
1311 // Choose an address to connect to based on most recently seen
1313 CAddress addrConnect;
1315 // Only connect out to one peer per network group (/16 for IPv4).
1316 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1318 set<vector<unsigned char> > setConnected;
1321 BOOST_FOREACH(CNode* pnode, vNodes) {
1322 if (!pnode->fInbound) {
1323 setConnected.insert(pnode->addr.GetGroup());
1329 int64_t nANow = GetAdjustedTime();
1334 // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
1335 CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
1337 // if we selected an invalid address, restart
1338 if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1341 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1342 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1343 // already-connected network ranges, ...) before trying new addrman addresses.
1348 if (IsLimited(addr))
1351 // only consider very recently tried nodes after 30 failed attempts
1352 if (nANow - addr.nLastTry < 600 && nTries < 30)
1355 // do not allow non-default ports, unless after 50 invalid addresses selected already
1356 if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
1363 if (addrConnect.IsValid())
1364 OpenNetworkConnection(addrConnect, &grant);
1368 void ThreadOpenAddedConnections()
1371 LOCK(cs_vAddedNodes);
1372 vAddedNodes = mapMultiArgs["-addnode"];
1375 if (HaveNameProxy()) {
1377 list<string> lAddresses(0);
1379 LOCK(cs_vAddedNodes);
1380 BOOST_FOREACH(string& strAddNode, vAddedNodes)
1381 lAddresses.push_back(strAddNode);
1383 BOOST_FOREACH(string& strAddNode, lAddresses) {
1385 CSemaphoreGrant grant(*semOutbound);
1386 OpenNetworkConnection(addr, &grant, strAddNode.c_str());
1389 MilliSleep(120000); // Retry every 2 minutes
1393 for (unsigned int i = 0; true; i++)
1395 list<string> lAddresses(0);
1397 LOCK(cs_vAddedNodes);
1398 BOOST_FOREACH(string& strAddNode, vAddedNodes)
1399 lAddresses.push_back(strAddNode);
1402 list<vector<CService> > lservAddressesToAdd(0);
1403 BOOST_FOREACH(string& strAddNode, lAddresses)
1405 vector<CService> vservNode(0);
1406 if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0))
1408 lservAddressesToAdd.push_back(vservNode);
1410 LOCK(cs_setservAddNodeAddresses);
1411 BOOST_FOREACH(CService& serv, vservNode)
1412 setservAddNodeAddresses.insert(serv);
1416 // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
1417 // (keeping in mind that addnode entries can have many IPs if fNameLookup)
1420 BOOST_FOREACH(CNode* pnode, vNodes)
1421 for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
1422 BOOST_FOREACH(CService& addrNode, *(it))
1423 if (pnode->addr == addrNode)
1425 it = lservAddressesToAdd.erase(it);
1430 BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd)
1432 CSemaphoreGrant grant(*semOutbound);
1433 OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
1436 MilliSleep(120000); // Retry every 2 minutes
1440 // if successful, this moves the passed grant to the constructed node
1441 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
1444 // Initiate outbound network connection
1446 boost::this_thread::interruption_point();
1448 if (IsLocal(addrConnect) ||
1449 FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
1450 FindNode(addrConnect.ToStringIPPort().c_str()))
1452 if (strDest && FindNode(strDest))
1455 CNode* pnode = ConnectNode(addrConnect, strDest);
1456 boost::this_thread::interruption_point();
1461 grantOutbound->MoveTo(pnode->grantOutbound);
1462 pnode->fNetworkNode = true;
1464 pnode->fOneShot = true;
1470 // for now, use a very simple selection metric: the node from which we received
1472 double static NodeSyncScore(const CNode *pnode) {
1473 return -pnode->nLastRecv;
1476 void static StartSync(const vector<CNode*> &vNodes) {
1477 CNode *pnodeNewSync = NULL;
1478 double dBestScore = 0;
1480 int nBestHeight = g_signals.GetHeight().get_value_or(0);
1482 // Iterate over all nodes
1483 BOOST_FOREACH(CNode* pnode, vNodes) {
1484 // check preconditions for allowing a sync
1485 if (!pnode->fClient && !pnode->fOneShot &&
1486 !pnode->fDisconnect && pnode->fSuccessfullyConnected &&
1487 (pnode->nStartingHeight > (nBestHeight - 144)) &&
1488 (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
1489 // if ok, compare node's score with the best so far
1490 double dScore = NodeSyncScore(pnode);
1491 if (pnodeNewSync == NULL || dScore > dBestScore) {
1492 pnodeNewSync = pnode;
1493 dBestScore = dScore;
1497 // if a new sync candidate was found, start sync!
1499 pnodeNewSync->fStartSync = true;
1500 pnodeSync = pnodeNewSync;
1504 void ThreadMessageHandler()
1506 SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1509 bool fHaveSyncNode = false;
1511 vector<CNode*> vNodesCopy;
1514 vNodesCopy = vNodes;
1515 BOOST_FOREACH(CNode* pnode, vNodesCopy) {
1517 if (pnode == pnodeSync)
1518 fHaveSyncNode = true;
1523 StartSync(vNodesCopy);
1525 // Poll the connected nodes for messages
1526 CNode* pnodeTrickle = NULL;
1527 if (!vNodesCopy.empty())
1528 pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1532 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1534 if (pnode->fDisconnect)
1539 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
1542 if (!g_signals.ProcessMessages(pnode))
1543 pnode->CloseSocketDisconnect();
1545 if (pnode->nSendSize < SendBufferSize())
1547 if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete()))
1554 boost::this_thread::interruption_point();
1558 TRY_LOCK(pnode->cs_vSend, lockSend);
1560 g_signals.SendMessages(pnode, pnode == pnodeTrickle);
1562 boost::this_thread::interruption_point();
1567 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1581 bool BindListenPort(const CService &addrBind, string& strError)
1586 // Create socket for listening for incoming connections
1588 struct sockaddr_storage sockaddr;
1590 struct sockaddr sockaddr;
1592 socklen_t len = sizeof(sockaddr);
1593 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
1595 strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
1596 LogPrintf("%s\n", strError.c_str());
1600 SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
1601 if (hListenSocket == INVALID_SOCKET)
1603 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
1604 LogPrintf("%s\n", strError.c_str());
1609 // Different way of disabling SIGPIPE on BSD
1610 setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1614 // Allow binding if the port is still in TIME_WAIT state after
1615 // the program was closed and restarted. Not an issue on windows.
1616 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1621 // Set to non-blocking, incoming connections will also inherit this
1622 if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
1624 if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
1627 strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
1628 LogPrintf("%s\n", strError.c_str());
1633 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
1634 // and enable it by default or not. Try to enable it, if possible.
1635 if (addrBind.IsIPv6()) {
1638 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
1640 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
1644 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
1645 int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
1646 // this call is allowed to fail
1647 setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
1652 if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
1654 int nErr = WSAGetLastError();
1655 if (nErr == WSAEADDRINUSE)
1656 strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin is probably already running."), addrBind.ToString().c_str());
1658 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
1659 LogPrintf("%s\n", strError.c_str());
1662 LogPrintf("Bound to %s\n", addrBind.ToString().c_str());
1664 // Listen for incoming connections
1665 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1667 strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
1668 LogPrintf("%s\n", strError.c_str());
1672 vhListenSocket.push_back(hListenSocket);
1674 if (addrBind.IsRoutable() && fDiscover)
1675 AddLocal(addrBind, LOCAL_BIND);
1680 void static Discover(boost::thread_group& threadGroup)
1686 // Get local host IP
1687 char pszHostName[1000] = "";
1688 if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1690 vector<CNetAddr> vaddr;
1691 if (LookupHost(pszHostName, vaddr))
1693 BOOST_FOREACH (const CNetAddr &addr, vaddr)
1695 AddLocal(addr, LOCAL_IF);
1700 // Get local host ip
1701 struct ifaddrs* myaddrs;
1702 if (getifaddrs(&myaddrs) == 0)
1704 for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1706 if (ifa->ifa_addr == NULL) continue;
1707 if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1708 if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1709 if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1710 if (ifa->ifa_addr->sa_family == AF_INET)
1712 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1713 CNetAddr addr(s4->sin_addr);
1714 if (AddLocal(addr, LOCAL_IF))
1715 LogPrintf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1718 else if (ifa->ifa_addr->sa_family == AF_INET6)
1720 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1721 CNetAddr addr(s6->sin6_addr);
1722 if (AddLocal(addr, LOCAL_IF))
1723 LogPrintf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1727 freeifaddrs(myaddrs);
1731 // Don't use external IPv4 discovery, when -onlynet="IPv6"
1732 if (!IsLimited(NET_IPV4))
1733 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "ext-ip", &ThreadGetMyExternalIP));
1736 void StartNode(boost::thread_group& threadGroup)
1738 if (semOutbound == NULL) {
1739 // initialize semaphore
1740 int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
1741 semOutbound = new CSemaphore(nMaxOutbound);
1744 if (pnodeLocalHost == NULL)
1745 pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
1747 Discover(threadGroup);
1753 if (!GetBoolArg("-dnsseed", true))
1754 LogPrintf("DNS seeding disabled\n");
1756 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
1759 // Map ports with UPnP
1760 MapPort(GetBoolArg("-upnp", USE_UPNP));
1763 // Send and receive from sockets, accept connections
1764 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
1766 // Initiate outbound connections from -addnode
1767 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
1769 // Initiate outbound connections
1770 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
1773 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
1775 // Dump network addresses
1776 threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000));
1781 LogPrintf("StopNode()\n");
1784 for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
1785 semOutbound->post();
1801 BOOST_FOREACH(CNode* pnode, vNodes)
1802 if (pnode->hSocket != INVALID_SOCKET)
1803 closesocket(pnode->hSocket);
1804 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
1805 if (hListenSocket != INVALID_SOCKET)
1806 if (closesocket(hListenSocket) == SOCKET_ERROR)
1807 LogPrintf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
1809 // clean up some globals (to help leak detection)
1810 BOOST_FOREACH(CNode *pnode, vNodes)
1812 BOOST_FOREACH(CNode *pnode, vNodesDisconnected)
1815 vNodesDisconnected.clear();
1818 delete pnodeLocalHost;
1819 pnodeLocalHost = NULL;
1822 // Shutdown Windows Sockets
1827 instance_of_cnetcleanup;
1835 void RelayTransaction(const CTransaction& tx, const uint256& hash)
1837 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1840 RelayTransaction(tx, hash, ss);
1843 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
1845 CInv inv(MSG_TX, hash);
1848 // Expire old relay messages
1849 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
1851 mapRelay.erase(vRelayExpiration.front().second);
1852 vRelayExpiration.pop_front();
1855 // Save original serialized message so newer versions are preserved
1856 mapRelay.insert(std::make_pair(inv, ss));
1857 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
1860 BOOST_FOREACH(CNode* pnode, vNodes)
1862 if(!pnode->fRelayTxes)
1864 LOCK(pnode->cs_filter);
1867 if (pnode->pfilter->IsRelevantAndUpdate(tx, hash))
1868 pnode->PushInventory(inv);
1870 pnode->PushInventory(inv);
1874 void CNode::RecordBytesRecv(uint64_t bytes)
1876 LOCK(cs_totalBytesRecv);
1877 nTotalBytesRecv += bytes;
1880 void CNode::RecordBytesSent(uint64_t bytes)
1882 LOCK(cs_totalBytesSent);
1883 nTotalBytesSent += bytes;
1886 uint64_t CNode::GetTotalBytesRecv()
1888 LOCK(cs_totalBytesRecv);
1889 return nTotalBytesRecv;
1892 uint64_t CNode::GetTotalBytesSent()
1894 LOCK(cs_totalBytesSent);
1895 return nTotalBytesSent;
1898 void CNode::Fuzz(int nChance)
1900 if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
1901 if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
1906 // xor a random byte with a random value:
1907 if (!ssSend.empty()) {
1908 CDataStream::size_type pos = GetRand(ssSend.size());
1909 ssSend[pos] ^= (unsigned char)(GetRand(256));
1913 // delete a random byte:
1914 if (!ssSend.empty()) {
1915 CDataStream::size_type pos = GetRand(ssSend.size());
1916 ssSend.erase(ssSend.begin()+pos);
1920 // insert a random byte at a random position
1922 CDataStream::size_type pos = GetRand(ssSend.size());
1923 char ch = (char)GetRand(256);
1924 ssSend.insert(ssSend.begin()+pos, ch);
1928 // Chance of more than one change half the time:
1929 // (more changes exponentially less likely):
1939 pathAddr = GetDataDir() / "peers.dat";
1942 bool CAddrDB::Write(const CAddrMan& addr)
1944 // Generate random temporary filename
1945 unsigned short randv = 0;
1946 RAND_bytes((unsigned char *)&randv, sizeof(randv));
1947 std::string tmpfn = strprintf("peers.dat.%04x", randv);
1949 // serialize addresses, checksum data up to that point, then append csum
1950 CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
1951 ssPeers << FLATDATA(Params().MessageStart());
1953 uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
1956 // open temp output file, and associate with CAutoFile
1957 boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
1958 FILE *file = fopen(pathTmp.string().c_str(), "wb");
1959 CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
1961 return error("CAddrman::Write() : open failed");
1963 // Write and commit header, data
1967 catch (std::exception &e) {
1968 return error("CAddrman::Write() : I/O error");
1970 FileCommit(fileout);
1973 // replace existing peers.dat, if any, with new peers.dat.XXXX
1974 if (!RenameOver(pathTmp, pathAddr))
1975 return error("CAddrman::Write() : Rename-into-place failed");
1980 bool CAddrDB::Read(CAddrMan& addr)
1982 // open input file, and associate with CAutoFile
1983 FILE *file = fopen(pathAddr.string().c_str(), "rb");
1984 CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
1986 return error("CAddrman::Read() : open failed");
1988 // use file size to size memory buffer
1989 int fileSize = GetFilesize(filein);
1990 int dataSize = fileSize - sizeof(uint256);
1991 //Don't try to resize to a negative number if file is small
1992 if ( dataSize < 0 ) dataSize = 0;
1993 vector<unsigned char> vchData;
1994 vchData.resize(dataSize);
1997 // read data and checksum from file
1999 filein.read((char *)&vchData[0], dataSize);
2002 catch (std::exception &e) {
2003 return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
2007 CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
2009 // verify stored checksum matches input data
2010 uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
2011 if (hashIn != hashTmp)
2012 return error("CAddrman::Read() : checksum mismatch; data corrupted");
2014 unsigned char pchMsgTmp[4];
2016 // de-serialize file header (network specific magic number) and ..
2017 ssPeers >> FLATDATA(pchMsgTmp);
2019 // ... verify the network matches ours
2020 if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
2021 return error("CAddrman::Read() : invalid network magic number");
2023 // de-serialize address data into one CAddrMan object
2026 catch (std::exception &e) {
2027 return error("CAddrman::Read() : I/O error or stream data corrupted");