Bitcoin v0.1.0 · 2009-01-08
net.cpp
1// Copyright (c) 2009 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"6#include <winsock2.h>78void ThreadMessageHandler2(void* parg);9void ThreadSocketHandler2(void* parg);10void ThreadOpenConnections2(void* parg);11121314151617//18// Global state variables19//20bool fClient = false;21uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);22CAddress addrLocalHost(0, DEFAULT_PORT, nLocalServices);23CNode nodeLocalHost(INVALID_SOCKET, CAddress("127.0.0.1", nLocalServices));24CNode* pnodeLocalHost = &nodeLocalHost;25bool fShutdown = false;26array<bool, 10> vfThreadRunning;27vector<CNode*> vNodes;28CCriticalSection cs_vNodes;29map<vector<unsigned char>, CAddress> mapAddresses;30CCriticalSection cs_mapAddresses;31map<CInv, CDataStream> mapRelay;32deque<pair<int64, CInv> > vRelayExpiration;33CCriticalSection cs_mapRelay;34map<CInv, int64> mapAlreadyAskedFor;35363738CAddress addrProxy;3940bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet)41{42 hSocketRet = INVALID_SOCKET;4344 SOCKET hSocket = socket(AF_INET, SOCK_STREAM, 0);45 if (hSocket == INVALID_SOCKET)46 return false;4748 bool fRoutable = !(addrConnect.GetByte(3) == 10 || (addrConnect.GetByte(3) == 192 && addrConnect.GetByte(2) == 168));49 bool fProxy = (addrProxy.ip && fRoutable);50 struct sockaddr_in sockaddr = (fProxy ? addrProxy.GetSockAddr() : addrConnect.GetSockAddr());5152 if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)53 {54 closesocket(hSocket);55 return false;56 }5758 if (fProxy)59 {60 printf("Proxy connecting to %s\n", addrConnect.ToString().c_str());61 char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";62 memcpy(pszSocks4IP + 2, &addrConnect.port, 2);63 memcpy(pszSocks4IP + 4, &addrConnect.ip, 4);64 char* pszSocks4 = pszSocks4IP;65 int nSize = sizeof(pszSocks4IP);6667 int ret = send(hSocket, pszSocks4, nSize, 0);68 if (ret != nSize)69 {70 closesocket(hSocket);71 return error("Error sending to proxy\n");72 }73 char pchRet[8];74 if (recv(hSocket, pchRet, 8, 0) != 8)75 {76 closesocket(hSocket);77 return error("Error reading proxy response\n");78 }79 if (pchRet[1] != 0x5a)80 {81 closesocket(hSocket);82 return error("Proxy returned error %d\n", pchRet[1]);83 }84 printf("Proxy connection established %s\n", addrConnect.ToString().c_str());85 }8687 hSocketRet = hSocket;88 return true;89}909192bool GetMyExternalIP(unsigned int& ipRet)93{94 CAddress addrConnect("72.233.89.199:80"); // whatismyip.com 198-2009596 SOCKET hSocket;97 if (!ConnectSocket(addrConnect, hSocket))98 return error("GetMyExternalIP() : connection to %s failed\n", addrConnect.ToString().c_str());99100 char* pszGet =101 "GET /automation/n09230945.asp HTTP/1.1\r\n"102 "Host: www.whatismyip.com\r\n"103 "User-Agent: Bitcoin/0.1\r\n"104 "Connection: close\r\n"105 "\r\n";106 send(hSocket, pszGet, strlen(pszGet), 0);107108 string strLine;109 while (RecvLine(hSocket, strLine))110 {111 if (strLine.empty())112 {113 if (!RecvLine(hSocket, strLine))114 {115 closesocket(hSocket);116 return false;117 }118 closesocket(hSocket);119 CAddress addr(strLine.c_str());120 printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());121 if (addr.ip == 0)122 return false;123 ipRet = addr.ip;124 return true;125 }126 }127 closesocket(hSocket);128 return error("GetMyExternalIP() : connection closed\n");129}130131132133134135136bool AddAddress(CAddrDB& addrdb, const CAddress& addr)137{138 if (!addr.IsRoutable())139 return false;140 if (addr.ip == addrLocalHost.ip)141 return false;142 CRITICAL_BLOCK(cs_mapAddresses)143 {144 map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());145 if (it == mapAddresses.end())146 {147 // New address148 mapAddresses.insert(make_pair(addr.GetKey(), addr));149 addrdb.WriteAddress(addr);150 return true;151 }152 else153 {154 CAddress& addrFound = (*it).second;155 if ((addrFound.nServices | addr.nServices) != addrFound.nServices)156 {157 // Services have been added158 addrFound.nServices |= addr.nServices;159 addrdb.WriteAddress(addrFound);160 return true;161 }162 }163 }164 return false;165}166167168169170171void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1)172{173 // If the dialog might get closed before the reply comes back,174 // call this in the destructor so it doesn't get called after it's deleted.175 CRITICAL_BLOCK(cs_vNodes)176 {177 foreach(CNode* pnode, vNodes)178 {179 CRITICAL_BLOCK(pnode->cs_mapRequests)180 {181 for (map<uint256, CRequestTracker>::iterator mi = pnode->mapRequests.begin(); mi != pnode->mapRequests.end();)182 {183 CRequestTracker& tracker = (*mi).second;184 if (tracker.fn == fn && tracker.param1 == param1)185 pnode->mapRequests.erase(mi++);186 else187 mi++;188 }189 }190 }191 }192}193194195196197198199200//201// Subscription methods for the broadcast and subscription system.202// Channel numbers are message numbers, i.e. MSG_TABLE and MSG_PRODUCT.203//204// The subscription system uses a meet-in-the-middle strategy.205// With 100,000 nodes, if senders broadcast to 1000 random nodes and receivers206// subscribe to 1000 random nodes, 99.995% (1 - 0.99^1000) of messages will get through.207//208209bool AnySubscribed(unsigned int nChannel)210{211 if (pnodeLocalHost->IsSubscribed(nChannel))212 return true;213 CRITICAL_BLOCK(cs_vNodes)214 foreach(CNode* pnode, vNodes)215 if (pnode->IsSubscribed(nChannel))216 return true;217 return false;218}219220bool CNode::IsSubscribed(unsigned int nChannel)221{222 if (nChannel >= vfSubscribe.size())223 return false;224 return vfSubscribe[nChannel];225}226227void CNode::Subscribe(unsigned int nChannel, unsigned int nHops)228{229 if (nChannel >= vfSubscribe.size())230 return;231232 if (!AnySubscribed(nChannel))233 {234 // Relay subscribe235 CRITICAL_BLOCK(cs_vNodes)236 foreach(CNode* pnode, vNodes)237 if (pnode != this)238 pnode->PushMessage("subscribe", nChannel, nHops);239 }240241 vfSubscribe[nChannel] = true;242}243244void CNode::CancelSubscribe(unsigned int nChannel)245{246 if (nChannel >= vfSubscribe.size())247 return;248249 // Prevent from relaying cancel if wasn't subscribed250 if (!vfSubscribe[nChannel])251 return;252 vfSubscribe[nChannel] = false;253254 if (!AnySubscribed(nChannel))255 {256 // Relay subscription cancel257 CRITICAL_BLOCK(cs_vNodes)258 foreach(CNode* pnode, vNodes)259 if (pnode != this)260 pnode->PushMessage("sub-cancel", nChannel);261262 // Clear memory, no longer subscribed263 if (nChannel == MSG_PRODUCT)264 CRITICAL_BLOCK(cs_mapProducts)265 mapProducts.clear();266 }267}268269270271272273274275276277CNode* FindNode(unsigned int ip)278{279 CRITICAL_BLOCK(cs_vNodes)280 {281 foreach(CNode* pnode, vNodes)282 if (pnode->addr.ip == ip)283 return (pnode);284 }285 return NULL;286}287288CNode* FindNode(CAddress addr)289{290 CRITICAL_BLOCK(cs_vNodes)291 {292 foreach(CNode* pnode, vNodes)293 if (pnode->addr == addr)294 return (pnode);295 }296 return NULL;297}298299CNode* ConnectNode(CAddress addrConnect, int64 nTimeout)300{301 if (addrConnect.ip == addrLocalHost.ip)302 return NULL;303304 // Look for an existing connection305 CNode* pnode = FindNode(addrConnect.ip);306 if (pnode)307 {308 if (nTimeout != 0)309 pnode->AddRef(nTimeout);310 else311 pnode->AddRef();312 return pnode;313 }314315 /// debug print316 printf("trying %s\n", addrConnect.ToString().c_str());317318 // Connect319 SOCKET hSocket;320 if (ConnectSocket(addrConnect, hSocket))321 {322 /// debug print323 printf("connected %s\n", addrConnect.ToString().c_str());324325 // Add node326 CNode* pnode = new CNode(hSocket, addrConnect, false);327 if (nTimeout != 0)328 pnode->AddRef(nTimeout);329 else330 pnode->AddRef();331 CRITICAL_BLOCK(cs_vNodes)332 vNodes.push_back(pnode);333334 CRITICAL_BLOCK(cs_mapAddresses)335 mapAddresses[addrConnect.GetKey()].nLastFailed = 0;336 return pnode;337 }338 else339 {340 CRITICAL_BLOCK(cs_mapAddresses)341 mapAddresses[addrConnect.GetKey()].nLastFailed = GetTime();342 return NULL;343 }344}345346void CNode::Disconnect()347{348 printf("disconnecting node %s\n", addr.ToString().c_str());349350 closesocket(hSocket);351352 // All of a nodes broadcasts and subscriptions are automatically torn down353 // when it goes down, so a node has to stay up to keep its broadcast going.354355 CRITICAL_BLOCK(cs_mapProducts)356 for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end();)357 AdvertRemoveSource(this, MSG_PRODUCT, 0, (*(mi++)).second);358359 // Cancel subscriptions360 for (unsigned int nChannel = 0; nChannel < vfSubscribe.size(); nChannel++)361 if (vfSubscribe[nChannel])362 CancelSubscribe(nChannel);363}364365366367368369370371372373374375376377void ThreadSocketHandler(void* parg)378{379 IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));380381 loop382 {383 vfThreadRunning[0] = true;384 CheckForShutdown(0);385 try386 {387 ThreadSocketHandler2(parg);388 }389 CATCH_PRINT_EXCEPTION("ThreadSocketHandler()")390 vfThreadRunning[0] = false;391 Sleep(5000);392 }393}394395void ThreadSocketHandler2(void* parg)396{397 printf("ThreadSocketHandler started\n");398 SOCKET hListenSocket = *(SOCKET*)parg;399 list<CNode*> vNodesDisconnected;400 int nPrevNodeCount = 0;401402 loop403 {404 //405 // Disconnect nodes406 //407 CRITICAL_BLOCK(cs_vNodes)408 {409 // Disconnect duplicate connections410 map<unsigned int, CNode*> mapFirst;411 foreach(CNode* pnode, vNodes)412 {413 if (pnode->fDisconnect)414 continue;415 unsigned int ip = pnode->addr.ip;416 if (mapFirst.count(ip) && addrLocalHost.ip < ip)417 {418 // In case two nodes connect to each other at once,419 // the lower ip disconnects its outbound connection420 CNode* pnodeExtra = mapFirst[ip];421422 if (pnodeExtra->GetRefCount() > (pnodeExtra->fNetworkNode ? 1 : 0))423 swap(pnodeExtra, pnode);424425 if (pnodeExtra->GetRefCount() <= (pnodeExtra->fNetworkNode ? 1 : 0))426 {427 printf("(%d nodes) disconnecting duplicate: %s\n", vNodes.size(), pnodeExtra->addr.ToString().c_str());428 if (pnodeExtra->fNetworkNode && !pnode->fNetworkNode)429 {430 pnode->AddRef();431 swap(pnodeExtra->fNetworkNode, pnode->fNetworkNode);432 pnodeExtra->Release();433 }434 pnodeExtra->fDisconnect = true;435 }436 }437 mapFirst[ip] = pnode;438 }439440 // Disconnect unused nodes441 vector<CNode*> vNodesCopy = vNodes;442 foreach(CNode* pnode, vNodesCopy)443 {444 if (pnode->ReadyToDisconnect() && pnode->vRecv.empty() && pnode->vSend.empty())445 {446 // remove from vNodes447 vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());448 pnode->Disconnect();449450 // hold in disconnected pool until all refs are released451 pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 5 * 60);452 if (pnode->fNetworkNode)453 pnode->Release();454 vNodesDisconnected.push_back(pnode);455 }456 }457458 // Delete disconnected nodes459 list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;460 foreach(CNode* pnode, vNodesDisconnectedCopy)461 {462 // wait until threads are done using it463 if (pnode->GetRefCount() <= 0)464 {465 bool fDelete = false;466 TRY_CRITICAL_BLOCK(pnode->cs_vSend)467 TRY_CRITICAL_BLOCK(pnode->cs_vRecv)468 TRY_CRITICAL_BLOCK(pnode->cs_mapRequests)469 TRY_CRITICAL_BLOCK(pnode->cs_inventory)470 fDelete = true;471 if (fDelete)472 {473 vNodesDisconnected.remove(pnode);474 delete pnode;475 }476 }477 }478 }479 if (vNodes.size() != nPrevNodeCount)480 {481 nPrevNodeCount = vNodes.size();482 MainFrameRepaint();483 }484485486 //487 // Find which sockets have data to receive488 //489 struct timeval timeout;490 timeout.tv_sec = 0;491 timeout.tv_usec = 50000; // frequency to poll pnode->vSend492493 struct fd_set fdsetRecv;494 struct fd_set fdsetSend;495 FD_ZERO(&fdsetRecv);496 FD_ZERO(&fdsetSend);497 SOCKET hSocketMax = 0;498 FD_SET(hListenSocket, &fdsetRecv);499 hSocketMax = max(hSocketMax, hListenSocket);500 CRITICAL_BLOCK(cs_vNodes)501 {502 foreach(CNode* pnode, vNodes)503 {504 FD_SET(pnode->hSocket, &fdsetRecv);505 hSocketMax = max(hSocketMax, pnode->hSocket);506 TRY_CRITICAL_BLOCK(pnode->cs_vSend)507 if (!pnode->vSend.empty())508 FD_SET(pnode->hSocket, &fdsetSend);509 }510 }511512 vfThreadRunning[0] = false;513 int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, NULL, &timeout);514 vfThreadRunning[0] = true;515 CheckForShutdown(0);516 if (nSelect == SOCKET_ERROR)517 {518 int nErr = WSAGetLastError();519 printf("select failed: %d\n", nErr);520 for (int i = 0; i <= hSocketMax; i++)521 {522 FD_SET(i, &fdsetRecv);523 FD_SET(i, &fdsetSend);524 }525 Sleep(timeout.tv_usec/1000);526 }527 RandAddSeed();528529 //// debug print530 //foreach(CNode* pnode, vNodes)531 //{532 // printf("vRecv = %-5d ", pnode->vRecv.size());533 // printf("vSend = %-5d ", pnode->vSend.size());534 //}535 //printf("\n");536537538 //539 // Accept new connections540 //541 if (FD_ISSET(hListenSocket, &fdsetRecv))542 {543 struct sockaddr_in sockaddr;544 int len = sizeof(sockaddr);545 SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);546 CAddress addr(sockaddr);547 if (hSocket == INVALID_SOCKET)548 {549 if (WSAGetLastError() != WSAEWOULDBLOCK)550 printf("ERROR ThreadSocketHandler accept failed: %d\n", WSAGetLastError());551 }552 else553 {554 printf("accepted connection from %s\n", addr.ToString().c_str());555 CNode* pnode = new CNode(hSocket, addr, true);556 pnode->AddRef();557 CRITICAL_BLOCK(cs_vNodes)558 vNodes.push_back(pnode);559 }560 }561562563 //564 // Service each socket565 //566 vector<CNode*> vNodesCopy;567 CRITICAL_BLOCK(cs_vNodes)568 vNodesCopy = vNodes;569 foreach(CNode* pnode, vNodesCopy)570 {571 CheckForShutdown(0);572 SOCKET hSocket = pnode->hSocket;573574 //575 // Receive576 //577 if (FD_ISSET(hSocket, &fdsetRecv))578 {579 TRY_CRITICAL_BLOCK(pnode->cs_vRecv)580 {581 CDataStream& vRecv = pnode->vRecv;582 unsigned int nPos = vRecv.size();583584 // typical socket buffer is 8K-64K585 const unsigned int nBufSize = 0x10000;586 vRecv.resize(nPos + nBufSize);587 int nBytes = recv(hSocket, &vRecv[nPos], nBufSize, 0);588 vRecv.resize(nPos + max(nBytes, 0));589 if (nBytes == 0)590 {591 // socket closed gracefully592 if (!pnode->fDisconnect)593 printf("recv: socket closed\n");594 pnode->fDisconnect = true;595 }596 else if (nBytes < 0)597 {598 // socket error599 int nErr = WSAGetLastError();600 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)601 {602 if (!pnode->fDisconnect)603 printf("recv failed: %d\n", nErr);604 pnode->fDisconnect = true;605 }606 }607 }608 }609610 //611 // Send612 //613 if (FD_ISSET(hSocket, &fdsetSend))614 {615 TRY_CRITICAL_BLOCK(pnode->cs_vSend)616 {617 CDataStream& vSend = pnode->vSend;618 if (!vSend.empty())619 {620 int nBytes = send(hSocket, &vSend[0], vSend.size(), 0);621 if (nBytes > 0)622 {623 vSend.erase(vSend.begin(), vSend.begin() + nBytes);624 }625 else if (nBytes == 0)626 {627 if (pnode->ReadyToDisconnect())628 pnode->vSend.clear();629 }630 else631 {632 printf("send error %d\n", nBytes);633 if (pnode->ReadyToDisconnect())634 pnode->vSend.clear();635 }636 }637 }638 }639 }640641642 Sleep(10);643 }644}645646647648649650651652653654655void ThreadOpenConnections(void* parg)656{657 IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));658659 loop660 {661 vfThreadRunning[1] = true;662 CheckForShutdown(1);663 try664 {665 ThreadOpenConnections2(parg);666 }667 CATCH_PRINT_EXCEPTION("ThreadOpenConnections()")668 vfThreadRunning[1] = false;669 Sleep(5000);670 }671}672673void ThreadOpenConnections2(void* parg)674{675 printf("ThreadOpenConnections started\n");676677 // Initiate network connections678 const int nMaxConnections = 15;679 loop680 {681 // Wait682 vfThreadRunning[1] = false;683 Sleep(500);684 while (vNodes.size() >= nMaxConnections || vNodes.size() >= mapAddresses.size())685 {686 CheckForShutdown(1);687 Sleep(2000);688 }689 vfThreadRunning[1] = true;690 CheckForShutdown(1);691692693 // Make a list of unique class C's694 unsigned char pchIPCMask[4] = { 0xff, 0xff, 0xff, 0x00 };695 unsigned int nIPCMask = *(unsigned int*)pchIPCMask;696 vector<unsigned int> vIPC;697 CRITICAL_BLOCK(cs_mapAddresses)698 {699 vIPC.reserve(mapAddresses.size());700 unsigned int nPrev = 0;701 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)702 {703 const CAddress& addr = item.second;704 if (!addr.IsIPv4())705 continue;706707 // Taking advantage of mapAddresses being in sorted order,708 // with IPs of the same class C grouped together.709 unsigned int ipC = addr.ip & nIPCMask;710 if (ipC != nPrev)711 vIPC.push_back(nPrev = ipC);712 }713 }714715 //716 // The IP selection process is designed to limit vulnerability to address flooding.717 // Any class C (a.b.c.?) has an equal chance of being chosen, then an IP is718 // chosen within the class C. An attacker may be able to allocate many IPs, but719 // they would normally be concentrated in blocks of class C's. They can hog the720 // attention within their class C, but not the whole IP address space overall.721 // A lone node in a class C will get as much attention as someone holding all 255722 // IPs in another class C.723 //724 bool fSuccess = false;725 int nLimit = vIPC.size();726 while (!fSuccess && nLimit-- > 0)727 {728 // Choose a random class C729 unsigned int ipC = vIPC[GetRand(vIPC.size())];730731 // Organize all addresses in the class C by IP732 map<unsigned int, vector<CAddress> > mapIP;733 CRITICAL_BLOCK(cs_mapAddresses)734 {735 unsigned int nDelay = ((30 * 60) << vNodes.size());736 if (nDelay > 8 * 60 * 60)737 nDelay = 8 * 60 * 60;738 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.lower_bound(CAddress(ipC, 0).GetKey());739 mi != mapAddresses.upper_bound(CAddress(ipC | ~nIPCMask, 0xffff).GetKey());740 ++mi)741 {742 const CAddress& addr = (*mi).second;743 unsigned int nRandomizer = (addr.nLastFailed * addr.ip * 7777U) % 20000;744 if (GetTime() - addr.nLastFailed > nDelay * nRandomizer / 10000)745 mapIP[addr.ip].push_back(addr);746 }747 }748 if (mapIP.empty())749 break;750751 // Choose a random IP in the class C752 map<unsigned int, vector<CAddress> >::iterator mi = mapIP.begin();753 advance(mi, GetRand(mapIP.size()));754755 // Once we've chosen an IP, we'll try every given port before moving on756 foreach(const CAddress& addrConnect, (*mi).second)757 {758 if (addrConnect.ip == addrLocalHost.ip || !addrConnect.IsIPv4() || FindNode(addrConnect.ip))759 continue;760761 CNode* pnode = ConnectNode(addrConnect);762 if (!pnode)763 continue;764 pnode->fNetworkNode = true;765766 if (addrLocalHost.IsRoutable())767 {768 // Advertise our address769 vector<CAddress> vAddrToSend;770 vAddrToSend.push_back(addrLocalHost);771 pnode->PushMessage("addr", vAddrToSend);772 }773774 // Get as many addresses as we can775 pnode->PushMessage("getaddr");776777 ////// should the one on the receiving end do this too?778 // Subscribe our local subscription list779 const unsigned int nHops = 0;780 for (unsigned int nChannel = 0; nChannel < pnodeLocalHost->vfSubscribe.size(); nChannel++)781 if (pnodeLocalHost->vfSubscribe[nChannel])782 pnode->PushMessage("subscribe", nChannel, nHops);783784 fSuccess = true;785 break;786 }787 }788 }789}790791792793794795796797798void ThreadMessageHandler(void* parg)799{800 IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));801802 loop803 {804 vfThreadRunning[2] = true;805 CheckForShutdown(2);806 try807 {808 ThreadMessageHandler2(parg);809 }810 CATCH_PRINT_EXCEPTION("ThreadMessageHandler()")811 vfThreadRunning[2] = false;812 Sleep(5000);813 }814}815816void ThreadMessageHandler2(void* parg)817{818 printf("ThreadMessageHandler started\n");819 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);820 loop821 {822 // Poll the connected nodes for messages823 vector<CNode*> vNodesCopy;824 CRITICAL_BLOCK(cs_vNodes)825 vNodesCopy = vNodes;826 foreach(CNode* pnode, vNodesCopy)827 {828 pnode->AddRef();829830 // Receive messages831 TRY_CRITICAL_BLOCK(pnode->cs_vRecv)832 ProcessMessages(pnode);833834 // Send messages835 TRY_CRITICAL_BLOCK(pnode->cs_vSend)836 SendMessages(pnode);837838 pnode->Release();839 }840841 // Wait and allow messages to bunch up842 vfThreadRunning[2] = false;843 Sleep(100);844 vfThreadRunning[2] = true;845 CheckForShutdown(2);846 }847}848849850851852853854855856857//// todo: start one thread per processor, use getenv("NUMBER_OF_PROCESSORS")858void ThreadBitcoinMiner(void* parg)859{860 vfThreadRunning[3] = true;861 CheckForShutdown(3);862 try863 {864 bool fRet = BitcoinMiner();865 printf("BitcoinMiner returned %s\n\n\n", fRet ? "true" : "false");866 }867 CATCH_PRINT_EXCEPTION("BitcoinMiner()")868 vfThreadRunning[3] = false;869}870871872873874875876877878879880881bool StartNode(string& strError)882{883 strError = "";884885 // Sockets startup886 WSADATA wsadata;887 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);888 if (ret != NO_ERROR)889 {890 strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);891 printf("%s\n", strError.c_str());892 return false;893 }894895 // Get local host ip896 char pszHostName[255];897 if (gethostname(pszHostName, 255) == SOCKET_ERROR)898 {899 strError = strprintf("Error: Unable to get IP address of this computer (gethostname returned error %d)", WSAGetLastError());900 printf("%s\n", strError.c_str());901 return false;902 }903 struct hostent* pHostEnt = gethostbyname(pszHostName);904 if (!pHostEnt)905 {906 strError = strprintf("Error: Unable to get IP address of this computer (gethostbyname returned error %d)", WSAGetLastError());907 printf("%s\n", strError.c_str());908 return false;909 }910 addrLocalHost = CAddress(*(long*)(pHostEnt->h_addr_list[0]),911 DEFAULT_PORT,912 nLocalServices);913 printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());914915 // Create socket for listening for incoming connections916 SOCKET hListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);917 if (hListenSocket == INVALID_SOCKET)918 {919 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());920 printf("%s\n", strError.c_str());921 return false;922 }923924 // Set to nonblocking, incoming connections will also inherit this925 u_long nOne = 1;926 if (ioctlsocket(hListenSocket, FIONBIO, &nOne) == SOCKET_ERROR)927 {928 strError = strprintf("Error: Couldn't set properties on socket for incoming connections (ioctlsocket returned error %d)", WSAGetLastError());929 printf("%s\n", strError.c_str());930 return false;931 }932933 // The sockaddr_in structure specifies the address family,934 // IP address, and port for the socket that is being bound935 int nRetryLimit = 15;936 struct sockaddr_in sockaddr = addrLocalHost.GetSockAddr();937 if (bind(hListenSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)938 {939 int nErr = WSAGetLastError();940 if (nErr == WSAEADDRINUSE)941 strError = strprintf("Error: Unable to bind to port %s on this computer. The program is probably already running.", addrLocalHost.ToString().c_str());942 else943 strError = strprintf("Error: Unable to bind to port %s on this computer (bind returned error %d)", addrLocalHost.ToString().c_str(), nErr);944 printf("%s\n", strError.c_str());945 return false;946 }947 printf("bound to addrLocalHost = %s\n\n", addrLocalHost.ToString().c_str());948949 // Listen for incoming connections950 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)951 {952 strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());953 printf("%s\n", strError.c_str());954 return false;955 }956957 // Get our external IP address for incoming connections958 if (addrIncoming.ip)959 addrLocalHost.ip = addrIncoming.ip;960961 if (GetMyExternalIP(addrLocalHost.ip))962 {963 addrIncoming = addrLocalHost;964 CWalletDB().WriteSetting("addrIncoming", addrIncoming);965 }966967 // Get addresses from IRC and advertise ours968 if (_beginthread(ThreadIRCSeed, 0, NULL) == -1)969 printf("Error: _beginthread(ThreadIRCSeed) failed\n");970971 //972 // Start threads973 //974 if (_beginthread(ThreadSocketHandler, 0, new SOCKET(hListenSocket)) == -1)975 {976 strError = "Error: _beginthread(ThreadSocketHandler) failed";977 printf("%s\n", strError.c_str());978 return false;979 }980981 if (_beginthread(ThreadOpenConnections, 0, NULL) == -1)982 {983 strError = "Error: _beginthread(ThreadOpenConnections) failed";984 printf("%s\n", strError.c_str());985 return false;986 }987988 if (_beginthread(ThreadMessageHandler, 0, NULL) == -1)989 {990 strError = "Error: _beginthread(ThreadMessageHandler) failed";991 printf("%s\n", strError.c_str());992 return false;993 }994995 return true;996}997998bool StopNode()999{1000 printf("StopNode()\n");1001 fShutdown = true;1002 nTransactionsUpdated++;1003 while (count(vfThreadRunning.begin(), vfThreadRunning.end(), true))1004 Sleep(10);1005 Sleep(50);10061007 // Sockets shutdown1008 WSACleanup();1009 return true;1010}10111012void CheckForShutdown(int n)1013{1014 if (fShutdown)1015 {1016 if (n != -1)1017 vfThreadRunning[n] = false;1018 _endthread();1019 }1020}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
