net.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832
  1. // ECOin - Copyright (c) - 2014/2022 - GPLv3 - epsylon@riseup.net (https://03c8.net)
  2. #include "irc.h"
  3. #include "db.h"
  4. #include "net.h"
  5. #include "init.h"
  6. #include "strlcpy.h"
  7. #include "addrman.h"
  8. #include "ui_interface.h"
  9. #ifdef WIN32
  10. #include <string.h>
  11. #endif
  12. #ifdef USE_UPNP
  13. #include <miniupnpc/miniwget.h>
  14. #include <miniupnpc/miniupnpc.h>
  15. #include <miniupnpc/upnpcommands.h>
  16. #include <miniupnpc/upnperrors.h>
  17. #endif
  18. using namespace std;
  19. using namespace boost;
  20. static const int MAX_OUTBOUND_CONNECTIONS = 16;
  21. void ThreadMessageHandler2(void* parg);
  22. void ThreadSocketHandler2(void* parg);
  23. void ThreadOpenConnections2(void* parg);
  24. void ThreadOpenAddedConnections2(void* parg);
  25. #ifdef USE_UPNP
  26. void ThreadMapPort2(void* parg);
  27. #endif
  28. void ThreadDNSAddressSeed2(void* parg);
  29. bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
  30. struct LocalServiceInfo {
  31. int nScore;
  32. int nPort;
  33. };
  34. // Global state variables
  35. bool fClient = false;
  36. bool fDiscover = true;
  37. bool fUseUPnP = false;
  38. uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
  39. static CCriticalSection cs_mapLocalHost;
  40. static map<CNetAddr, LocalServiceInfo> mapLocalHost;
  41. static bool vfReachable[NET_MAX] = {};
  42. static bool vfLimited[NET_MAX] = {};
  43. static CNode* pnodeLocalHost = NULL;
  44. CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices);
  45. uint64 nLocalHostNonce = 0;
  46. boost::array<int, THREAD_MAX> vnThreadsRunning;
  47. static std::vector<SOCKET> vhListenSocket;
  48. CAddrMan addrman;
  49. vector<CNode*> vNodes;
  50. CCriticalSection cs_vNodes;
  51. map<CInv, CDataStream> mapRelay;
  52. deque<pair<int64, CInv> > vRelayExpiration;
  53. CCriticalSection cs_mapRelay;
  54. map<CInv, int64> mapAlreadyAskedFor;
  55. static deque<string> vOneShots;
  56. CCriticalSection cs_vOneShots;
  57. set<CNetAddr> setservAddNodeAddresses;
  58. CCriticalSection cs_setservAddNodeAddresses;
  59. static CSemaphore *semOutbound = NULL;
  60. void AddOneShot(string strDest)
  61. {
  62. LOCK(cs_vOneShots);
  63. vOneShots.push_back(strDest);
  64. }
  65. unsigned short GetListenPort()
  66. {
  67. return (unsigned short)(GetArg("-port", GetDefaultPort()));
  68. }
  69. void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
  70. {
  71. // Filter out duplicate requests
  72. if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
  73. return;
  74. pindexLastGetBlocksBegin = pindexBegin;
  75. hashLastGetBlocksEnd = hashEnd;
  76. PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
  77. }
  78. bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
  79. {
  80. if (fNoListen)
  81. return false;
  82. int nBestScore = -1;
  83. int nBestReachability = -1;
  84. {
  85. LOCK(cs_mapLocalHost);
  86. for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
  87. {
  88. int nScore = (*it).second.nScore;
  89. int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
  90. if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
  91. {
  92. addr = CService((*it).first, (*it).second.nPort);
  93. nBestReachability = nReachability;
  94. nBestScore = nScore;
  95. }
  96. }
  97. }
  98. return nBestScore >= 0;
  99. }
  100. CAddress GetLocalAddress(const CNetAddr *paddrPeer)
  101. {
  102. CAddress ret(CService("0.0.0.0",0),0);
  103. CService addr;
  104. if (GetLocal(addr, paddrPeer))
  105. {
  106. ret = CAddress(addr);
  107. ret.nServices = nLocalServices;
  108. ret.nTime = GetAdjustedTime();
  109. }
  110. return ret;
  111. }
  112. bool RecvLine(SOCKET hSocket, string& strLine)
  113. {
  114. strLine = "";
  115. while (true)
  116. {
  117. char c;
  118. int nBytes = recv(hSocket, &c, 1, 0);
  119. if (nBytes > 0)
  120. {
  121. if (c == '\n')
  122. continue;
  123. if (c == '\r')
  124. return true;
  125. strLine += c;
  126. if (strLine.size() >= 9000)
  127. return true;
  128. }
  129. else if (nBytes <= 0)
  130. {
  131. if (fShutdown)
  132. return false;
  133. if (nBytes < 0)
  134. {
  135. int nErr = WSAGetLastError();
  136. if (nErr == WSAEMSGSIZE)
  137. continue;
  138. if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
  139. {
  140. Sleep(10);
  141. continue;
  142. }
  143. }
  144. if (!strLine.empty())
  145. return true;
  146. if (nBytes == 0)
  147. {
  148. // socket closed
  149. printf("socket closed\n");
  150. return false;
  151. }
  152. else
  153. {
  154. // socket error
  155. int nErr = WSAGetLastError();
  156. printf("recv failed: %d\n", nErr);
  157. return false;
  158. }
  159. }
  160. }
  161. }
  162. void static AdvertizeLocal()
  163. {
  164. LOCK(cs_vNodes);
  165. BOOST_FOREACH(CNode* pnode, vNodes)
  166. {
  167. if (pnode->fSuccessfullyConnected)
  168. {
  169. CAddress addrLocal = GetLocalAddress(&pnode->addr);
  170. if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
  171. {
  172. pnode->PushAddress(addrLocal);
  173. pnode->addrLocal = addrLocal;
  174. }
  175. }
  176. }
  177. }
  178. void SetReachable(enum Network net, bool fFlag)
  179. {
  180. LOCK(cs_mapLocalHost);
  181. vfReachable[net] = fFlag;
  182. if (net == NET_IPV6 && fFlag)
  183. vfReachable[NET_IPV4] = true;
  184. }
  185. bool AddLocal(const CService& addr, int nScore)
  186. {
  187. if (!addr.IsRoutable())
  188. return false;
  189. if (!fDiscover && nScore < LOCAL_MANUAL)
  190. return false;
  191. if (IsLimited(addr))
  192. return false;
  193. printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
  194. {
  195. LOCK(cs_mapLocalHost);
  196. bool fAlready = mapLocalHost.count(addr) > 0;
  197. LocalServiceInfo &info = mapLocalHost[addr];
  198. if (!fAlready || nScore >= info.nScore) {
  199. info.nScore = nScore + (fAlready ? 1 : 0);
  200. info.nPort = addr.GetPort();
  201. }
  202. SetReachable(addr.GetNetwork());
  203. }
  204. AdvertizeLocal();
  205. return true;
  206. }
  207. bool AddLocal(const CNetAddr &addr, int nScore)
  208. {
  209. return AddLocal(CService(addr, GetListenPort()), nScore);
  210. }
  211. void SetLimited(enum Network net, bool fLimited)
  212. {
  213. if (net == NET_UNROUTABLE)
  214. return;
  215. LOCK(cs_mapLocalHost);
  216. vfLimited[net] = fLimited;
  217. }
  218. bool IsLimited(enum Network net)
  219. {
  220. LOCK(cs_mapLocalHost);
  221. return vfLimited[net];
  222. }
  223. bool IsLimited(const CNetAddr &addr)
  224. {
  225. return IsLimited(addr.GetNetwork());
  226. }
  227. bool SeenLocal(const CService& addr)
  228. {
  229. {
  230. LOCK(cs_mapLocalHost);
  231. if (mapLocalHost.count(addr) == 0)
  232. return false;
  233. mapLocalHost[addr].nScore++;
  234. }
  235. AdvertizeLocal();
  236. return true;
  237. }
  238. bool IsLocal(const CService& addr)
  239. {
  240. LOCK(cs_mapLocalHost);
  241. return mapLocalHost.count(addr) > 0;
  242. }
  243. bool IsReachable(const CNetAddr& addr)
  244. {
  245. LOCK(cs_mapLocalHost);
  246. enum Network net = addr.GetNetwork();
  247. return vfReachable[net] && !vfLimited[net];
  248. }
  249. bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
  250. {
  251. SOCKET hSocket;
  252. if (!ConnectSocket(addrConnect, hSocket))
  253. return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
  254. send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
  255. string strLine;
  256. while (RecvLine(hSocket, strLine))
  257. {
  258. if (strLine.empty()) // HTTP response is separated from headers by blank line
  259. {
  260. while (true)
  261. {
  262. if (!RecvLine(hSocket, strLine))
  263. {
  264. closesocket(hSocket);
  265. return false;
  266. }
  267. if (pszKeyword == NULL)
  268. break;
  269. if (strLine.find(pszKeyword) != string::npos)
  270. {
  271. strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
  272. break;
  273. }
  274. }
  275. closesocket(hSocket);
  276. if (strLine.find("<") != string::npos)
  277. strLine = strLine.substr(0, strLine.find("<"));
  278. strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
  279. while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
  280. strLine.resize(strLine.size()-1);
  281. CService addr(strLine,0,true);
  282. printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
  283. if (!addr.IsValid() || !addr.IsRoutable())
  284. return false;
  285. ipRet.SetIP(addr);
  286. return true;
  287. }
  288. }
  289. closesocket(hSocket);
  290. return error("GetMyExternalIP() : connection closed");
  291. }
  292. bool GetMyExternalIP(CNetAddr& ipRet)
  293. {
  294. CService addrConnect;
  295. const char* pszGet;
  296. const char* pszKeyword;
  297. for (int nLookup = 0; nLookup <= 1; nLookup++)
  298. for (int nHost = 1; nHost <= 2; nHost++)
  299. {
  300. if (nHost == 1)
  301. {
  302. addrConnect = CService("131.186.113.70",80); // checkip.dyndns.org:80 (11/01/2021)
  303. if (nLookup == 1)
  304. {
  305. CService addrIP("checkip.dyndns.org", 80, true);
  306. if (addrIP.IsValid())
  307. addrConnect = addrIP;
  308. }
  309. pszGet = "GET / HTTP/1.1\r\n"
  310. "Host: checkip.dyndns.org\r\n"
  311. "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
  312. "Connection: close\r\n"
  313. "\r\n";
  314. pszKeyword = "Address:";
  315. }
  316. else if (nHost == 2)
  317. {
  318. addrConnect = CService("104.18.59.232", 443); // www.showmyip.com:443 (11/01/2021)
  319. if (nLookup == 1)
  320. {
  321. CService addrIP("www.showmyip.com", 443, true);
  322. if (addrIP.IsValid())
  323. addrConnect = addrIP;
  324. }
  325. pszGet = "GET /simple/ HTTP/1.1\r\n"
  326. "Host: www.showmyip.com\r\n"
  327. "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
  328. "Connection: close\r\n"
  329. "\r\n";
  330. pszKeyword = NULL; // Returns just IP address
  331. }
  332. if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
  333. return true;
  334. }
  335. return false;
  336. }
  337. void ThreadGetMyExternalIP(void* parg)
  338. {
  339. RenameThread("ecoin-ext-ip");
  340. CNetAddr addrLocalHost;
  341. if (GetMyExternalIP(addrLocalHost))
  342. {
  343. printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
  344. AddLocal(addrLocalHost, LOCAL_HTTP);
  345. }
  346. }
  347. void AddressCurrentlyConnected(const CService& addr)
  348. {
  349. addrman.Connected(addr);
  350. }
  351. CNode* FindNode(const CNetAddr& ip)
  352. {
  353. {
  354. LOCK(cs_vNodes);
  355. BOOST_FOREACH(CNode* pnode, vNodes)
  356. if ((CNetAddr)pnode->addr == ip)
  357. return (pnode);
  358. }
  359. return NULL;
  360. }
  361. CNode* FindNode(std::string addrName)
  362. {
  363. LOCK(cs_vNodes);
  364. BOOST_FOREACH(CNode* pnode, vNodes)
  365. if (pnode->addrName == addrName)
  366. return (pnode);
  367. return NULL;
  368. }
  369. CNode* FindNode(const CService& addr)
  370. {
  371. {
  372. LOCK(cs_vNodes);
  373. BOOST_FOREACH(CNode* pnode, vNodes)
  374. if ((CService)pnode->addr == addr)
  375. return (pnode);
  376. }
  377. return NULL;
  378. }
  379. CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
  380. {
  381. if (pszDest == NULL) {
  382. if (IsLocal(addrConnect))
  383. return NULL;
  384. CNode* pnode = FindNode((CService)addrConnect);
  385. if (pnode)
  386. {
  387. if (nTimeout != 0)
  388. pnode->AddRef(nTimeout);
  389. else
  390. pnode->AddRef();
  391. return pnode;
  392. }
  393. }
  394. printf("trying connection %s lastseen=%.1fhrs\n",
  395. pszDest ? pszDest : addrConnect.ToString().c_str(),
  396. pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
  397. SOCKET hSocket;
  398. if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
  399. {
  400. addrman.Attempt(addrConnect);
  401. printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
  402. #ifdef WIN32
  403. u_long nOne = 1;
  404. if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
  405. printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
  406. #else
  407. if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
  408. printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
  409. #endif
  410. CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
  411. if (nTimeout != 0)
  412. pnode->AddRef(nTimeout);
  413. else
  414. pnode->AddRef();
  415. {
  416. LOCK(cs_vNodes);
  417. vNodes.push_back(pnode);
  418. }
  419. pnode->nTimeConnected = GetTime();
  420. return pnode;
  421. }
  422. else
  423. {
  424. return NULL;
  425. }
  426. }
  427. void CNode::CloseSocketDisconnect()
  428. {
  429. fDisconnect = true;
  430. if (hSocket != INVALID_SOCKET)
  431. {
  432. printf("disconnecting node %s\n", addrName.c_str());
  433. closesocket(hSocket);
  434. hSocket = INVALID_SOCKET;
  435. vRecv.clear();
  436. }
  437. }
  438. void CNode::Cleanup()
  439. {
  440. }
  441. void CNode::PushVersion()
  442. {
  443. int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
  444. CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
  445. CAddress addrMe = GetLocalAddress(&addr);
  446. RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
  447. printf("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());
  448. PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
  449. nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
  450. }
  451. std::map<CNetAddr, int64> CNode::setBanned;
  452. CCriticalSection CNode::cs_setBanned;
  453. void CNode::ClearBanned()
  454. {
  455. setBanned.clear();
  456. }
  457. bool CNode::IsBanned(CNetAddr ip)
  458. {
  459. bool fResult = false;
  460. {
  461. LOCK(cs_setBanned);
  462. std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
  463. if (i != setBanned.end())
  464. {
  465. int64 t = (*i).second;
  466. if (GetTime() < t)
  467. fResult = true;
  468. }
  469. }
  470. return fResult;
  471. }
  472. bool CNode::Misbehaving(int howmuch)
  473. {
  474. if (addr.IsLocal())
  475. {
  476. printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
  477. return false;
  478. }
  479. nMisbehavior += howmuch;
  480. if (nMisbehavior >= GetArg("-banscore", 100))
  481. {
  482. int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
  483. printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
  484. {
  485. LOCK(cs_setBanned);
  486. if (setBanned[addr] < banTime)
  487. setBanned[addr] = banTime;
  488. }
  489. CloseSocketDisconnect();
  490. return true;
  491. } else
  492. printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
  493. return false;
  494. }
  495. #undef X
  496. #define X(name) stats.name = name
  497. void CNode::copyStats(CNodeStats &stats)
  498. {
  499. X(nServices);
  500. X(nLastSend);
  501. X(nLastRecv);
  502. X(nTimeConnected);
  503. X(addrName);
  504. X(nVersion);
  505. X(strSubVer);
  506. X(fInbound);
  507. X(nReleaseTime);
  508. X(nStartingHeight);
  509. X(nMisbehavior);
  510. }
  511. #undef X
  512. void ThreadSocketHandler(void* parg)
  513. {
  514. // Make this thread recognisable as the networking thread
  515. RenameThread("ecoin-net");
  516. try
  517. {
  518. vnThreadsRunning[THREAD_SOCKETHANDLER]++;
  519. ThreadSocketHandler2(parg);
  520. vnThreadsRunning[THREAD_SOCKETHANDLER]--;
  521. }
  522. catch (std::exception& e) {
  523. vnThreadsRunning[THREAD_SOCKETHANDLER]--;
  524. PrintException(&e, "ThreadSocketHandler()");
  525. } catch (...) {
  526. vnThreadsRunning[THREAD_SOCKETHANDLER]--;
  527. throw; // support pthread_cancel()
  528. }
  529. printf("ThreadSocketHandler exited\n");
  530. }
  531. void ThreadSocketHandler2(void* parg)
  532. {
  533. printf("ThreadSocketHandler started\n");
  534. list<CNode*> vNodesDisconnected;
  535. unsigned int nPrevNodeCount = 0;
  536. while (true)
  537. {
  538. {
  539. LOCK(cs_vNodes);
  540. vector<CNode*> vNodesCopy = vNodes;
  541. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  542. {
  543. if (pnode->fDisconnect ||
  544. (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
  545. {
  546. vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
  547. // release outbound grant (if any)
  548. pnode->grantOutbound.Release();
  549. // close socket and cleanup
  550. pnode->CloseSocketDisconnect();
  551. pnode->Cleanup();
  552. // hold in disconnected pool until all refs are released
  553. pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
  554. if (pnode->fNetworkNode || pnode->fInbound)
  555. pnode->Release();
  556. vNodesDisconnected.push_back(pnode);
  557. }
  558. }
  559. // Delete disconnected nodes
  560. list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
  561. BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
  562. {
  563. // wait until threads are done using it
  564. if (pnode->GetRefCount() <= 0)
  565. {
  566. bool fDelete = false;
  567. {
  568. TRY_LOCK(pnode->cs_vSend, lockSend);
  569. if (lockSend)
  570. {
  571. TRY_LOCK(pnode->cs_vRecv, lockRecv);
  572. if (lockRecv)
  573. {
  574. TRY_LOCK(pnode->cs_mapRequests, lockReq);
  575. if (lockReq)
  576. {
  577. TRY_LOCK(pnode->cs_inventory, lockInv);
  578. if (lockInv)
  579. fDelete = true;
  580. }
  581. }
  582. }
  583. }
  584. if (fDelete)
  585. {
  586. vNodesDisconnected.remove(pnode);
  587. delete pnode;
  588. }
  589. }
  590. }
  591. }
  592. if (vNodes.size() != nPrevNodeCount)
  593. {
  594. nPrevNodeCount = vNodes.size();
  595. uiInterface.NotifyNumConnectionsChanged(vNodes.size());
  596. }
  597. // Find which sockets have data to receive
  598. struct timeval timeout;
  599. timeout.tv_sec = 0;
  600. timeout.tv_usec = 50000; // frequency to poll pnode->vSend
  601. fd_set fdsetRecv;
  602. fd_set fdsetSend;
  603. fd_set fdsetError;
  604. FD_ZERO(&fdsetRecv);
  605. FD_ZERO(&fdsetSend);
  606. FD_ZERO(&fdsetError);
  607. SOCKET hSocketMax = 0;
  608. bool have_fds = false;
  609. BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
  610. FD_SET(hListenSocket, &fdsetRecv);
  611. hSocketMax = max(hSocketMax, hListenSocket);
  612. have_fds = true;
  613. }
  614. {
  615. LOCK(cs_vNodes);
  616. BOOST_FOREACH(CNode* pnode, vNodes)
  617. {
  618. if (pnode->hSocket == INVALID_SOCKET)
  619. continue;
  620. FD_SET(pnode->hSocket, &fdsetRecv);
  621. FD_SET(pnode->hSocket, &fdsetError);
  622. hSocketMax = max(hSocketMax, pnode->hSocket);
  623. have_fds = true;
  624. {
  625. TRY_LOCK(pnode->cs_vSend, lockSend);
  626. if (lockSend && !pnode->vSend.empty())
  627. FD_SET(pnode->hSocket, &fdsetSend);
  628. }
  629. }
  630. }
  631. vnThreadsRunning[THREAD_SOCKETHANDLER]--;
  632. int nSelect = select(have_fds ? hSocketMax + 1 : 0,
  633. &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
  634. vnThreadsRunning[THREAD_SOCKETHANDLER]++;
  635. if (fShutdown)
  636. return;
  637. if (nSelect == SOCKET_ERROR)
  638. {
  639. if (have_fds)
  640. {
  641. int nErr = WSAGetLastError();
  642. printf("socket select error %d\n", nErr);
  643. for (unsigned int i = 0; i <= hSocketMax; i++)
  644. FD_SET(i, &fdsetRecv);
  645. }
  646. FD_ZERO(&fdsetSend);
  647. FD_ZERO(&fdsetError);
  648. Sleep(timeout.tv_usec/1000);
  649. }
  650. // Accept new connections
  651. BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
  652. if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
  653. {
  654. #ifdef USE_IPV6
  655. struct sockaddr_storage sockaddr;
  656. #else
  657. struct sockaddr sockaddr;
  658. #endif
  659. socklen_t len = sizeof(sockaddr);
  660. SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
  661. CAddress addr;
  662. int nInbound = 0;
  663. if (hSocket != INVALID_SOCKET)
  664. if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
  665. printf("Warning: Unknown socket family\n");
  666. {
  667. LOCK(cs_vNodes);
  668. BOOST_FOREACH(CNode* pnode, vNodes)
  669. if (pnode->fInbound)
  670. nInbound++;
  671. }
  672. if (hSocket == INVALID_SOCKET)
  673. {
  674. int nErr = WSAGetLastError();
  675. if (nErr != WSAEWOULDBLOCK)
  676. printf("socket error accept failed: %d\n", nErr);
  677. }
  678. else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
  679. {
  680. {
  681. LOCK(cs_setservAddNodeAddresses);
  682. if (!setservAddNodeAddresses.count(addr))
  683. closesocket(hSocket);
  684. }
  685. }
  686. else if (CNode::IsBanned(addr))
  687. {
  688. printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
  689. closesocket(hSocket);
  690. }
  691. else
  692. {
  693. printf("accepted connection %s\n", addr.ToString().c_str());
  694. CNode* pnode = new CNode(hSocket, addr, "", true);
  695. pnode->AddRef();
  696. {
  697. LOCK(cs_vNodes);
  698. vNodes.push_back(pnode);
  699. }
  700. }
  701. }
  702. // Service each socket
  703. vector<CNode*> vNodesCopy;
  704. {
  705. LOCK(cs_vNodes);
  706. vNodesCopy = vNodes;
  707. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  708. pnode->AddRef();
  709. }
  710. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  711. {
  712. if (fShutdown)
  713. return;
  714. // Receive
  715. if (pnode->hSocket == INVALID_SOCKET)
  716. continue;
  717. if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
  718. {
  719. TRY_LOCK(pnode->cs_vRecv, lockRecv);
  720. if (lockRecv)
  721. {
  722. CDataStream& vRecv = pnode->vRecv;
  723. unsigned int nPos = vRecv.size();
  724. if (nPos > ReceiveBufferSize()) {
  725. if (!pnode->fDisconnect)
  726. printf("socket recv flood control disconnect (%" PRIszu" bytes)\n", vRecv.size());
  727. pnode->CloseSocketDisconnect();
  728. }
  729. else {
  730. // typical socket buffer is 8K-64K
  731. char pchBuf[0x10000];
  732. int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
  733. if (nBytes > 0)
  734. {
  735. vRecv.resize(nPos + nBytes);
  736. memcpy(&vRecv[nPos], pchBuf, nBytes);
  737. pnode->nLastRecv = GetTime();
  738. }
  739. else if (nBytes == 0)
  740. {
  741. // socket closed gracefully
  742. if (!pnode->fDisconnect)
  743. printf("socket closed\n");
  744. pnode->CloseSocketDisconnect();
  745. }
  746. else if (nBytes < 0)
  747. {
  748. // error
  749. int nErr = WSAGetLastError();
  750. if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
  751. {
  752. if (!pnode->fDisconnect)
  753. printf("socket recv error %d\n", nErr);
  754. pnode->CloseSocketDisconnect();
  755. }
  756. }
  757. }
  758. }
  759. }
  760. // Send
  761. if (pnode->hSocket == INVALID_SOCKET)
  762. continue;
  763. if (FD_ISSET(pnode->hSocket, &fdsetSend))
  764. {
  765. TRY_LOCK(pnode->cs_vSend, lockSend);
  766. if (lockSend)
  767. {
  768. CDataStream& vSend = pnode->vSend;
  769. if (!vSend.empty())
  770. {
  771. int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
  772. if (nBytes > 0)
  773. {
  774. vSend.erase(vSend.begin(), vSend.begin() + nBytes);
  775. pnode->nLastSend = GetTime();
  776. }
  777. else if (nBytes < 0)
  778. {
  779. // error
  780. int nErr = WSAGetLastError();
  781. if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
  782. {
  783. printf("socket send error %d\n", nErr);
  784. pnode->CloseSocketDisconnect();
  785. }
  786. }
  787. }
  788. }
  789. }
  790. // Inactivity checking
  791. if (pnode->vSend.empty())
  792. pnode->nLastSendEmpty = GetTime();
  793. if (GetTime() - pnode->nTimeConnected > 60)
  794. {
  795. if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
  796. {
  797. printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
  798. pnode->fDisconnect = true;
  799. }
  800. else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
  801. {
  802. printf("socket not sending\n");
  803. pnode->fDisconnect = true;
  804. }
  805. else if (GetTime() - pnode->nLastRecv > 90*60)
  806. {
  807. printf("socket inactivity timeout\n");
  808. pnode->fDisconnect = true;
  809. }
  810. }
  811. }
  812. {
  813. LOCK(cs_vNodes);
  814. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  815. pnode->Release();
  816. }
  817. Sleep(10);
  818. }
  819. }
  820. #ifdef USE_UPNP
  821. void ThreadMapPort(void* parg)
  822. {
  823. // Make this thread recognisable as the UPnP thread
  824. RenameThread("ecoin-UPnP");
  825. try
  826. {
  827. vnThreadsRunning[THREAD_UPNP]++;
  828. ThreadMapPort2(parg);
  829. vnThreadsRunning[THREAD_UPNP]--;
  830. }
  831. catch (std::exception& e) {
  832. vnThreadsRunning[THREAD_UPNP]--;
  833. PrintException(&e, "ThreadMapPort()");
  834. } catch (...) {
  835. vnThreadsRunning[THREAD_UPNP]--;
  836. PrintException(NULL, "ThreadMapPort()");
  837. }
  838. printf("ThreadMapPort exited\n");
  839. }
  840. void ThreadMapPort2(void* parg)
  841. {
  842. printf("ThreadMapPort started\n");
  843. std::string port = strprintf("%u", GetListenPort());
  844. const char * multicastif = 0;
  845. const char * minissdpdpath = 0;
  846. struct UPNPDev * devlist = 0;
  847. char lanaddr[64];
  848. #ifndef UPNPDISCOVER_SUCCESS
  849. // /* miniupnpc 1.5 */
  850. devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
  851. #else
  852. // /* miniupnpc 1.9.20150730 */
  853. int error = 0;
  854. devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
  855. #endif
  856. struct UPNPUrls urls;
  857. struct IGDdatas data;
  858. int r;
  859. r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
  860. if (r == 1)
  861. {
  862. if (fDiscover) {
  863. char externalIPAddress[40];
  864. r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
  865. if(r != UPNPCOMMAND_SUCCESS)
  866. printf("UPnP: GetExternalIPAddress() returned %d\n", r);
  867. else
  868. {
  869. if(externalIPAddress[0])
  870. {
  871. printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
  872. AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
  873. }
  874. else
  875. printf("UPnP: GetExternalIPAddress failed.\n");
  876. }
  877. }
  878. string strDesc = "Ecoin " + FormatFullVersion();
  879. #ifndef UPNPDISCOVER_SUCCESS
  880. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  881. port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
  882. #else
  883. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  884. port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
  885. #endif
  886. if(r!=UPNPCOMMAND_SUCCESS)
  887. printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
  888. port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
  889. else
  890. printf("UPnP Port Mapping successful.\n");
  891. int i = 1;
  892. while (true)
  893. {
  894. if (fShutdown || !fUseUPnP)
  895. {
  896. r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
  897. printf("UPNP_DeletePortMapping() returned : %d\n", r);
  898. freeUPNPDevlist(devlist); devlist = 0;
  899. FreeUPNPUrls(&urls);
  900. return;
  901. }
  902. if (i % 600 == 0) // Refresh every 20 minutes
  903. {
  904. #ifndef UPNPDISCOVER_SUCCESS
  905. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  906. port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
  907. #else
  908. r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
  909. port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
  910. #endif
  911. if(r!=UPNPCOMMAND_SUCCESS)
  912. printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
  913. port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
  914. else
  915. printf("UPnP Port Mapping successful.\n");;
  916. }
  917. Sleep(2000);
  918. i++;
  919. }
  920. } else {
  921. printf("No valid UPnP IGDs found\n");
  922. freeUPNPDevlist(devlist); devlist = 0;
  923. if (r != 0)
  924. FreeUPNPUrls(&urls);
  925. while (true)
  926. {
  927. if (fShutdown || !fUseUPnP)
  928. return;
  929. Sleep(2000);
  930. }
  931. }
  932. }
  933. void MapPort()
  934. {
  935. if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
  936. {
  937. if (!NewThread(ThreadMapPort, NULL))
  938. printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
  939. }
  940. }
  941. #else
  942. void MapPort()
  943. {
  944. // Intentionally left blank.
  945. }
  946. #endif
  947. // DNS seeds
  948. static const char *strDNSSeed[][2] = {
  949. {"ecoinseed.03c8.net", "dnsecoin.03c8.net"},
  950. };
  951. void ThreadDNSAddressSeed(void* parg)
  952. {
  953. // Make this thread recognisable as the DNS seeding thread
  954. RenameThread("ecoin-dnsseed");
  955. try
  956. {
  957. vnThreadsRunning[THREAD_DNSSEED]++;
  958. ThreadDNSAddressSeed2(parg);
  959. vnThreadsRunning[THREAD_DNSSEED]--;
  960. }
  961. catch (std::exception& e) {
  962. vnThreadsRunning[THREAD_DNSSEED]--;
  963. PrintException(&e, "ThreadDNSAddressSeed()");
  964. } catch (...) {
  965. vnThreadsRunning[THREAD_DNSSEED]--;
  966. throw; // support pthread_cancel()
  967. }
  968. printf("ThreadDNSAddressSeed exited\n");
  969. }
  970. void ThreadDNSAddressSeed2(void* parg)
  971. {
  972. printf("ThreadDNSAddressSeed started\n");
  973. int found = 0;
  974. if (!fTestNet)
  975. {
  976. printf("Loading addresses from DNS seeds (could take a while)\n");
  977. for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
  978. if (HaveNameProxy()) {
  979. AddOneShot(strDNSSeed[seed_idx][1]);
  980. } else {
  981. vector<CNetAddr> vaddr;
  982. vector<CAddress> vAdd;
  983. if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
  984. {
  985. BOOST_FOREACH(CNetAddr& ip, vaddr)
  986. {
  987. int nOneDay = 24*3600;
  988. CAddress addr = CAddress(CService(ip, GetDefaultPort()));
  989. addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
  990. vAdd.push_back(addr);
  991. found++;
  992. }
  993. }
  994. addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
  995. }
  996. }
  997. }
  998. printf("%d addresses found from DNS seeds\n", found);
  999. }
  1000. unsigned int pnSeed[] =
  1001. {
  1002. 0x36CBF4AA, 0x36CBF41B,
  1003. };
  1004. void DumpAddresses()
  1005. {
  1006. int64 nStart = GetTimeMillis();
  1007. CAddrDB adb;
  1008. adb.Write(addrman);
  1009. printf("Flushed %d addresses to peers.dat %" PRI64d"ms\n",
  1010. addrman.size(), GetTimeMillis() - nStart);
  1011. }
  1012. void ThreadDumpAddress2(void* parg)
  1013. {
  1014. vnThreadsRunning[THREAD_DUMPADDRESS]++;
  1015. while (!fShutdown)
  1016. {
  1017. DumpAddresses();
  1018. vnThreadsRunning[THREAD_DUMPADDRESS]--;
  1019. Sleep(600000);
  1020. vnThreadsRunning[THREAD_DUMPADDRESS]++;
  1021. }
  1022. vnThreadsRunning[THREAD_DUMPADDRESS]--;
  1023. }
  1024. void ThreadDumpAddress(void* parg)
  1025. {
  1026. // Make this thread recognisable as the address dumping thread
  1027. RenameThread("ecoin-adrdump");
  1028. try
  1029. {
  1030. ThreadDumpAddress2(parg);
  1031. }
  1032. catch (std::exception& e) {
  1033. PrintException(&e, "ThreadDumpAddress()");
  1034. }
  1035. printf("ThreadDumpAddress exited\n");
  1036. }
  1037. void ThreadOpenConnections(void* parg)
  1038. {
  1039. // Make this thread recognisable as the connection opening thread
  1040. RenameThread("ecoin-opencon");
  1041. try
  1042. {
  1043. vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
  1044. ThreadOpenConnections2(parg);
  1045. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1046. }
  1047. catch (std::exception& e) {
  1048. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1049. PrintException(&e, "ThreadOpenConnections()");
  1050. } catch (...) {
  1051. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1052. PrintException(NULL, "ThreadOpenConnections()");
  1053. }
  1054. printf("ThreadOpenConnections exited\n");
  1055. }
  1056. void static ProcessOneShot()
  1057. {
  1058. string strDest;
  1059. {
  1060. LOCK(cs_vOneShots);
  1061. if (vOneShots.empty())
  1062. return;
  1063. strDest = vOneShots.front();
  1064. vOneShots.pop_front();
  1065. }
  1066. CAddress addr;
  1067. CSemaphoreGrant grant(*semOutbound, true);
  1068. if (grant) {
  1069. if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
  1070. AddOneShot(strDest);
  1071. }
  1072. }
  1073. void static ThreadStakeMinter(void* parg)
  1074. {
  1075. printf("ThreadStakeMinter started\n");
  1076. CWallet* pwallet = (CWallet*)parg;
  1077. try
  1078. {
  1079. vnThreadsRunning[THREAD_MINTER]++;
  1080. StakeMiner(pwallet);
  1081. vnThreadsRunning[THREAD_MINTER]--;
  1082. }
  1083. catch (std::exception& e) {
  1084. vnThreadsRunning[THREAD_MINTER]--;
  1085. PrintException(&e, "ThreadStakeMinter()");
  1086. } catch (...) {
  1087. vnThreadsRunning[THREAD_MINTER]--;
  1088. PrintException(NULL, "ThreadStakeMinter()");
  1089. }
  1090. printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);
  1091. }
  1092. void ThreadOpenConnections2(void* parg)
  1093. {
  1094. printf("ThreadOpenConnections started\n");
  1095. // Connect to specific addresses
  1096. if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
  1097. {
  1098. for (int64 nLoop = 0;; nLoop++)
  1099. {
  1100. ProcessOneShot();
  1101. BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
  1102. {
  1103. CAddress addr;
  1104. OpenNetworkConnection(addr, NULL, strAddr.c_str());
  1105. for (int i = 0; i < 10 && i < nLoop; i++)
  1106. {
  1107. Sleep(500);
  1108. if (fShutdown)
  1109. return;
  1110. }
  1111. }
  1112. Sleep(500);
  1113. }
  1114. }
  1115. // Initiate network connections
  1116. int64 nStart = GetTime();
  1117. while (true)
  1118. {
  1119. ProcessOneShot();
  1120. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1121. Sleep(500);
  1122. vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
  1123. if (fShutdown)
  1124. return;
  1125. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1126. CSemaphoreGrant grant(*semOutbound);
  1127. vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
  1128. if (fShutdown)
  1129. return;
  1130. // Add seed nodes if IRC isn't working
  1131. if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
  1132. {
  1133. std::vector<CAddress> vAdd;
  1134. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
  1135. {
  1136. const int64 nOneWeek = 7*24*60*60;
  1137. struct in_addr ip;
  1138. memcpy(&ip, &pnSeed[i], sizeof(ip));
  1139. CAddress addr(CService(ip, GetDefaultPort()));
  1140. addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
  1141. vAdd.push_back(addr);
  1142. }
  1143. addrman.Add(vAdd, CNetAddr("127.0.0.1"));
  1144. }
  1145. CAddress addrConnect;
  1146. int nOutbound = 0;
  1147. set<vector<unsigned char> > setConnected;
  1148. {
  1149. LOCK(cs_vNodes);
  1150. BOOST_FOREACH(CNode* pnode, vNodes) {
  1151. if (!pnode->fInbound) {
  1152. setConnected.insert(pnode->addr.GetGroup());
  1153. nOutbound++;
  1154. }
  1155. }
  1156. }
  1157. int64 nANow = GetAdjustedTime();
  1158. int nTries = 0;
  1159. while (true)
  1160. {
  1161. // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
  1162. CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
  1163. // if we selected an invalid address, restart
  1164. if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
  1165. break;
  1166. nTries++;
  1167. if (nTries > 100)
  1168. break;
  1169. if (IsLimited(addr))
  1170. continue;
  1171. if (nANow - addr.nLastTry < 600 && nTries < 30)
  1172. continue;
  1173. if (addr.GetPort() != GetDefaultPort() && nTries < 50)
  1174. continue;
  1175. addrConnect = addr;
  1176. break;
  1177. }
  1178. if (addrConnect.IsValid())
  1179. OpenNetworkConnection(addrConnect, &grant);
  1180. }
  1181. }
  1182. void ThreadOpenAddedConnections(void* parg)
  1183. {
  1184. RenameThread("ecoin-opencon");
  1185. try
  1186. {
  1187. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
  1188. ThreadOpenAddedConnections2(parg);
  1189. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1190. }
  1191. catch (std::exception& e) {
  1192. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1193. PrintException(&e, "ThreadOpenAddedConnections()");
  1194. } catch (...) {
  1195. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1196. PrintException(NULL, "ThreadOpenAddedConnections()");
  1197. }
  1198. printf("ThreadOpenAddedConnections exited\n");
  1199. }
  1200. void ThreadOpenAddedConnections2(void* parg)
  1201. {
  1202. printf("ThreadOpenAddedConnections started\n");
  1203. if (mapArgs.count("-addnode") == 0)
  1204. return;
  1205. if (HaveNameProxy()) {
  1206. while(!fShutdown) {
  1207. BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
  1208. CAddress addr;
  1209. CSemaphoreGrant grant(*semOutbound);
  1210. OpenNetworkConnection(addr, &grant, strAddNode.c_str());
  1211. Sleep(500);
  1212. }
  1213. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1214. Sleep(120000); // Retry every 2 minutes
  1215. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
  1216. }
  1217. return;
  1218. }
  1219. vector<vector<CService> > vservAddressesToAdd(0);
  1220. BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
  1221. {
  1222. vector<CService> vservNode(0);
  1223. if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
  1224. {
  1225. vservAddressesToAdd.push_back(vservNode);
  1226. {
  1227. LOCK(cs_setservAddNodeAddresses);
  1228. BOOST_FOREACH(CService& serv, vservNode)
  1229. setservAddNodeAddresses.insert(serv);
  1230. }
  1231. }
  1232. }
  1233. while (true)
  1234. {
  1235. vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
  1236. {
  1237. LOCK(cs_vNodes);
  1238. BOOST_FOREACH(CNode* pnode, vNodes)
  1239. for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
  1240. BOOST_FOREACH(CService& addrNode, *(it))
  1241. if (pnode->addr == addrNode)
  1242. {
  1243. it = vservConnectAddresses.erase(it);
  1244. it--;
  1245. break;
  1246. }
  1247. }
  1248. BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
  1249. {
  1250. CSemaphoreGrant grant(*semOutbound);
  1251. OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
  1252. Sleep(500);
  1253. if (fShutdown)
  1254. return;
  1255. }
  1256. if (fShutdown)
  1257. return;
  1258. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
  1259. Sleep(120000); // Retry every 2 minutes
  1260. vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
  1261. if (fShutdown)
  1262. return;
  1263. }
  1264. }
  1265. bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
  1266. {
  1267. // Initiate outbound network connection
  1268. if (fShutdown)
  1269. return false;
  1270. if (!strDest)
  1271. if (IsLocal(addrConnect) ||
  1272. FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
  1273. FindNode(addrConnect.ToStringIPPort().c_str()))
  1274. return false;
  1275. if (strDest && FindNode(strDest))
  1276. return false;
  1277. vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
  1278. CNode* pnode = ConnectNode(addrConnect, strDest);
  1279. vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
  1280. if (fShutdown)
  1281. return false;
  1282. if (!pnode)
  1283. return false;
  1284. if (grantOutbound)
  1285. grantOutbound->MoveTo(pnode->grantOutbound);
  1286. pnode->fNetworkNode = true;
  1287. if (fOneShot)
  1288. pnode->fOneShot = true;
  1289. return true;
  1290. }
  1291. void ThreadMessageHandler(void* parg)
  1292. {
  1293. // Make this thread recognisable as the message handling thread
  1294. RenameThread("ecoin-msghand");
  1295. try
  1296. {
  1297. vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
  1298. ThreadMessageHandler2(parg);
  1299. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1300. }
  1301. catch (std::exception& e) {
  1302. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1303. PrintException(&e, "ThreadMessageHandler()");
  1304. } catch (...) {
  1305. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1306. PrintException(NULL, "ThreadMessageHandler()");
  1307. }
  1308. printf("ThreadMessageHandler exited\n");
  1309. }
  1310. void ThreadMessageHandler2(void* parg)
  1311. {
  1312. printf("ThreadMessageHandler started\n");
  1313. SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
  1314. while (!fShutdown)
  1315. {
  1316. vector<CNode*> vNodesCopy;
  1317. {
  1318. LOCK(cs_vNodes);
  1319. vNodesCopy = vNodes;
  1320. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1321. pnode->AddRef();
  1322. }
  1323. // Poll the connected nodes for messages
  1324. CNode* pnodeTrickle = NULL;
  1325. if (!vNodesCopy.empty())
  1326. pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
  1327. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1328. {
  1329. // Receive messages
  1330. {
  1331. TRY_LOCK(pnode->cs_vRecv, lockRecv);
  1332. if (lockRecv)
  1333. ProcessMessages(pnode);
  1334. }
  1335. if (fShutdown)
  1336. return;
  1337. // Send messages
  1338. {
  1339. TRY_LOCK(pnode->cs_vSend, lockSend);
  1340. if (lockSend)
  1341. SendMessages(pnode, pnode == pnodeTrickle);
  1342. }
  1343. if (fShutdown)
  1344. return;
  1345. }
  1346. {
  1347. LOCK(cs_vNodes);
  1348. BOOST_FOREACH(CNode* pnode, vNodesCopy)
  1349. pnode->Release();
  1350. }
  1351. vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
  1352. Sleep(100);
  1353. if (fRequestShutdown)
  1354. StartShutdown();
  1355. vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
  1356. if (fShutdown)
  1357. return;
  1358. }
  1359. }
  1360. bool BindListenPort(const CService &addrBind, string& strError)
  1361. {
  1362. strError = "";
  1363. int nOne = 1;
  1364. #ifdef WIN32
  1365. // Initialize Windows Sockets
  1366. WSADATA wsadata;
  1367. int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
  1368. if (ret != NO_ERROR)
  1369. {
  1370. strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
  1371. printf("%s\n", strError.c_str());
  1372. return false;
  1373. }
  1374. #endif
  1375. // Create socket for listening for incoming connections
  1376. #ifdef USE_IPV6
  1377. struct sockaddr_storage sockaddr;
  1378. #else
  1379. struct sockaddr sockaddr;
  1380. #endif
  1381. socklen_t len = sizeof(sockaddr);
  1382. if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
  1383. {
  1384. strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
  1385. printf("%s\n", strError.c_str());
  1386. return false;
  1387. }
  1388. SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
  1389. if (hListenSocket == INVALID_SOCKET)
  1390. {
  1391. strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
  1392. printf("%s\n", strError.c_str());
  1393. return false;
  1394. }
  1395. #ifdef SO_NOSIGPIPE
  1396. // Different way of disabling SIGPIPE on BSD
  1397. setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
  1398. #endif
  1399. #ifndef WIN32
  1400. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
  1401. #endif
  1402. #ifdef WIN32
  1403. // Set to non-blocking, incoming connections will also inherit this
  1404. if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
  1405. #else
  1406. if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
  1407. #endif
  1408. {
  1409. strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
  1410. printf("%s\n", strError.c_str());
  1411. return false;
  1412. }
  1413. #ifdef USE_IPV6
  1414. if (addrBind.IsIPv6()) {
  1415. #ifdef IPV6_V6ONLY
  1416. #ifdef WIN32
  1417. setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
  1418. #else
  1419. setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
  1420. #endif
  1421. #endif
  1422. #ifdef WIN32
  1423. int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
  1424. int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
  1425. // this call is allowed to fail
  1426. setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
  1427. #endif
  1428. }
  1429. #endif
  1430. if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
  1431. {
  1432. int nErr = WSAGetLastError();
  1433. if (nErr == WSAEADDRINUSE)
  1434. strError = strprintf(_("Unable to bind to %s on this computer. Ecoin is probably already running."), addrBind.ToString().c_str());
  1435. else
  1436. strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
  1437. printf("%s\n", strError.c_str());
  1438. return false;
  1439. }
  1440. printf("Bound to %s\n", addrBind.ToString().c_str());
  1441. // Listen for incoming connections
  1442. if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
  1443. {
  1444. strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
  1445. printf("%s\n", strError.c_str());
  1446. return false;
  1447. }
  1448. vhListenSocket.push_back(hListenSocket);
  1449. if (addrBind.IsRoutable() && fDiscover)
  1450. AddLocal(addrBind, LOCAL_BIND);
  1451. return true;
  1452. }
  1453. void static Discover()
  1454. {
  1455. if (!fDiscover)
  1456. return;
  1457. #ifdef WIN32
  1458. // Get local host IP
  1459. char pszHostName[1000] = "";
  1460. if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
  1461. {
  1462. vector<CNetAddr> vaddr;
  1463. if (LookupHost(pszHostName, vaddr))
  1464. {
  1465. BOOST_FOREACH (const CNetAddr &addr, vaddr)
  1466. {
  1467. AddLocal(addr, LOCAL_IF);
  1468. }
  1469. }
  1470. }
  1471. #else
  1472. // Get local host ip
  1473. struct ifaddrs* myaddrs;
  1474. if (getifaddrs(&myaddrs) == 0)
  1475. {
  1476. for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
  1477. {
  1478. if (ifa->ifa_addr == NULL) continue;
  1479. if ((ifa->ifa_flags & IFF_UP) == 0) continue;
  1480. if (strcmp(ifa->ifa_name, "lo") == 0) continue;
  1481. if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
  1482. if (ifa->ifa_addr->sa_family == AF_INET)
  1483. {
  1484. struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
  1485. CNetAddr addr(s4->sin_addr);
  1486. if (AddLocal(addr, LOCAL_IF))
  1487. printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
  1488. }
  1489. #ifdef USE_IPV6
  1490. else if (ifa->ifa_addr->sa_family == AF_INET6)
  1491. {
  1492. struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
  1493. CNetAddr addr(s6->sin6_addr);
  1494. if (AddLocal(addr, LOCAL_IF))
  1495. printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
  1496. }
  1497. #endif
  1498. }
  1499. freeifaddrs(myaddrs);
  1500. }
  1501. #endif
  1502. // Don't use external IPv4 discovery, when -onlynet="IPv6"
  1503. if (!IsLimited(NET_IPV4))
  1504. NewThread(ThreadGetMyExternalIP, NULL);
  1505. }
  1506. void StartNode(void* parg)
  1507. {
  1508. // Make this thread recognisable as the startup thread
  1509. RenameThread("ecoin-start");
  1510. if (semOutbound == NULL) {
  1511. // initialize semaphore
  1512. int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
  1513. semOutbound = new CSemaphore(nMaxOutbound);
  1514. }
  1515. if (pnodeLocalHost == NULL)
  1516. pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
  1517. Discover();
  1518. // Start threads
  1519. if (!GetBoolArg("-dnsseed", true))
  1520. printf("DNS seeding disabled\n");
  1521. else
  1522. if (!NewThread(ThreadDNSAddressSeed, NULL))
  1523. printf("Error: NewThread(ThreadDNSAddressSeed) failed\n");
  1524. // Map ports with UPnP
  1525. if (fUseUPnP)
  1526. MapPort();
  1527. // Get addresses from IRC and advertise ours
  1528. if (!NewThread(ThreadIRCSeed, NULL))
  1529. printf("Error: NewThread(ThreadIRCSeed) failed\n");
  1530. // Send and receive from sockets, accept connections
  1531. if (!NewThread(ThreadSocketHandler, NULL))
  1532. printf("Error: NewThread(ThreadSocketHandler) failed\n");
  1533. // Initiate outbound connections from -addnode
  1534. if (!NewThread(ThreadOpenAddedConnections, NULL))
  1535. printf("Error: NewThread(ThreadOpenAddedConnections) failed\n");
  1536. // Initiate outbound connections
  1537. if (!NewThread(ThreadOpenConnections, NULL))
  1538. printf("Error: NewThread(ThreadOpenConnections) failed\n");
  1539. // Process messages
  1540. if (!NewThread(ThreadMessageHandler, NULL))
  1541. printf("Error: NewThread(ThreadMessageHandler) failed\n");
  1542. // Dump network addresses
  1543. if (!NewThread(ThreadDumpAddress, NULL))
  1544. printf("Error; NewThread(ThreadDumpAddress) failed\n");
  1545. // ecoin: mint proof-of-stake blocks in the background
  1546. if (!GetBoolArg("-staking", true))
  1547. printf("Staking disabled\n");
  1548. else
  1549. if (!NewThread(ThreadStakeMinter, pwalletMain))
  1550. printf("Error: NewThread(ThreadStakeMinter) failed\n");
  1551. }
  1552. bool StopNode()
  1553. {
  1554. printf("StopNode()\n");
  1555. fShutdown = true;
  1556. nTransactionsUpdated++;
  1557. int64 nStart = GetTime();
  1558. if (semOutbound)
  1559. for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
  1560. semOutbound->post();
  1561. do
  1562. {
  1563. int nThreadsRunning = 0;
  1564. for (int n = 0; n < THREAD_MAX; n++)
  1565. nThreadsRunning += vnThreadsRunning[n];
  1566. if (nThreadsRunning == 0)
  1567. break;
  1568. if (GetTime() - nStart > 20)
  1569. break;
  1570. Sleep(20);
  1571. } while(true);
  1572. if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
  1573. if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
  1574. if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
  1575. if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
  1576. if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
  1577. #ifdef USE_UPNP
  1578. if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
  1579. #endif
  1580. if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
  1581. if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
  1582. if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
  1583. if (vnThreadsRunning[THREAD_MINTER] > 0) printf("ThreadStakeMinter still running\n");
  1584. while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
  1585. Sleep(20);
  1586. Sleep(50);
  1587. DumpAddresses();
  1588. return true;
  1589. }
  1590. class CNetCleanup
  1591. {
  1592. public:
  1593. CNetCleanup()
  1594. {
  1595. }
  1596. ~CNetCleanup()
  1597. {
  1598. // Close sockets
  1599. BOOST_FOREACH(CNode* pnode, vNodes)
  1600. if (pnode->hSocket != INVALID_SOCKET)
  1601. closesocket(pnode->hSocket);
  1602. BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
  1603. if (hListenSocket != INVALID_SOCKET)
  1604. if (closesocket(hListenSocket) == SOCKET_ERROR)
  1605. printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
  1606. #ifdef WIN32
  1607. // Shutdown Windows Sockets
  1608. WSACleanup();
  1609. #endif
  1610. }
  1611. }
  1612. instance_of_cnetcleanup;
  1613. void RelayTransaction(const CTransaction& tx, const uint256& hash)
  1614. {
  1615. CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
  1616. ss.reserve(10000);
  1617. ss << tx;
  1618. RelayTransaction(tx, hash, ss);
  1619. }
  1620. void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
  1621. {
  1622. CInv inv(MSG_TX, hash);
  1623. {
  1624. LOCK(cs_mapRelay);
  1625. // Expire old relay messages
  1626. while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
  1627. {
  1628. mapRelay.erase(vRelayExpiration.front().second);
  1629. vRelayExpiration.pop_front();
  1630. }
  1631. // Save original serialized message so newer versions are preserved
  1632. mapRelay.insert(std::make_pair(inv, ss));
  1633. vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
  1634. }
  1635. RelayInventory(inv);
  1636. }