You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

net_processing.cpp 146KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 The Bitcoin Core developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "net_processing.h"
  6. #include "addrman.h"
  7. #include "arith_uint256.h"
  8. #include "blockencodings.h"
  9. #include "chainparams.h"
  10. #include "consensus/validation.h"
  11. #include "hash.h"
  12. #include "init.h"
  13. #include "validation.h"
  14. #include "merkleblock.h"
  15. #include "net.h"
  16. #include "netmessagemaker.h"
  17. #include "netbase.h"
  18. #include "policy/fees.h"
  19. #include "policy/policy.h"
  20. #include "primitives/block.h"
  21. #include "primitives/transaction.h"
  22. #include "random.h"
  23. #include "tinyformat.h"
  24. #include "txmempool.h"
  25. #include "ui_interface.h"
  26. #include "util.h"
  27. #include "utilmoneystr.h"
  28. #include "utilstrencodings.h"
  29. #include "validationinterface.h"
  30. #include <boost/thread.hpp>
  31. #if defined(NDEBUG)
  32. # error "Bitcoin cannot be compiled without assertions."
  33. #endif
  34. std::atomic<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block
  35. struct IteratorComparator
  36. {
  37. template<typename I>
  38. bool operator()(const I& a, const I& b)
  39. {
  40. return &(*a) < &(*b);
  41. }
  42. };
  43. struct COrphanTx {
  44. // When modifying, adapt the copy of this definition in tests/DoS_tests.
  45. CTransactionRef tx;
  46. NodeId fromPeer;
  47. int64_t nTimeExpire;
  48. };
  49. std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_main);
  50. std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(cs_main);
  51. void EraseOrphansFor(NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
  52. static size_t vExtraTxnForCompactIt = 0;
  53. static std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(cs_main);
  54. static const uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; // SHA256("main address relay")[0:8]
  55. // Internal stuff
  56. namespace {
  57. /** Number of nodes with fSyncStarted. */
  58. int nSyncStarted = 0;
  59. /**
  60. * Sources of received blocks, saved to be able to send them reject
  61. * messages or ban them when processing happens afterwards. Protected by
  62. * cs_main.
  63. * Set mapBlockSource[hash].second to false if the node should not be
  64. * punished if the block is invalid.
  65. */
  66. std::map<uint256, std::pair<NodeId, bool>> mapBlockSource;
  67. /**
  68. * Filter for transactions that were recently rejected by
  69. * AcceptToMemoryPool. These are not rerequested until the chain tip
  70. * changes, at which point the entire filter is reset. Protected by
  71. * cs_main.
  72. *
  73. * Without this filter we'd be re-requesting txs from each of our peers,
  74. * increasing bandwidth consumption considerably. For instance, with 100
  75. * peers, half of which relay a tx we don't accept, that might be a 50x
  76. * bandwidth increase. A flooding attacker attempting to roll-over the
  77. * filter using minimum-sized, 60byte, transactions might manage to send
  78. * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a
  79. * two minute window to send invs to us.
  80. *
  81. * Decreasing the false positive rate is fairly cheap, so we pick one in a
  82. * million to make it highly unlikely for users to have issues with this
  83. * filter.
  84. *
  85. * Memory used: 1.3 MB
  86. */
  87. std::unique_ptr<CRollingBloomFilter> recentRejects;
  88. uint256 hashRecentRejectsChainTip;
  89. /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
  90. struct QueuedBlock {
  91. uint256 hash;
  92. const CBlockIndex* pindex; //!< Optional.
  93. bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request.
  94. std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads
  95. };
  96. std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight;
  97. /** Stack of nodes which we have set to announce using compact blocks */
  98. std::list<NodeId> lNodesAnnouncingHeaderAndIDs;
  99. /** Number of preferable block download peers. */
  100. int nPreferredDownload = 0;
  101. /** Number of peers from which we're downloading blocks. */
  102. int nPeersWithValidatedDownloads = 0;
  103. /** Relay map, protected by cs_main. */
  104. typedef std::map<uint256, CTransactionRef> MapRelay;
  105. MapRelay mapRelay;
  106. /** Expiration-time ordered list of (expire time, relay map entry) pairs, protected by cs_main). */
  107. std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration;
  108. } // anon namespace
  109. //////////////////////////////////////////////////////////////////////////////
  110. //
  111. // Registration of network node signals.
  112. //
  113. namespace {
  114. struct CBlockReject {
  115. unsigned char chRejectCode;
  116. std::string strRejectReason;
  117. uint256 hashBlock;
  118. };
  119. /**
  120. * Maintain validation-specific state about nodes, protected by cs_main, instead
  121. * by CNode's own locks. This simplifies asynchronous operation, where
  122. * processing of incoming data is done after the ProcessMessage call returns,
  123. * and we're no longer holding the node's locks.
  124. */
  125. struct CNodeState {
  126. //! The peer's address
  127. const CService address;
  128. //! Whether we have a fully established connection.
  129. bool fCurrentlyConnected;
  130. //! Accumulated misbehaviour score for this peer.
  131. int nMisbehavior;
  132. //! Whether this peer should be disconnected and banned (unless whitelisted).
  133. bool fShouldBan;
  134. //! String name of this peer (debugging/logging purposes).
  135. const std::string name;
  136. //! List of asynchronously-determined block rejections to notify this peer about.
  137. std::vector<CBlockReject> rejects;
  138. //! The best known block we know this peer has announced.
  139. const CBlockIndex *pindexBestKnownBlock;
  140. //! The hash of the last unknown block this peer has announced.
  141. uint256 hashLastUnknownBlock;
  142. //! The last full block we both have.
  143. const CBlockIndex *pindexLastCommonBlock;
  144. //! The best header we have sent our peer.
  145. const CBlockIndex *pindexBestHeaderSent;
  146. //! Length of current-streak of unconnecting headers announcements
  147. int nUnconnectingHeaders;
  148. //! Whether we've started headers synchronization with this peer.
  149. bool fSyncStarted;
  150. //! Since when we're stalling block download progress (in microseconds), or 0.
  151. int64_t nStallingSince;
  152. std::list<QueuedBlock> vBlocksInFlight;
  153. //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty.
  154. int64_t nDownloadingSince;
  155. int nBlocksInFlight;
  156. int nBlocksInFlightValidHeaders;
  157. //! Whether we consider this a preferred download peer.
  158. bool fPreferredDownload;
  159. //! Whether this peer wants invs or headers (when possible) for block announcements.
  160. bool fPreferHeaders;
  161. //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements.
  162. bool fPreferHeaderAndIDs;
  163. /**
  164. * Whether this peer will send us cmpctblocks if we request them.
  165. * This is not used to gate request logic, as we really only care about fSupportsDesiredCmpctVersion,
  166. * but is used as a flag to "lock in" the version of compact blocks (fWantsCmpctWitness) we send.
  167. */
  168. bool fProvidesHeaderAndIDs;
  169. //! Whether this peer can give us witnesses
  170. bool fHaveWitness;
  171. //! Whether this peer wants witnesses in cmpctblocks/blocktxns
  172. bool fWantsCmpctWitness;
  173. /**
  174. * If we've announced NODE_WITNESS to this peer: whether the peer sends witnesses in cmpctblocks/blocktxns,
  175. * otherwise: whether this peer sends non-witnesses in cmpctblocks/blocktxns.
  176. */
  177. bool fSupportsDesiredCmpctVersion;
  178. CNodeState(CAddress addrIn, std::string addrNameIn) : address(addrIn), name(addrNameIn) {
  179. fCurrentlyConnected = false;
  180. nMisbehavior = 0;
  181. fShouldBan = false;
  182. pindexBestKnownBlock = NULL;
  183. hashLastUnknownBlock.SetNull();
  184. pindexLastCommonBlock = NULL;
  185. pindexBestHeaderSent = NULL;
  186. nUnconnectingHeaders = 0;
  187. fSyncStarted = false;
  188. nStallingSince = 0;
  189. nDownloadingSince = 0;
  190. nBlocksInFlight = 0;
  191. nBlocksInFlightValidHeaders = 0;
  192. fPreferredDownload = false;
  193. fPreferHeaders = false;
  194. fPreferHeaderAndIDs = false;
  195. fProvidesHeaderAndIDs = false;
  196. fHaveWitness = false;
  197. fWantsCmpctWitness = false;
  198. fSupportsDesiredCmpctVersion = false;
  199. }
  200. };
  201. /** Map maintaining per-node state. Requires cs_main. */
  202. std::map<NodeId, CNodeState> mapNodeState;
  203. // Requires cs_main.
  204. CNodeState *State(NodeId pnode) {
  205. std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
  206. if (it == mapNodeState.end())
  207. return NULL;
  208. return &it->second;
  209. }
  210. void UpdatePreferredDownload(CNode* node, CNodeState* state)
  211. {
  212. nPreferredDownload -= state->fPreferredDownload;
  213. // Whether this node should be marked as a preferred download node.
  214. state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
  215. nPreferredDownload += state->fPreferredDownload;
  216. }
  217. void PushNodeVersion(CNode *pnode, CConnman& connman, int64_t nTime)
  218. {
  219. ServiceFlags nLocalNodeServices = pnode->GetLocalServices();
  220. uint64_t nonce = pnode->GetLocalNonce();
  221. int nNodeStartingHeight = pnode->GetMyStartingHeight();
  222. NodeId nodeid = pnode->GetId();
  223. CAddress addr = pnode->addr;
  224. CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(), addr.nServices));
  225. CAddress addrMe = CAddress(CService(), nLocalNodeServices);
  226. connman.PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, PROTOCOL_VERSION, (uint64_t)nLocalNodeServices, nTime, addrYou, addrMe,
  227. nonce, strSubVersion, nNodeStartingHeight, ::fRelayTxes));
  228. if (fLogIPs) {
  229. LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), addrYou.ToString(), nodeid);
  230. } else {
  231. LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nNodeStartingHeight, addrMe.ToString(), nodeid);
  232. }
  233. }
  234. void InitializeNode(CNode *pnode, CConnman& connman) {
  235. CAddress addr = pnode->addr;
  236. std::string addrName = pnode->GetAddrName();
  237. NodeId nodeid = pnode->GetId();
  238. {
  239. LOCK(cs_main);
  240. mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName)));
  241. }
  242. if(!pnode->fInbound)
  243. PushNodeVersion(pnode, connman, GetTime());
  244. }
  245. void FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) {
  246. fUpdateConnectionTime = false;
  247. LOCK(cs_main);
  248. CNodeState *state = State(nodeid);
  249. if (state->fSyncStarted)
  250. nSyncStarted--;
  251. if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
  252. fUpdateConnectionTime = true;
  253. }
  254. BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight) {
  255. mapBlocksInFlight.erase(entry.hash);
  256. }
  257. EraseOrphansFor(nodeid);
  258. nPreferredDownload -= state->fPreferredDownload;
  259. nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0);
  260. assert(nPeersWithValidatedDownloads >= 0);
  261. mapNodeState.erase(nodeid);
  262. if (mapNodeState.empty()) {
  263. // Do a consistency check after the last peer is removed.
  264. assert(mapBlocksInFlight.empty());
  265. assert(nPreferredDownload == 0);
  266. assert(nPeersWithValidatedDownloads == 0);
  267. }
  268. }
  269. // Requires cs_main.
  270. // Returns a bool indicating whether we requested this block.
  271. // Also used if a block was /not/ received and timed out or started with another peer
  272. bool MarkBlockAsReceived(const uint256& hash) {
  273. std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
  274. if (itInFlight != mapBlocksInFlight.end()) {
  275. CNodeState *state = State(itInFlight->second.first);
  276. state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
  277. if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
  278. // Last validated block on the queue was received.
  279. nPeersWithValidatedDownloads--;
  280. }
  281. if (state->vBlocksInFlight.begin() == itInFlight->second.second) {
  282. // First block on the queue was received, update the start download time for the next one
  283. state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros());
  284. }
  285. state->vBlocksInFlight.erase(itInFlight->second.second);
  286. state->nBlocksInFlight--;
  287. state->nStallingSince = 0;
  288. mapBlocksInFlight.erase(itInFlight);
  289. return true;
  290. }
  291. return false;
  292. }
  293. // Requires cs_main.
  294. // returns false, still setting pit, if the block was already in flight from the same peer
  295. // pit will only be valid as long as the same cs_main lock is being held
  296. bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const Consensus::Params& consensusParams, const CBlockIndex* pindex = NULL, std::list<QueuedBlock>::iterator** pit = NULL) {
  297. CNodeState *state = State(nodeid);
  298. assert(state != NULL);
  299. // Short-circuit most stuff in case its from the same node
  300. std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
  301. if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) {
  302. *pit = &itInFlight->second.second;
  303. return false;
  304. }
  305. // Make sure it's not listed somewhere already.
  306. MarkBlockAsReceived(hash);
  307. std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(),
  308. {hash, pindex, pindex != NULL, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : NULL)});
  309. state->nBlocksInFlight++;
  310. state->nBlocksInFlightValidHeaders += it->fValidatedHeaders;
  311. if (state->nBlocksInFlight == 1) {
  312. // We're starting a block download (batch) from this peer.
  313. state->nDownloadingSince = GetTimeMicros();
  314. }
  315. if (state->nBlocksInFlightValidHeaders == 1 && pindex != NULL) {
  316. nPeersWithValidatedDownloads++;
  317. }
  318. itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first;
  319. if (pit)
  320. *pit = &itInFlight->second.second;
  321. return true;
  322. }
  323. /** Check whether the last unknown block a peer advertised is not yet known. */
  324. void ProcessBlockAvailability(NodeId nodeid) {
  325. CNodeState *state = State(nodeid);
  326. assert(state != NULL);
  327. if (!state->hashLastUnknownBlock.IsNull()) {
  328. BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
  329. if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
  330. if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
  331. state->pindexBestKnownBlock = itOld->second;
  332. state->hashLastUnknownBlock.SetNull();
  333. }
  334. }
  335. }
  336. /** Update tracking information about which blocks a peer is assumed to have. */
  337. void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
  338. CNodeState *state = State(nodeid);
  339. assert(state != NULL);
  340. ProcessBlockAvailability(nodeid);
  341. BlockMap::iterator it = mapBlockIndex.find(hash);
  342. if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
  343. // An actually better block was announced.
  344. if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
  345. state->pindexBestKnownBlock = it->second;
  346. } else {
  347. // An unknown block was announced; just assume that the latest one is the best one.
  348. state->hashLastUnknownBlock = hash;
  349. }
  350. }
  351. void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman& connman) {
  352. AssertLockHeld(cs_main);
  353. CNodeState* nodestate = State(nodeid);
  354. if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) {
  355. // Never ask from peers who can't provide witnesses.
  356. return;
  357. }
  358. if (nodestate->fProvidesHeaderAndIDs) {
  359. for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) {
  360. if (*it == nodeid) {
  361. lNodesAnnouncingHeaderAndIDs.erase(it);
  362. lNodesAnnouncingHeaderAndIDs.push_back(nodeid);
  363. return;
  364. }
  365. }
  366. connman.ForNode(nodeid, [&connman](CNode* pfrom){
  367. bool fAnnounceUsingCMPCTBLOCK = false;
  368. uint64_t nCMPCTBLOCKVersion = (pfrom->GetLocalServices() & NODE_WITNESS) ? 2 : 1;
  369. if (lNodesAnnouncingHeaderAndIDs.size() >= 3) {
  370. // As per BIP152, we only get 3 of our peers to announce
  371. // blocks using compact encodings.
  372. connman.ForNode(lNodesAnnouncingHeaderAndIDs.front(), [&connman, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion](CNode* pnodeStop){
  373. connman.PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetSendVersion()).Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
  374. return true;
  375. });
  376. lNodesAnnouncingHeaderAndIDs.pop_front();
  377. }
  378. fAnnounceUsingCMPCTBLOCK = true;
  379. connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
  380. lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId());
  381. return true;
  382. });
  383. }
  384. }
  385. // Requires cs_main
  386. bool CanDirectFetch(const Consensus::Params &consensusParams)
  387. {
  388. return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20;
  389. }
  390. // Requires cs_main
  391. bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex)
  392. {
  393. if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight))
  394. return true;
  395. if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight))
  396. return true;
  397. return false;
  398. }
  399. /** Find the last common ancestor two blocks have.
  400. * Both pa and pb must be non-NULL. */
  401. const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) {
  402. if (pa->nHeight > pb->nHeight) {
  403. pa = pa->GetAncestor(pb->nHeight);
  404. } else if (pb->nHeight > pa->nHeight) {
  405. pb = pb->GetAncestor(pa->nHeight);
  406. }
  407. while (pa != pb && pa && pb) {
  408. pa = pa->pprev;
  409. pb = pb->pprev;
  410. }
  411. // Eventually all chain branches meet at the genesis block.
  412. assert(pa == pb);
  413. return pa;
  414. }
  415. /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
  416. * at most count entries. */
  417. void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller, const Consensus::Params& consensusParams) {
  418. if (count == 0)
  419. return;
  420. vBlocks.reserve(vBlocks.size() + count);
  421. CNodeState *state = State(nodeid);
  422. assert(state != NULL);
  423. // Make sure pindexBestKnownBlock is up to date, we'll need it.
  424. ProcessBlockAvailability(nodeid);
  425. if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
  426. // This peer has nothing interesting.
  427. return;
  428. }
  429. if (state->pindexLastCommonBlock == NULL) {
  430. // Bootstrap quickly by guessing a parent of our best tip is the forking point.
  431. // Guessing wrong in either direction is not a problem.
  432. state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
  433. }
  434. // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
  435. // of its current tip anymore. Go back enough to fix that.
  436. state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
  437. if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
  438. return;
  439. std::vector<const CBlockIndex*> vToFetch;
  440. const CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
  441. // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
  442. // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
  443. // download that next block if the window were 1 larger.
  444. int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
  445. int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
  446. NodeId waitingfor = -1;
  447. while (pindexWalk->nHeight < nMaxHeight) {
  448. // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
  449. // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
  450. // as iterating over ~100 CBlockIndex* entries anyway.
  451. int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
  452. vToFetch.resize(nToFetch);
  453. pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
  454. vToFetch[nToFetch - 1] = pindexWalk;
  455. for (unsigned int i = nToFetch - 1; i > 0; i--) {
  456. vToFetch[i - 1] = vToFetch[i]->pprev;
  457. }
  458. // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
  459. // are not yet downloaded and not in flight to vBlocks. In the mean time, update
  460. // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's
  461. // already part of our chain (and therefore don't need it even if pruned).
  462. BOOST_FOREACH(const CBlockIndex* pindex, vToFetch) {
  463. if (!pindex->IsValid(BLOCK_VALID_TREE)) {
  464. // We consider the chain that this peer is on invalid.
  465. return;
  466. }
  467. if (!State(nodeid)->fHaveWitness && IsWitnessEnabled(pindex->pprev, consensusParams)) {
  468. // We wouldn't download this block or its descendants from this peer.
  469. return;
  470. }
  471. if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
  472. if (pindex->nChainTx)
  473. state->pindexLastCommonBlock = pindex;
  474. } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
  475. // The block is not already downloaded, and not yet in flight.
  476. if (pindex->nHeight > nWindowEnd) {
  477. // We reached the end of the window.
  478. if (vBlocks.size() == 0 && waitingfor != nodeid) {
  479. // We aren't able to fetch anything, but we would be if the download window was one larger.
  480. nodeStaller = waitingfor;
  481. }
  482. return;
  483. }
  484. vBlocks.push_back(pindex);
  485. if (vBlocks.size() == count) {
  486. return;
  487. }
  488. } else if (waitingfor == -1) {
  489. // This is the first already-in-flight block.
  490. waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
  491. }
  492. }
  493. }
  494. }
  495. } // anon namespace
  496. bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
  497. LOCK(cs_main);
  498. CNodeState *state = State(nodeid);
  499. if (state == NULL)
  500. return false;
  501. stats.nMisbehavior = state->nMisbehavior;
  502. stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
  503. stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
  504. BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
  505. if (queue.pindex)
  506. stats.vHeightInFlight.push_back(queue.pindex->nHeight);
  507. }
  508. return true;
  509. }
  510. void RegisterNodeSignals(CNodeSignals& nodeSignals)
  511. {
  512. nodeSignals.ProcessMessages.connect(&ProcessMessages);
  513. nodeSignals.SendMessages.connect(&SendMessages);
  514. nodeSignals.InitializeNode.connect(&InitializeNode);
  515. nodeSignals.FinalizeNode.connect(&FinalizeNode);
  516. }
  517. void UnregisterNodeSignals(CNodeSignals& nodeSignals)
  518. {
  519. nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
  520. nodeSignals.SendMessages.disconnect(&SendMessages);
  521. nodeSignals.InitializeNode.disconnect(&InitializeNode);
  522. nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
  523. }
  524. //////////////////////////////////////////////////////////////////////////////
  525. //
  526. // mapOrphanTransactions
  527. //
  528. void AddToCompactExtraTransactions(const CTransactionRef& tx)
  529. {
  530. size_t max_extra_txn = GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN);
  531. if (max_extra_txn <= 0)
  532. return;
  533. if (!vExtraTxnForCompact.size())
  534. vExtraTxnForCompact.resize(max_extra_txn);
  535. vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetWitnessHash(), tx);
  536. vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn;
  537. }
  538. bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
  539. {
  540. const uint256& hash = tx->GetHash();
  541. if (mapOrphanTransactions.count(hash))
  542. return false;
  543. // Ignore big transactions, to avoid a
  544. // send-big-orphans memory exhaustion attack. If a peer has a legitimate
  545. // large transaction with a missing parent then we assume
  546. // it will rebroadcast it later, after the parent transaction(s)
  547. // have been mined or received.
  548. // 100 orphans, each of which is at most 99,999 bytes big is
  549. // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case):
  550. unsigned int sz = GetTransactionWeight(*tx);
  551. if (sz >= MAX_STANDARD_TX_WEIGHT)
  552. {
  553. LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
  554. return false;
  555. }
  556. auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME});
  557. assert(ret.second);
  558. BOOST_FOREACH(const CTxIn& txin, tx->vin) {
  559. mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first);
  560. }
  561. AddToCompactExtraTransactions(tx);
  562. LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(),
  563. mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
  564. return true;
  565. }
  566. int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
  567. {
  568. std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
  569. if (it == mapOrphanTransactions.end())
  570. return 0;
  571. BOOST_FOREACH(const CTxIn& txin, it->second.tx->vin)
  572. {
  573. auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout);
  574. if (itPrev == mapOrphanTransactionsByPrev.end())
  575. continue;
  576. itPrev->second.erase(it);
  577. if (itPrev->second.empty())
  578. mapOrphanTransactionsByPrev.erase(itPrev);
  579. }
  580. mapOrphanTransactions.erase(it);
  581. return 1;
  582. }
  583. void EraseOrphansFor(NodeId peer)
  584. {
  585. int nErased = 0;
  586. std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
  587. while (iter != mapOrphanTransactions.end())
  588. {
  589. std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
  590. if (maybeErase->second.fromPeer == peer)
  591. {
  592. nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
  593. }
  594. }
  595. if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx from peer=%d\n", nErased, peer);
  596. }
  597. unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
  598. {
  599. unsigned int nEvicted = 0;
  600. static int64_t nNextSweep;
  601. int64_t nNow = GetTime();
  602. if (nNextSweep <= nNow) {
  603. // Sweep out expired orphan pool entries:
  604. int nErased = 0;
  605. int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL;
  606. std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
  607. while (iter != mapOrphanTransactions.end())
  608. {
  609. std::map<uint256, COrphanTx>::iterator maybeErase = iter++;
  610. if (maybeErase->second.nTimeExpire <= nNow) {
  611. nErased += EraseOrphanTx(maybeErase->second.tx->GetHash());
  612. } else {
  613. nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime);
  614. }
  615. }
  616. // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan.
  617. nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL;
  618. if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx due to expiration\n", nErased);
  619. }
  620. while (mapOrphanTransactions.size() > nMaxOrphans)
  621. {
  622. // Evict a random orphan:
  623. uint256 randomhash = GetRandHash();
  624. std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
  625. if (it == mapOrphanTransactions.end())
  626. it = mapOrphanTransactions.begin();
  627. EraseOrphanTx(it->first);
  628. ++nEvicted;
  629. }
  630. return nEvicted;
  631. }
  632. // Requires cs_main.
  633. void Misbehaving(NodeId pnode, int howmuch)
  634. {
  635. if (howmuch == 0)
  636. return;
  637. CNodeState *state = State(pnode);
  638. if (state == NULL)
  639. return;
  640. state->nMisbehavior += howmuch;
  641. int banscore = GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD);
  642. if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
  643. {
  644. LogPrintf("%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
  645. state->fShouldBan = true;
  646. } else
  647. LogPrintf("%s: %s peer=%d (%d -> %d)\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior);
  648. }
  649. //////////////////////////////////////////////////////////////////////////////
  650. //
  651. // blockchain -> download logic notification
  652. //
  653. PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn) : connman(connmanIn) {
  654. // Initialize global variables that cannot be constructed at startup.
  655. recentRejects.reset(new CRollingBloomFilter(120000, 0.000001));
  656. }
  657. void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex, const std::vector<CTransactionRef>& vtxConflicted) {
  658. LOCK(cs_main);
  659. std::vector<uint256> vOrphanErase;
  660. for (const CTransactionRef& ptx : pblock->vtx) {
  661. const CTransaction& tx = *ptx;
  662. // Which orphan pool entries must we evict?
  663. for (size_t j = 0; j < tx.vin.size(); j++) {
  664. auto itByPrev = mapOrphanTransactionsByPrev.find(tx.vin[j].prevout);
  665. if (itByPrev == mapOrphanTransactionsByPrev.end()) continue;
  666. for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) {
  667. const CTransaction& orphanTx = *(*mi)->second.tx;
  668. const uint256& orphanHash = orphanTx.GetHash();
  669. vOrphanErase.push_back(orphanHash);
  670. }
  671. }
  672. }
  673. // Erase orphan transactions include or precluded by this block
  674. if (vOrphanErase.size()) {
  675. int nErased = 0;
  676. BOOST_FOREACH(uint256 &orphanHash, vOrphanErase) {
  677. nErased += EraseOrphanTx(orphanHash);
  678. }
  679. LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
  680. }
  681. }
  682. // All of the following cache a recent block, and are protected by cs_most_recent_block
  683. static CCriticalSection cs_most_recent_block;
  684. static std::shared_ptr<const CBlock> most_recent_block;
  685. static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block;
  686. static uint256 most_recent_block_hash;
  687. static bool fWitnessesPresentInMostRecentCompactBlock;
  688. void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) {
  689. std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock, true);
  690. const CNetMsgMaker msgMaker(PROTOCOL_VERSION);
  691. LOCK(cs_main);
  692. static int nHighestFastAnnounce = 0;
  693. if (pindex->nHeight <= nHighestFastAnnounce)
  694. return;
  695. nHighestFastAnnounce = pindex->nHeight;
  696. bool fWitnessEnabled = IsWitnessEnabled(pindex->pprev, Params().GetConsensus());
  697. uint256 hashBlock(pblock->GetHash());
  698. {
  699. LOCK(cs_most_recent_block);
  700. most_recent_block_hash = hashBlock;
  701. most_recent_block = pblock;
  702. most_recent_compact_block = pcmpctblock;
  703. fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
  704. }
  705. connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) {
  706. // TODO: Avoid the repeated-serialization here
  707. if (pnode->nVersion < INVALID_CB_NO_BAN_VERSION || pnode->fDisconnect)
  708. return;
  709. ProcessBlockAvailability(pnode->GetId());
  710. CNodeState &state = *State(pnode->GetId());
  711. // If the peer has, or we announced to them the previous block already,
  712. // but we don't think they have this one, go ahead and announce it
  713. if (state.fPreferHeaderAndIDs && (!fWitnessEnabled || state.fWantsCmpctWitness) &&
  714. !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) {
  715. LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
  716. hashBlock.ToString(), pnode->id);
  717. connman->PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
  718. state.pindexBestHeaderSent = pindex;
  719. }
  720. });
  721. }
  722. void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
  723. const int nNewHeight = pindexNew->nHeight;
  724. connman->SetBestHeight(nNewHeight);
  725. if (!fInitialDownload) {
  726. // Find the hashes of all blocks that weren't previously in the best chain.
  727. std::vector<uint256> vHashes;
  728. const CBlockIndex *pindexToAnnounce = pindexNew;
  729. while (pindexToAnnounce != pindexFork) {
  730. vHashes.push_back(pindexToAnnounce->GetBlockHash());
  731. pindexToAnnounce = pindexToAnnounce->pprev;
  732. if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) {
  733. // Limit announcements in case of a huge reorganization.
  734. // Rely on the peer's synchronization mechanism in that case.
  735. break;
  736. }
  737. }
  738. // Relay inventory, but don't relay old inventory during initial block download.
  739. connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) {
  740. if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
  741. BOOST_REVERSE_FOREACH(const uint256& hash, vHashes) {
  742. pnode->PushBlockHash(hash);
  743. }
  744. }
  745. });
  746. connman->WakeMessageHandler();
  747. }
  748. nTimeBestReceived = GetTime();
  749. }
  750. void PeerLogicValidation::BlockChecked(const CBlock& block, const CValidationState& state) {
  751. LOCK(cs_main);
  752. const uint256 hash(block.GetHash());
  753. std::map<uint256, std::pair<NodeId, bool>>::iterator it = mapBlockSource.find(hash);
  754. int nDoS = 0;
  755. if (state.IsInvalid(nDoS)) {
  756. // Don't send reject message with code 0 or an internal reject code.
  757. if (it != mapBlockSource.end() && State(it->second.first) && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) {
  758. CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), hash};
  759. State(it->second.first)->rejects.push_back(reject);
  760. if (nDoS > 0 && it->second.second)
  761. Misbehaving(it->second.first, nDoS);
  762. }
  763. }
  764. // Check that:
  765. // 1. The block is valid
  766. // 2. We're not in initial block download
  767. // 3. This is currently the best block we're aware of. We haven't updated
  768. // the tip yet so we have no way to check this directly here. Instead we
  769. // just check that there are currently no other blocks in flight.
  770. else if (state.IsValid() &&
  771. !IsInitialBlockDownload() &&
  772. mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
  773. if (it != mapBlockSource.end()) {
  774. MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, *connman);
  775. }
  776. }
  777. if (it != mapBlockSource.end())
  778. mapBlockSource.erase(it);
  779. }
  780. //////////////////////////////////////////////////////////////////////////////
  781. //
  782. // Messages
  783. //
  784. bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
  785. {
  786. switch (inv.type)
  787. {
  788. case MSG_TX:
  789. case MSG_WITNESS_TX:
  790. {
  791. assert(recentRejects);
  792. if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip)
  793. {
  794. // If the chain tip has changed previously rejected transactions
  795. // might be now valid, e.g. due to a nLockTime'd tx becoming valid,
  796. // or a double-spend. Reset the rejects filter and give those
  797. // txs a second chance.
  798. hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash();
  799. recentRejects->reset();
  800. }
  801. // Use pcoinsTip->HaveCoinsInCache as a quick approximation to exclude
  802. // requesting or processing some txs which have already been included in a block
  803. return recentRejects->contains(inv.hash) ||
  804. mempool.exists(inv.hash) ||
  805. mapOrphanTransactions.count(inv.hash) ||
  806. pcoinsTip->HaveCoinsInCache(inv.hash);
  807. }
  808. case MSG_BLOCK:
  809. case MSG_WITNESS_BLOCK:
  810. return mapBlockIndex.count(inv.hash);
  811. }
  812. // Don't know what it is, just say we already got one
  813. return true;
  814. }
  815. static void RelayTransaction(const CTransaction& tx, CConnman& connman)
  816. {
  817. CInv inv(MSG_TX, tx.GetHash());
  818. connman.ForEachNode([&inv](CNode* pnode)
  819. {
  820. pnode->PushInventory(inv);
  821. });
  822. }
  823. static void RelayAddress(const CAddress& addr, bool fReachable, CConnman& connman)
  824. {
  825. unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
  826. // Relay to a limited number of other nodes
  827. // Use deterministic randomness to send to the same nodes for 24 hours
  828. // at a time so the addrKnowns of the chosen nodes prevent repeats
  829. uint64_t hashAddr = addr.GetHash();
  830. const CSipHasher hasher = connman.GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60));
  831. FastRandomContext insecure_rand;
  832. std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}};
  833. assert(nRelayNodes <= best.size());
  834. auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) {
  835. if (pnode->nVersion >= CADDR_TIME_VERSION) {
  836. uint64_t hashKey = CSipHasher(hasher).Write(pnode->id).Finalize();
  837. for (unsigned int i = 0; i < nRelayNodes; i++) {
  838. if (hashKey > best[i].first) {
  839. std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1);
  840. best[i] = std::make_pair(hashKey, pnode);
  841. break;
  842. }
  843. }
  844. }
  845. };
  846. auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] {
  847. for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) {
  848. best[i].second->PushAddress(addr, insecure_rand);
  849. }
  850. };
  851. connman.ForEachNodeThen(std::move(sortfunc), std::move(pushfunc));
  852. }
  853. void static ProcessGetData(CNode* pfrom, const Consensus::Params& consensusParams, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
  854. {
  855. std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
  856. std::vector<CInv> vNotFound;
  857. const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
  858. LOCK(cs_main);
  859. while (it != pfrom->vRecvGetData.end()) {
  860. // Don't bother if send buffer is too full to respond anyway
  861. if (pfrom->fPauseSend)
  862. break;
  863. const CInv &inv = *it;
  864. {
  865. if (interruptMsgProc)
  866. return;
  867. it++;
  868. if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
  869. {
  870. bool send = false;
  871. BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
  872. std::shared_ptr<const CBlock> a_recent_block;
  873. std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block;
  874. bool fWitnessesPresentInARecentCompactBlock;
  875. {
  876. LOCK(cs_most_recent_block);
  877. a_recent_block = most_recent_block;
  878. a_recent_compact_block = most_recent_compact_block;
  879. fWitnessesPresentInARecentCompactBlock = fWitnessesPresentInMostRecentCompactBlock;
  880. }
  881. if (mi != mapBlockIndex.end())
  882. {
  883. if (mi->second->nChainTx && !mi->second->IsValid(BLOCK_VALID_SCRIPTS) &&
  884. mi->second->IsValid(BLOCK_VALID_TREE)) {
  885. // If we have the block and all of its parents, but have not yet validated it,
  886. // we might be in the middle of connecting it (ie in the unlock of cs_main
  887. // before ActivateBestChain but after AcceptBlock).
  888. // In this case, we need to run ActivateBestChain prior to checking the relay
  889. // conditions below.
  890. CValidationState dummy;
  891. ActivateBestChain(dummy, Params(), a_recent_block);
  892. }
  893. if (chainActive.Contains(mi->second)) {
  894. send = true;
  895. } else {
  896. static const int nOneMonth = 30 * 24 * 60 * 60;
  897. // To prevent fingerprinting attacks, only send blocks outside of the active
  898. // chain if they are valid, and no more than a month older (both in time, and in
  899. // best equivalent proof of work) than the best header chain we know about.
  900. send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
  901. (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() < nOneMonth) &&
  902. (GetBlockProofEquivalentTime(*pindexBestHeader, *mi->second, *pindexBestHeader, consensusParams) < nOneMonth);
  903. if (!send) {
  904. LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
  905. }
  906. }
  907. }
  908. // disconnect node in case we have reached the outbound limit for serving historical blocks
  909. // never disconnect whitelisted nodes
  910. static const int nOneWeek = 7 * 24 * 60 * 60; // assume > 1 week = historical
  911. if (send && connman.OutboundTargetReached(true) && ( ((pindexBestHeader != NULL) && (pindexBestHeader->GetBlockTime() - mi->second->GetBlockTime() > nOneWeek)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted)
  912. {
  913. LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId());
  914. //disconnect node
  915. pfrom->fDisconnect = true;
  916. send = false;
  917. }
  918. // Pruned nodes may have deleted the block, so check whether
  919. // it's available before trying to send.
  920. if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
  921. {
  922. std::shared_ptr<const CBlock> pblock;
  923. if (a_recent_block && a_recent_block->GetHash() == (*mi).second->GetBlockHash()) {
  924. pblock = a_recent_block;
  925. } else {
  926. // Send block from disk
  927. std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>();
  928. if (!ReadBlockFromDisk(*pblockRead, (*mi).second, consensusParams))
  929. assert(!"cannot load block from disk");
  930. pblock = pblockRead;
  931. }
  932. if (inv.type == MSG_BLOCK)
  933. connman.PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::BLOCK, *pblock));
  934. else if (inv.type == MSG_WITNESS_BLOCK)
  935. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock));
  936. else if (inv.type == MSG_FILTERED_BLOCK)
  937. {
  938. bool sendMerkleBlock = false;
  939. CMerkleBlock merkleBlock;
  940. {
  941. LOCK(pfrom->cs_filter);
  942. if (pfrom->pfilter) {
  943. sendMerkleBlock = true;
  944. merkleBlock = CMerkleBlock(*pblock, *pfrom->pfilter);
  945. }
  946. }
  947. if (sendMerkleBlock) {
  948. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock));
  949. // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
  950. // This avoids hurting performance by pointlessly requiring a round-trip
  951. // Note that there is currently no way for a node to request any single transactions we didn't send here -
  952. // they must either disconnect and retry or request the full block.
  953. // Thus, the protocol spec specified allows for us to provide duplicate txn here,
  954. // however we MUST always provide at least what the remote peer needs
  955. typedef std::pair<unsigned int, uint256> PairType;
  956. BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
  957. connman.PushMessage(pfrom, msgMaker.Make(SERIALIZE_TRANSACTION_NO_WITNESS, NetMsgType::TX, *pblock->vtx[pair.first]));
  958. }
  959. // else
  960. // no response
  961. }
  962. else if (inv.type == MSG_CMPCT_BLOCK)
  963. {
  964. // If a peer is asking for old blocks, we're almost guaranteed
  965. // they won't have a useful mempool to match against a compact block,
  966. // and we don't feel like constructing the object for them, so
  967. // instead we respond with the full, non-compact block.
  968. bool fPeerWantsWitness = State(pfrom->GetId())->fWantsCmpctWitness;
  969. int nSendFlags = fPeerWantsWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
  970. if (CanDirectFetch(consensusParams) && mi->second->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) {
  971. if ((fPeerWantsWitness || !fWitnessesPresentInARecentCompactBlock) && a_recent_compact_block && a_recent_compact_block->header.GetHash() == mi->second->GetBlockHash()) {
  972. connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *a_recent_compact_block));
  973. } else {
  974. CBlockHeaderAndShortTxIDs cmpctblock(*pblock, fPeerWantsWitness);
  975. connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
  976. }
  977. } else {
  978. connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCK, *pblock));
  979. }
  980. }
  981. // Trigger the peer node to send a getblocks request for the next batch of inventory
  982. if (inv.hash == pfrom->hashContinue)
  983. {
  984. // Bypass PushInventory, this must send even if redundant,
  985. // and we want it right after the last block so they don't
  986. // wait for other stuff first.
  987. std::vector<CInv> vInv;
  988. vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
  989. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv));
  990. pfrom->hashContinue.SetNull();
  991. }
  992. }
  993. }
  994. else if (inv.type == MSG_TX || inv.type == MSG_WITNESS_TX)
  995. {
  996. // Send stream from relay memory
  997. bool push = false;
  998. auto mi = mapRelay.find(inv.hash);
  999. int nSendFlags = (inv.type == MSG_TX ? SERIALIZE_TRANSACTION_NO_WITNESS : 0);
  1000. if (mi != mapRelay.end()) {
  1001. connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *mi->second));
  1002. push = true;
  1003. } else if (pfrom->timeLastMempoolReq) {
  1004. auto txinfo = mempool.info(inv.hash);
  1005. // To protect privacy, do not answer getdata using the mempool when
  1006. // that TX couldn't have been INVed in reply to a MEMPOOL request.
  1007. if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) {
  1008. connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::TX, *txinfo.tx));
  1009. push = true;
  1010. }
  1011. }
  1012. if (!push) {
  1013. vNotFound.push_back(inv);
  1014. }
  1015. }
  1016. // Track requests for our stuff.
  1017. GetMainSignals().Inventory(inv.hash);
  1018. if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK || inv.type == MSG_WITNESS_BLOCK)
  1019. break;
  1020. }
  1021. }
  1022. pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
  1023. if (!vNotFound.empty()) {
  1024. // Let the peer know that we didn't find what it asked for, so it doesn't
  1025. // have to wait around forever. Currently only SPV clients actually care
  1026. // about this message: it's needed when they are recursively walking the
  1027. // dependencies of relevant unconfirmed transactions. SPV clients want to
  1028. // do that because they want to know about (and store and rebroadcast and
  1029. // risk analyze) the dependencies of transactions relevant to them, without
  1030. // having to download the entire memory pool.
  1031. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound));
  1032. }
  1033. }
  1034. uint32_t GetFetchFlags(CNode* pfrom) {
  1035. uint32_t nFetchFlags = 0;
  1036. if ((pfrom->GetLocalServices() & NODE_WITNESS) && State(pfrom->GetId())->fHaveWitness) {
  1037. nFetchFlags |= MSG_WITNESS_FLAG;
  1038. }
  1039. return nFetchFlags;
  1040. }
  1041. inline void static SendBlockTransactions(const CBlock& block, const BlockTransactionsRequest& req, CNode* pfrom, CConnman& connman) {
  1042. BlockTransactions resp(req);
  1043. for (size_t i = 0; i < req.indexes.size(); i++) {
  1044. if (req.indexes[i] >= block.vtx.size()) {
  1045. LOCK(cs_main);
  1046. Misbehaving(pfrom->GetId(), 100);
  1047. LogPrintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom->id);
  1048. return;
  1049. }
  1050. resp.txn[i] = block.vtx[req.indexes[i]];
  1051. }
  1052. LOCK(cs_main);
  1053. const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
  1054. int nSendFlags = State(pfrom->GetId())->fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
  1055. connman.PushMessage(pfrom, msgMaker.Make(nSendFlags, NetMsgType::BLOCKTXN, resp));
  1056. }
  1057. bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
  1058. {
  1059. LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
  1060. if (IsArgSet("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 0)) == 0)
  1061. {
  1062. LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
  1063. return true;
  1064. }
  1065. if (!(pfrom->GetLocalServices() & NODE_BLOOM) &&
  1066. (strCommand == NetMsgType::FILTERLOAD ||
  1067. strCommand == NetMsgType::FILTERADD))
  1068. {
  1069. if (pfrom->nVersion >= NO_BLOOM_VERSION) {
  1070. LOCK(cs_main);
  1071. Misbehaving(pfrom->GetId(), 100);
  1072. return false;
  1073. } else {
  1074. pfrom->fDisconnect = true;
  1075. return false;
  1076. }
  1077. }
  1078. if (strCommand == NetMsgType::REJECT)
  1079. {
  1080. if (LogAcceptCategory(BCLog::NET)) {
  1081. try {
  1082. std::string strMsg; unsigned char ccode; std::string strReason;
  1083. vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
  1084. std::ostringstream ss;
  1085. ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
  1086. if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX)
  1087. {
  1088. uint256 hash;
  1089. vRecv >> hash;
  1090. ss << ": hash " << hash.ToString();
  1091. }
  1092. LogPrint(BCLog::NET, "Reject %s\n", SanitizeString(ss.str()));
  1093. } catch (const std::ios_base::failure&) {
  1094. // Avoid feedback loops by preventing reject messages from triggering a new reject message.
  1095. LogPrint(BCLog::NET, "Unparseable reject message received\n");
  1096. }
  1097. }
  1098. }
  1099. else if (strCommand == NetMsgType::VERSION)
  1100. {
  1101. // Each connection can only send one version message
  1102. if (pfrom->nVersion != 0)
  1103. {
  1104. connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")));
  1105. LOCK(cs_main);
  1106. Misbehaving(pfrom->GetId(), 1);
  1107. return false;
  1108. }
  1109. int64_t nTime;
  1110. CAddress addrMe;
  1111. CAddress addrFrom;
  1112. uint64_t nNonce = 1;
  1113. uint64_t nServiceInt;
  1114. ServiceFlags nServices;
  1115. int nVersion;
  1116. int nSendVersion;
  1117. std::string strSubVer;
  1118. std::string cleanSubVer;
  1119. int nStartingHeight = -1;
  1120. bool fRelay = true;
  1121. vRecv >> nVersion >> nServiceInt >> nTime >> addrMe;
  1122. nSendVersion = std::min(nVersion, PROTOCOL_VERSION);
  1123. nServices = ServiceFlags(nServiceInt);
  1124. if (!pfrom->fInbound)
  1125. {
  1126. connman.SetServices(pfrom->addr, nServices);
  1127. }
  1128. if (pfrom->nServicesExpected & ~nServices)
  1129. {
  1130. LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->id, nServices, pfrom->nServicesExpected);
  1131. connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD,
  1132. strprintf("Expected to offer services %08x", pfrom->nServicesExpected)));
  1133. pfrom->fDisconnect = true;
  1134. return false;
  1135. }
  1136. if (nVersion < MIN_PEER_PROTO_VERSION)
  1137. {
  1138. // disconnect from peers older than this proto version
  1139. LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, nVersion);
  1140. connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE,
  1141. strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION)));
  1142. pfrom->fDisconnect = true;
  1143. return false;
  1144. }
  1145. if (nVersion == 10300)
  1146. nVersion = 300;
  1147. if (!vRecv.empty())
  1148. vRecv >> addrFrom >> nNonce;
  1149. if (!vRecv.empty()) {
  1150. vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH);
  1151. cleanSubVer = SanitizeString(strSubVer);
  1152. }
  1153. if (!vRecv.empty()) {
  1154. vRecv >> nStartingHeight;
  1155. }
  1156. if (!vRecv.empty())
  1157. vRecv >> fRelay;
  1158. // Disconnect if we connected to ourself
  1159. if (pfrom->fInbound && !connman.CheckIncomingNonce(nNonce))
  1160. {
  1161. LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
  1162. pfrom->fDisconnect = true;
  1163. return true;
  1164. }
  1165. if (pfrom->fInbound && addrMe.IsRoutable())
  1166. {
  1167. SeenLocal(addrMe);
  1168. }
  1169. // Be shy and don't send version until we hear
  1170. if (pfrom->fInbound)
  1171. PushNodeVersion(pfrom, connman, GetAdjustedTime());
  1172. connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK));
  1173. pfrom->nServices = nServices;
  1174. pfrom->SetAddrLocal(addrMe);
  1175. {
  1176. LOCK(pfrom->cs_SubVer);
  1177. pfrom->strSubVer = strSubVer;
  1178. pfrom->cleanSubVer = cleanSubVer;
  1179. }
  1180. pfrom->nStartingHeight = nStartingHeight;
  1181. pfrom->fClient = !(nServices & NODE_NETWORK);
  1182. {
  1183. LOCK(pfrom->cs_filter);
  1184. pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message
  1185. }
  1186. // Change version
  1187. pfrom->SetSendVersion(nSendVersion);
  1188. pfrom->nVersion = nVersion;
  1189. if((nServices & NODE_WITNESS))
  1190. {
  1191. LOCK(cs_main);
  1192. State(pfrom->GetId())->fHaveWitness = true;
  1193. }
  1194. // Potentially mark this peer as a preferred download peer.
  1195. {
  1196. LOCK(cs_main);
  1197. UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
  1198. }
  1199. if (!pfrom->fInbound)
  1200. {
  1201. // Advertise our address
  1202. if (fListen && !IsInitialBlockDownload())
  1203. {
  1204. CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices());
  1205. FastRandomContext insecure_rand;
  1206. if (addr.IsRoutable())
  1207. {
  1208. LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
  1209. pfrom->PushAddress(addr, insecure_rand);
  1210. } else if (IsPeerAddrLocalGood(pfrom)) {
  1211. addr.SetIP(addrMe);
  1212. LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString());
  1213. pfrom->PushAddress(addr, insecure_rand);
  1214. }
  1215. }
  1216. // Get recent addresses
  1217. if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || connman.GetAddressCount() < 1000)
  1218. {
  1219. connman.PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
  1220. pfrom->fGetAddr = true;
  1221. }
  1222. connman.MarkAddressGood(pfrom->addr);
  1223. }
  1224. std::string remoteAddr;
  1225. if (fLogIPs)
  1226. remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
  1227. LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
  1228. cleanSubVer, pfrom->nVersion,
  1229. pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
  1230. remoteAddr);
  1231. int64_t nTimeOffset = nTime - GetTime();
  1232. pfrom->nTimeOffset = nTimeOffset;
  1233. AddTimeData(pfrom->addr, nTimeOffset);
  1234. // If the peer is old enough to have the old alert system, send it the final alert.
  1235. if (pfrom->nVersion <= 70012) {
  1236. CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
  1237. connman.PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make("alert", finalAlert));
  1238. }
  1239. // Feeler connections exist only to verify if address is online.
  1240. if (pfrom->fFeeler) {
  1241. assert(pfrom->fInbound == false);
  1242. pfrom->fDisconnect = true;
  1243. }
  1244. return true;
  1245. }
  1246. else if (pfrom->nVersion == 0)
  1247. {
  1248. // Must have a version message before anything else
  1249. LOCK(cs_main);
  1250. Misbehaving(pfrom->GetId(), 1);
  1251. return false;
  1252. }
  1253. // At this point, the outgoing message serialization version can't change.
  1254. const CNetMsgMaker msgMaker(pfrom->GetSendVersion());
  1255. if (strCommand == NetMsgType::VERACK)
  1256. {
  1257. pfrom->SetRecvVersion(std::min(pfrom->nVersion.load(), PROTOCOL_VERSION));
  1258. if (!pfrom->fInbound) {
  1259. // Mark this node as currently connected, so we update its timestamp later.
  1260. LOCK(cs_main);
  1261. State(pfrom->GetId())->fCurrentlyConnected = true;
  1262. }
  1263. if (pfrom->nVersion >= SENDHEADERS_VERSION) {
  1264. // Tell our peer we prefer to receive headers rather than inv's
  1265. // We send this to non-NODE NETWORK peers as well, because even
  1266. // non-NODE NETWORK peers can announce blocks (such as pruning
  1267. // nodes)
  1268. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
  1269. }
  1270. if (pfrom->nVersion >= SHORT_IDS_BLOCKS_VERSION) {
  1271. // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
  1272. // However, we do not request new block announcements using
  1273. // cmpctblock messages.
  1274. // We send this to non-NODE NETWORK peers as well, because
  1275. // they may wish to request compact blocks from us
  1276. bool fAnnounceUsingCMPCTBLOCK = false;
  1277. uint64_t nCMPCTBLOCKVersion = 2;
  1278. if (pfrom->GetLocalServices() & NODE_WITNESS)
  1279. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
  1280. nCMPCTBLOCKVersion = 1;
  1281. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
  1282. }
  1283. pfrom->fSuccessfullyConnected = true;
  1284. }
  1285. else if (!pfrom->fSuccessfullyConnected)
  1286. {
  1287. // Must have a verack message before anything else
  1288. LOCK(cs_main);
  1289. Misbehaving(pfrom->GetId(), 1);
  1290. return false;
  1291. }
  1292. else if (strCommand == NetMsgType::ADDR)
  1293. {
  1294. std::vector<CAddress> vAddr;
  1295. vRecv >> vAddr;
  1296. // Don't want addr from older versions unless seeding
  1297. if (pfrom->nVersion < CADDR_TIME_VERSION && connman.GetAddressCount() > 1000)
  1298. return true;
  1299. if (vAddr.size() > 1000)
  1300. {
  1301. LOCK(cs_main);
  1302. Misbehaving(pfrom->GetId(), 20);
  1303. return error("message addr size() = %u", vAddr.size());
  1304. }
  1305. // Store the new addresses
  1306. std::vector<CAddress> vAddrOk;
  1307. int64_t nNow = GetAdjustedTime();
  1308. int64_t nSince = nNow - 10 * 60;
  1309. BOOST_FOREACH(CAddress& addr, vAddr)
  1310. {
  1311. if (interruptMsgProc)
  1312. return true;
  1313. if ((addr.nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES)
  1314. continue;
  1315. if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
  1316. addr.nTime = nNow - 5 * 24 * 60 * 60;
  1317. pfrom->AddAddressKnown(addr);
  1318. bool fReachable = IsReachable(addr);
  1319. if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
  1320. {
  1321. // Relay to a limited number of other nodes
  1322. RelayAddress(addr, fReachable, connman);
  1323. }
  1324. // Do not store addresses outside our network
  1325. if (fReachable)
  1326. vAddrOk.push_back(addr);
  1327. }
  1328. connman.AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60);
  1329. if (vAddr.size() < 1000)
  1330. pfrom->fGetAddr = false;
  1331. if (pfrom->fOneShot)
  1332. pfrom->fDisconnect = true;
  1333. }
  1334. else if (strCommand == NetMsgType::SENDHEADERS)
  1335. {
  1336. LOCK(cs_main);
  1337. State(pfrom->GetId())->fPreferHeaders = true;
  1338. }
  1339. else if (strCommand == NetMsgType::SENDCMPCT)
  1340. {
  1341. bool fAnnounceUsingCMPCTBLOCK = false;
  1342. uint64_t nCMPCTBLOCKVersion = 0;
  1343. vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion;
  1344. if (nCMPCTBLOCKVersion == 1 || ((pfrom->GetLocalServices() & NODE_WITNESS) && nCMPCTBLOCKVersion == 2)) {
  1345. LOCK(cs_main);
  1346. // fProvidesHeaderAndIDs is used to "lock in" version of compact blocks we send (fWantsCmpctWitness)
  1347. if (!State(pfrom->GetId())->fProvidesHeaderAndIDs) {
  1348. State(pfrom->GetId())->fProvidesHeaderAndIDs = true;
  1349. State(pfrom->GetId())->fWantsCmpctWitness = nCMPCTBLOCKVersion == 2;
  1350. }
  1351. if (State(pfrom->GetId())->fWantsCmpctWitness == (nCMPCTBLOCKVersion == 2)) // ignore later version announces
  1352. State(pfrom->GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK;
  1353. if (!State(pfrom->GetId())->fSupportsDesiredCmpctVersion) {
  1354. if (pfrom->GetLocalServices() & NODE_WITNESS)
  1355. State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 2);
  1356. else
  1357. State(pfrom->GetId())->fSupportsDesiredCmpctVersion = (nCMPCTBLOCKVersion == 1);
  1358. }
  1359. }
  1360. }
  1361. else if (strCommand == NetMsgType::INV)
  1362. {
  1363. std::vector<CInv> vInv;
  1364. vRecv >> vInv;
  1365. if (vInv.size() > MAX_INV_SZ)
  1366. {
  1367. LOCK(cs_main);
  1368. Misbehaving(pfrom->GetId(), 20);
  1369. return error("message inv size() = %u", vInv.size());
  1370. }
  1371. bool fBlocksOnly = !fRelayTxes;
  1372. // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true
  1373. if (pfrom->fWhitelisted && GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))
  1374. fBlocksOnly = false;
  1375. LOCK(cs_main);
  1376. uint32_t nFetchFlags = GetFetchFlags(pfrom);
  1377. std::vector<CInv> vToFetch;
  1378. for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
  1379. {
  1380. CInv &inv = vInv[nInv];
  1381. if (interruptMsgProc)
  1382. return true;
  1383. bool fAlreadyHave = AlreadyHave(inv);
  1384. LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
  1385. if (inv.type == MSG_TX) {
  1386. inv.type |= nFetchFlags;
  1387. }
  1388. if (inv.type == MSG_BLOCK) {
  1389. UpdateBlockAvailability(pfrom->GetId(), inv.hash);
  1390. if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
  1391. // We used to request the full block here, but since headers-announcements are now the
  1392. // primary method of announcement on the network, and since, in the case that a node
  1393. // fell back to inv we probably have a reorg which we should get the headers for first,
  1394. // we now only provide a getheaders response here. When we receive the headers, we will
  1395. // then ask for the blocks we need.
  1396. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash));
  1397. LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
  1398. }
  1399. }
  1400. else
  1401. {
  1402. pfrom->AddInventoryKnown(inv);
  1403. if (fBlocksOnly) {
  1404. LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->id);
  1405. } else if (!fAlreadyHave && !fImporting && !fReindex && !IsInitialBlockDownload()) {
  1406. pfrom->AskFor(inv);
  1407. }
  1408. }
  1409. // Track requests for our stuff
  1410. GetMainSignals().Inventory(inv.hash);
  1411. }
  1412. if (!vToFetch.empty())
  1413. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vToFetch));
  1414. }
  1415. else if (strCommand == NetMsgType::GETDATA)
  1416. {
  1417. std::vector<CInv> vInv;
  1418. vRecv >> vInv;
  1419. if (vInv.size() > MAX_INV_SZ)
  1420. {
  1421. LOCK(cs_main);
  1422. Misbehaving(pfrom->GetId(), 20);
  1423. return error("message getdata size() = %u", vInv.size());
  1424. }
  1425. LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
  1426. if (vInv.size() > 0) {
  1427. LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
  1428. }
  1429. pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
  1430. ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
  1431. }
  1432. else if (strCommand == NetMsgType::GETBLOCKS)
  1433. {
  1434. CBlockLocator locator;
  1435. uint256 hashStop;
  1436. vRecv >> locator >> hashStop;
  1437. // We might have announced the currently-being-connected tip using a
  1438. // compact block, which resulted in the peer sending a getblocks
  1439. // request, which we would otherwise respond to without the new block.
  1440. // To avoid this situation we simply verify that we are on our best
  1441. // known chain now. This is super overkill, but we handle it better
  1442. // for getheaders requests, and there are no known nodes which support
  1443. // compact blocks but still use getblocks to request blocks.
  1444. {
  1445. std::shared_ptr<const CBlock> a_recent_block;
  1446. {
  1447. LOCK(cs_most_recent_block);
  1448. a_recent_block = most_recent_block;
  1449. }
  1450. CValidationState dummy;
  1451. ActivateBestChain(dummy, Params(), a_recent_block);
  1452. }
  1453. LOCK(cs_main);
  1454. // Find the last block the caller has in the main chain
  1455. const CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
  1456. // Send the rest of the chain
  1457. if (pindex)
  1458. pindex = chainActive.Next(pindex);
  1459. int nLimit = 500;
  1460. LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
  1461. for (; pindex; pindex = chainActive.Next(pindex))
  1462. {
  1463. if (pindex->GetBlockHash() == hashStop)
  1464. {
  1465. LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  1466. break;
  1467. }
  1468. // If pruning, don't inv blocks unless we have on disk and are likely to still have
  1469. // for some reasonable time window (1 hour) that block relay might require.
  1470. const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing;
  1471. if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave))
  1472. {
  1473. LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  1474. break;
  1475. }
  1476. pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
  1477. if (--nLimit <= 0)
  1478. {
  1479. // When this block is requested, we'll send an inv that'll
  1480. // trigger the peer to getblocks the next batch of inventory.
  1481. LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  1482. pfrom->hashContinue = pindex->GetBlockHash();
  1483. break;
  1484. }
  1485. }
  1486. }
  1487. else if (strCommand == NetMsgType::GETBLOCKTXN)
  1488. {
  1489. BlockTransactionsRequest req;
  1490. vRecv >> req;
  1491. std::shared_ptr<const CBlock> recent_block;
  1492. {
  1493. LOCK(cs_most_recent_block);
  1494. if (most_recent_block_hash == req.blockhash)
  1495. recent_block = most_recent_block;
  1496. // Unlock cs_most_recent_block to avoid cs_main lock inversion
  1497. }
  1498. if (recent_block) {
  1499. SendBlockTransactions(*recent_block, req, pfrom, connman);
  1500. return true;
  1501. }
  1502. LOCK(cs_main);
  1503. BlockMap::iterator it = mapBlockIndex.find(req.blockhash);
  1504. if (it == mapBlockIndex.end() || !(it->second->nStatus & BLOCK_HAVE_DATA)) {
  1505. LogPrintf("Peer %d sent us a getblocktxn for a block we don't have", pfrom->id);
  1506. return true;
  1507. }
  1508. if (it->second->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) {
  1509. // If an older block is requested (should never happen in practice,
  1510. // but can happen in tests) send a block response instead of a
  1511. // blocktxn response. Sending a full block response instead of a
  1512. // small blocktxn response is preferable in the case where a peer
  1513. // might maliciously send lots of getblocktxn requests to trigger
  1514. // expensive disk reads, because it will require the peer to
  1515. // actually receive all the data read from disk over the network.
  1516. LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep", pfrom->id, MAX_BLOCKTXN_DEPTH);
  1517. CInv inv;
  1518. inv.type = State(pfrom->GetId())->fWantsCmpctWitness ? MSG_WITNESS_BLOCK : MSG_BLOCK;
  1519. inv.hash = req.blockhash;
  1520. pfrom->vRecvGetData.push_back(inv);
  1521. ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
  1522. return true;
  1523. }
  1524. CBlock block;
  1525. bool ret = ReadBlockFromDisk(block, it->second, chainparams.GetConsensus());
  1526. assert(ret);
  1527. SendBlockTransactions(block, req, pfrom, connman);
  1528. }
  1529. else if (strCommand == NetMsgType::GETHEADERS)
  1530. {
  1531. CBlockLocator locator;
  1532. uint256 hashStop;
  1533. vRecv >> locator >> hashStop;
  1534. LOCK(cs_main);
  1535. if (IsInitialBlockDownload() && !pfrom->fWhitelisted) {
  1536. LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->id);
  1537. return true;
  1538. }
  1539. CNodeState *nodestate = State(pfrom->GetId());
  1540. const CBlockIndex* pindex = NULL;
  1541. if (locator.IsNull())
  1542. {
  1543. // If locator is null, return the hashStop block
  1544. BlockMap::iterator mi = mapBlockIndex.find(hashStop);
  1545. if (mi == mapBlockIndex.end())
  1546. return true;
  1547. pindex = (*mi).second;
  1548. }
  1549. else
  1550. {
  1551. // Find the last block the caller has in the main chain
  1552. pindex = FindForkInGlobalIndex(chainActive, locator);
  1553. if (pindex)
  1554. pindex = chainActive.Next(pindex);
  1555. }
  1556. // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
  1557. std::vector<CBlock> vHeaders;
  1558. int nLimit = MAX_HEADERS_RESULTS;
  1559. LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->id);
  1560. for (; pindex; pindex = chainActive.Next(pindex))
  1561. {
  1562. vHeaders.push_back(pindex->GetBlockHeader());
  1563. if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
  1564. break;
  1565. }
  1566. // pindex can be NULL either if we sent chainActive.Tip() OR
  1567. // if our peer has chainActive.Tip() (and thus we are sending an empty
  1568. // headers message). In both cases it's safe to update
  1569. // pindexBestHeaderSent to be our tip.
  1570. //
  1571. // It is important that we simply reset the BestHeaderSent value here,
  1572. // and not max(BestHeaderSent, newHeaderSent). We might have announced
  1573. // the currently-being-connected tip using a compact block, which
  1574. // resulted in the peer sending a headers request, which we respond to
  1575. // without the new block. By resetting the BestHeaderSent, we ensure we
  1576. // will re-announce the new block via headers (or compact blocks again)
  1577. // in the SendMessages logic.
  1578. nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip();
  1579. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
  1580. }
  1581. else if (strCommand == NetMsgType::TX)
  1582. {
  1583. // Stop processing the transaction early if
  1584. // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off
  1585. if (!fRelayTxes && (!pfrom->fWhitelisted || !GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)))
  1586. {
  1587. LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->id);
  1588. return true;
  1589. }
  1590. std::deque<COutPoint> vWorkQueue;
  1591. std::vector<uint256> vEraseQueue;
  1592. CTransactionRef ptx;
  1593. vRecv >> ptx;
  1594. const CTransaction& tx = *ptx;
  1595. CInv inv(MSG_TX, tx.GetHash());
  1596. pfrom->AddInventoryKnown(inv);
  1597. LOCK(cs_main);
  1598. bool fMissingInputs = false;
  1599. CValidationState state;
  1600. pfrom->setAskFor.erase(inv.hash);
  1601. mapAlreadyAskedFor.erase(inv.hash);
  1602. std::list<CTransactionRef> lRemovedTxn;
  1603. if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, ptx, true, &fMissingInputs, &lRemovedTxn)) {
  1604. mempool.check(pcoinsTip);
  1605. RelayTransaction(tx, connman);
  1606. for (unsigned int i = 0; i < tx.vout.size(); i++) {
  1607. vWorkQueue.emplace_back(inv.hash, i);
  1608. }
  1609. pfrom->nLastTXTime = GetTime();
  1610. LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
  1611. pfrom->id,
  1612. tx.GetHash().ToString(),
  1613. mempool.size(), mempool.DynamicMemoryUsage() / 1000);
  1614. // Recursively process any orphan transactions that depended on this one
  1615. std::set<NodeId> setMisbehaving;
  1616. while (!vWorkQueue.empty()) {
  1617. auto itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue.front());
  1618. vWorkQueue.pop_front();
  1619. if (itByPrev == mapOrphanTransactionsByPrev.end())
  1620. continue;
  1621. for (auto mi = itByPrev->second.begin();
  1622. mi != itByPrev->second.end();
  1623. ++mi)
  1624. {
  1625. const CTransactionRef& porphanTx = (*mi)->second.tx;
  1626. const CTransaction& orphanTx = *porphanTx;
  1627. const uint256& orphanHash = orphanTx.GetHash();
  1628. NodeId fromPeer = (*mi)->second.fromPeer;
  1629. bool fMissingInputs2 = false;
  1630. // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
  1631. // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
  1632. // anyone relaying LegitTxX banned)
  1633. CValidationState stateDummy;
  1634. if (setMisbehaving.count(fromPeer))
  1635. continue;
  1636. if (AcceptToMemoryPool(mempool, stateDummy, porphanTx, true, &fMissingInputs2, &lRemovedTxn)) {
  1637. LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString());
  1638. RelayTransaction(orphanTx, connman);
  1639. for (unsigned int i = 0; i < orphanTx.vout.size(); i++) {
  1640. vWorkQueue.emplace_back(orphanHash, i);
  1641. }
  1642. vEraseQueue.push_back(orphanHash);
  1643. }
  1644. else if (!fMissingInputs2)
  1645. {
  1646. int nDos = 0;
  1647. if (stateDummy.IsInvalid(nDos) && nDos > 0)
  1648. {
  1649. // Punish peer that gave us an invalid orphan tx
  1650. Misbehaving(fromPeer, nDos);
  1651. setMisbehaving.insert(fromPeer);
  1652. LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString());
  1653. }
  1654. // Has inputs but not accepted to mempool
  1655. // Probably non-standard or insufficient fee
  1656. LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString());
  1657. vEraseQueue.push_back(orphanHash);
  1658. if (!orphanTx.HasWitness() && !stateDummy.CorruptionPossible()) {
  1659. // Do not use rejection cache for witness transactions or
  1660. // witness-stripped transactions, as they can have been malleated.
  1661. // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
  1662. assert(recentRejects);
  1663. recentRejects->insert(orphanHash);
  1664. }
  1665. }
  1666. mempool.check(pcoinsTip);
  1667. }
  1668. }
  1669. BOOST_FOREACH(uint256 hash, vEraseQueue)
  1670. EraseOrphanTx(hash);
  1671. }
  1672. else if (fMissingInputs)
  1673. {
  1674. bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected
  1675. BOOST_FOREACH(const CTxIn& txin, tx.vin) {
  1676. if (recentRejects->contains(txin.prevout.hash)) {
  1677. fRejectedParents = true;
  1678. break;
  1679. }
  1680. }
  1681. if (!fRejectedParents) {
  1682. uint32_t nFetchFlags = GetFetchFlags(pfrom);
  1683. BOOST_FOREACH(const CTxIn& txin, tx.vin) {
  1684. CInv _inv(MSG_TX | nFetchFlags, txin.prevout.hash);
  1685. pfrom->AddInventoryKnown(_inv);
  1686. if (!AlreadyHave(_inv)) pfrom->AskFor(_inv);
  1687. }
  1688. AddOrphanTx(ptx, pfrom->GetId());
  1689. // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
  1690. unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
  1691. unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
  1692. if (nEvicted > 0) {
  1693. LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted);
  1694. }
  1695. } else {
  1696. LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString());
  1697. // We will continue to reject this tx since it has rejected
  1698. // parents so avoid re-requesting it from other peers.
  1699. recentRejects->insert(tx.GetHash());
  1700. }
  1701. } else {
  1702. if (!tx.HasWitness() && !state.CorruptionPossible()) {
  1703. // Do not use rejection cache for witness transactions or
  1704. // witness-stripped transactions, as they can have been malleated.
  1705. // See https://github.com/bitcoin/bitcoin/issues/8279 for details.
  1706. assert(recentRejects);
  1707. recentRejects->insert(tx.GetHash());
  1708. if (RecursiveDynamicUsage(*ptx) < 100000) {
  1709. AddToCompactExtraTransactions(ptx);
  1710. }
  1711. } else if (tx.HasWitness() && RecursiveDynamicUsage(*ptx) < 100000) {
  1712. AddToCompactExtraTransactions(ptx);
  1713. }
  1714. if (pfrom->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
  1715. // Always relay transactions received from whitelisted peers, even
  1716. // if they were already in the mempool or rejected from it due
  1717. // to policy, allowing the node to function as a gateway for
  1718. // nodes hidden behind it.
  1719. //
  1720. // Never relay transactions that we would assign a non-zero DoS
  1721. // score for, as we expect peers to do the same with us in that
  1722. // case.
  1723. int nDoS = 0;
  1724. if (!state.IsInvalid(nDoS) || nDoS == 0) {
  1725. LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->id);
  1726. RelayTransaction(tx, connman);
  1727. } else {
  1728. LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->id, FormatStateMessage(state));
  1729. }
  1730. }
  1731. }
  1732. for (const CTransactionRef& removedTx : lRemovedTxn)
  1733. AddToCompactExtraTransactions(removedTx);
  1734. int nDoS = 0;
  1735. if (state.IsInvalid(nDoS))
  1736. {
  1737. LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(),
  1738. pfrom->id,
  1739. FormatStateMessage(state));
  1740. if (state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) // Never send AcceptToMemoryPool's internal codes over P2P
  1741. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(),
  1742. state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash));
  1743. if (nDoS > 0) {
  1744. Misbehaving(pfrom->GetId(), nDoS);
  1745. }
  1746. }
  1747. }
  1748. else if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
  1749. {
  1750. CBlockHeaderAndShortTxIDs cmpctblock;
  1751. vRecv >> cmpctblock;
  1752. {
  1753. LOCK(cs_main);
  1754. if (mapBlockIndex.find(cmpctblock.header.hashPrevBlock) == mapBlockIndex.end()) {
  1755. // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
  1756. if (!IsInitialBlockDownload())
  1757. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
  1758. return true;
  1759. }
  1760. }
  1761. const CBlockIndex *pindex = NULL;
  1762. CValidationState state;
  1763. if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) {
  1764. int nDoS;
  1765. if (state.IsInvalid(nDoS)) {
  1766. if (nDoS > 0) {
  1767. LOCK(cs_main);
  1768. Misbehaving(pfrom->GetId(), nDoS);
  1769. }
  1770. LogPrintf("Peer %d sent us invalid header via cmpctblock\n", pfrom->id);
  1771. return true;
  1772. }
  1773. }
  1774. // When we succeed in decoding a block's txids from a cmpctblock
  1775. // message we typically jump to the BLOCKTXN handling code, with a
  1776. // dummy (empty) BLOCKTXN message, to re-use the logic there in
  1777. // completing processing of the putative block (without cs_main).
  1778. bool fProcessBLOCKTXN = false;
  1779. CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION);
  1780. // If we end up treating this as a plain headers message, call that as well
  1781. // without cs_main.
  1782. bool fRevertToHeaderProcessing = false;
  1783. CDataStream vHeadersMsg(SER_NETWORK, PROTOCOL_VERSION);
  1784. // Keep a CBlock for "optimistic" compactblock reconstructions (see
  1785. // below)
  1786. std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
  1787. bool fBlockReconstructed = false;
  1788. {
  1789. LOCK(cs_main);
  1790. // If AcceptBlockHeader returned true, it set pindex
  1791. assert(pindex);
  1792. UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash());
  1793. std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash());
  1794. bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end();
  1795. if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here
  1796. return true;
  1797. if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better
  1798. pindex->nTx != 0) { // We had this block at some point, but pruned it
  1799. if (fAlreadyInFlight) {
  1800. // We requested this block for some reason, but our mempool will probably be useless
  1801. // so we just grab the block via normal getdata
  1802. std::vector<CInv> vInv(1);
  1803. vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
  1804. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
  1805. }
  1806. return true;
  1807. }
  1808. // If we're not close to tip yet, give up and let parallel block fetch work its magic
  1809. if (!fAlreadyInFlight && !CanDirectFetch(chainparams.GetConsensus()))
  1810. return true;
  1811. CNodeState *nodestate = State(pfrom->GetId());
  1812. if (IsWitnessEnabled(pindex->pprev, chainparams.GetConsensus()) && !nodestate->fSupportsDesiredCmpctVersion) {
  1813. // Don't bother trying to process compact blocks from v1 peers
  1814. // after segwit activates.
  1815. return true;
  1816. }
  1817. // We want to be a bit conservative just to be extra careful about DoS
  1818. // possibilities in compact block processing...
  1819. if (pindex->nHeight <= chainActive.Height() + 2) {
  1820. if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
  1821. (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) {
  1822. std::list<QueuedBlock>::iterator* queuedBlockIt = NULL;
  1823. if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), chainparams.GetConsensus(), pindex, &queuedBlockIt)) {
  1824. if (!(*queuedBlockIt)->partialBlock)
  1825. (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool));
  1826. else {
  1827. // The block was already in flight using compact blocks from the same peer
  1828. LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
  1829. return true;
  1830. }
  1831. }
  1832. PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock;
  1833. ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact);
  1834. if (status == READ_STATUS_INVALID) {
  1835. MarkBlockAsReceived(pindex->GetBlockHash()); // Reset in-flight state in case of whitelist
  1836. Misbehaving(pfrom->GetId(), 100);
  1837. LogPrintf("Peer %d sent us invalid compact block\n", pfrom->id);
  1838. return true;
  1839. } else if (status == READ_STATUS_FAILED) {
  1840. // Duplicate txindexes, the block is now in-flight, so just request it
  1841. std::vector<CInv> vInv(1);
  1842. vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
  1843. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
  1844. return true;
  1845. }
  1846. BlockTransactionsRequest req;
  1847. for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) {
  1848. if (!partialBlock.IsTxAvailable(i))
  1849. req.indexes.push_back(i);
  1850. }
  1851. if (req.indexes.empty()) {
  1852. // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions)
  1853. BlockTransactions txn;
  1854. txn.blockhash = cmpctblock.header.GetHash();
  1855. blockTxnMsg << txn;
  1856. fProcessBLOCKTXN = true;
  1857. } else {
  1858. req.blockhash = pindex->GetBlockHash();
  1859. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
  1860. }
  1861. } else {
  1862. // This block is either already in flight from a different
  1863. // peer, or this peer has too many blocks outstanding to
  1864. // download from.
  1865. // Optimistically try to reconstruct anyway since we might be
  1866. // able to without any round trips.
  1867. PartiallyDownloadedBlock tempBlock(&mempool);
  1868. ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
  1869. if (status != READ_STATUS_OK) {
  1870. // TODO: don't ignore failures
  1871. return true;
  1872. }
  1873. std::vector<CTransactionRef> dummy;
  1874. status = tempBlock.FillBlock(*pblock, dummy);
  1875. if (status == READ_STATUS_OK) {
  1876. fBlockReconstructed = true;
  1877. }
  1878. }
  1879. } else {
  1880. if (fAlreadyInFlight) {
  1881. // We requested this block, but its far into the future, so our
  1882. // mempool will probably be useless - request the block normally
  1883. std::vector<CInv> vInv(1);
  1884. vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
  1885. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
  1886. return true;
  1887. } else {
  1888. // If this was an announce-cmpctblock, we want the same treatment as a header message
  1889. // Dirty hack to process as if it were just a headers message (TODO: move message handling into their own functions)
  1890. std::vector<CBlock> headers;
  1891. headers.push_back(cmpctblock.header);
  1892. vHeadersMsg << headers;
  1893. fRevertToHeaderProcessing = true;
  1894. }
  1895. }
  1896. } // cs_main
  1897. if (fProcessBLOCKTXN)
  1898. return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, interruptMsgProc);
  1899. if (fRevertToHeaderProcessing)
  1900. return ProcessMessage(pfrom, NetMsgType::HEADERS, vHeadersMsg, nTimeReceived, chainparams, connman, interruptMsgProc);
  1901. if (fBlockReconstructed) {
  1902. // If we got here, we were able to optimistically reconstruct a
  1903. // block that is in flight from some other peer.
  1904. {
  1905. LOCK(cs_main);
  1906. mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom->GetId(), false));
  1907. }
  1908. bool fNewBlock = false;
  1909. ProcessNewBlock(chainparams, pblock, true, &fNewBlock);
  1910. if (fNewBlock)
  1911. pfrom->nLastBlockTime = GetTime();
  1912. LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid()
  1913. if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) {
  1914. // Clear download state for this block, which is in
  1915. // process from some other peer. We do this after calling
  1916. // ProcessNewBlock so that a malleated cmpctblock announcement
  1917. // can't be used to interfere with block relay.
  1918. MarkBlockAsReceived(pblock->GetHash());
  1919. }
  1920. }
  1921. }
  1922. else if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex) // Ignore blocks received while importing
  1923. {
  1924. BlockTransactions resp;
  1925. vRecv >> resp;
  1926. std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
  1927. bool fBlockRead = false;
  1928. {
  1929. LOCK(cs_main);
  1930. std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash);
  1931. if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock ||
  1932. it->second.first != pfrom->GetId()) {
  1933. LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->id);
  1934. return true;
  1935. }
  1936. PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock;
  1937. ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn);
  1938. if (status == READ_STATUS_INVALID) {
  1939. MarkBlockAsReceived(resp.blockhash); // Reset in-flight state in case of whitelist
  1940. Misbehaving(pfrom->GetId(), 100);
  1941. LogPrintf("Peer %d sent us invalid compact block/non-matching block transactions\n", pfrom->id);
  1942. return true;
  1943. } else if (status == READ_STATUS_FAILED) {
  1944. // Might have collided, fall back to getdata now :(
  1945. std::vector<CInv> invs;
  1946. invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
  1947. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
  1948. } else {
  1949. // Block is either okay, or possibly we received
  1950. // READ_STATUS_CHECKBLOCK_FAILED.
  1951. // Note that CheckBlock can only fail for one of a few reasons:
  1952. // 1. bad-proof-of-work (impossible here, because we've already
  1953. // accepted the header)
  1954. // 2. merkleroot doesn't match the transactions given (already
  1955. // caught in FillBlock with READ_STATUS_FAILED, so
  1956. // impossible here)
  1957. // 3. the block is otherwise invalid (eg invalid coinbase,
  1958. // block is too big, too many legacy sigops, etc).
  1959. // So if CheckBlock failed, #3 is the only possibility.
  1960. // Under BIP 152, we don't DoS-ban unless proof of work is
  1961. // invalid (we don't require all the stateless checks to have
  1962. // been run). This is handled below, so just treat this as
  1963. // though the block was successfully read, and rely on the
  1964. // handling in ProcessNewBlock to ensure the block index is
  1965. // updated, reject messages go out, etc.
  1966. MarkBlockAsReceived(resp.blockhash); // it is now an empty pointer
  1967. fBlockRead = true;
  1968. // mapBlockSource is only used for sending reject messages and DoS scores,
  1969. // so the race between here and cs_main in ProcessNewBlock is fine.
  1970. // BIP 152 permits peers to relay compact blocks after validating
  1971. // the header only; we should not punish peers if the block turns
  1972. // out to be invalid.
  1973. mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom->GetId(), false));
  1974. }
  1975. } // Don't hold cs_main when we call into ProcessNewBlock
  1976. if (fBlockRead) {
  1977. bool fNewBlock = false;
  1978. // Since we requested this block (it was in mapBlocksInFlight), force it to be processed,
  1979. // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc)
  1980. ProcessNewBlock(chainparams, pblock, true, &fNewBlock);
  1981. if (fNewBlock)
  1982. pfrom->nLastBlockTime = GetTime();
  1983. }
  1984. }
  1985. else if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing
  1986. {
  1987. std::vector<CBlockHeader> headers;
  1988. // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
  1989. unsigned int nCount = ReadCompactSize(vRecv);
  1990. if (nCount > MAX_HEADERS_RESULTS) {
  1991. LOCK(cs_main);
  1992. Misbehaving(pfrom->GetId(), 20);
  1993. return error("headers message size = %u", nCount);
  1994. }
  1995. headers.resize(nCount);
  1996. for (unsigned int n = 0; n < nCount; n++) {
  1997. vRecv >> headers[n];
  1998. ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
  1999. }
  2000. if (nCount == 0) {
  2001. // Nothing interesting. Stop asking this peers for more headers.
  2002. return true;
  2003. }
  2004. const CBlockIndex *pindexLast = NULL;
  2005. {
  2006. LOCK(cs_main);
  2007. CNodeState *nodestate = State(pfrom->GetId());
  2008. // If this looks like it could be a block announcement (nCount <
  2009. // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that
  2010. // don't connect:
  2011. // - Send a getheaders message in response to try to connect the chain.
  2012. // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that
  2013. // don't connect before giving DoS points
  2014. // - Once a headers message is received that is valid and does connect,
  2015. // nUnconnectingHeaders gets reset back to 0.
  2016. if (mapBlockIndex.find(headers[0].hashPrevBlock) == mapBlockIndex.end() && nCount < MAX_BLOCKS_TO_ANNOUNCE) {
  2017. nodestate->nUnconnectingHeaders++;
  2018. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256()));
  2019. LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n",
  2020. headers[0].GetHash().ToString(),
  2021. headers[0].hashPrevBlock.ToString(),
  2022. pindexBestHeader->nHeight,
  2023. pfrom->id, nodestate->nUnconnectingHeaders);
  2024. // Set hashLastUnknownBlock for this peer, so that if we
  2025. // eventually get the headers - even from a different peer -
  2026. // we can use this peer to download.
  2027. UpdateBlockAvailability(pfrom->GetId(), headers.back().GetHash());
  2028. if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) {
  2029. Misbehaving(pfrom->GetId(), 20);
  2030. }
  2031. return true;
  2032. }
  2033. uint256 hashLastBlock;
  2034. for (const CBlockHeader& header : headers) {
  2035. if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) {
  2036. Misbehaving(pfrom->GetId(), 20);
  2037. return error("non-continuous headers sequence");
  2038. }
  2039. hashLastBlock = header.GetHash();
  2040. }
  2041. }
  2042. CValidationState state;
  2043. if (!ProcessNewBlockHeaders(headers, state, chainparams, &pindexLast)) {
  2044. int nDoS;
  2045. if (state.IsInvalid(nDoS)) {
  2046. if (nDoS > 0) {
  2047. LOCK(cs_main);
  2048. Misbehaving(pfrom->GetId(), nDoS);
  2049. }
  2050. return error("invalid header received");
  2051. }
  2052. }
  2053. {
  2054. LOCK(cs_main);
  2055. CNodeState *nodestate = State(pfrom->GetId());
  2056. if (nodestate->nUnconnectingHeaders > 0) {
  2057. LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom->id, nodestate->nUnconnectingHeaders);
  2058. }
  2059. nodestate->nUnconnectingHeaders = 0;
  2060. assert(pindexLast);
  2061. UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
  2062. if (nCount == MAX_HEADERS_RESULTS) {
  2063. // Headers message had its maximum size; the peer may have more headers.
  2064. // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
  2065. // from there instead.
  2066. LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
  2067. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256()));
  2068. }
  2069. bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus());
  2070. // If this set of headers is valid and ends in a block with at least as
  2071. // much work as our tip, download as much as possible.
  2072. if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) {
  2073. std::vector<const CBlockIndex*> vToFetch;
  2074. const CBlockIndex *pindexWalk = pindexLast;
  2075. // Calculate all the blocks we'd need to switch to pindexLast, up to a limit.
  2076. while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
  2077. if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) &&
  2078. !mapBlocksInFlight.count(pindexWalk->GetBlockHash()) &&
  2079. (!IsWitnessEnabled(pindexWalk->pprev, chainparams.GetConsensus()) || State(pfrom->GetId())->fHaveWitness)) {
  2080. // We don't have this block, and it's not yet in flight.
  2081. vToFetch.push_back(pindexWalk);
  2082. }
  2083. pindexWalk = pindexWalk->pprev;
  2084. }
  2085. // If pindexWalk still isn't on our main chain, we're looking at a
  2086. // very large reorg at a time we think we're close to caught up to
  2087. // the main chain -- this shouldn't really happen. Bail out on the
  2088. // direct fetch and rely on parallel download instead.
  2089. if (!chainActive.Contains(pindexWalk)) {
  2090. LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n",
  2091. pindexLast->GetBlockHash().ToString(),
  2092. pindexLast->nHeight);
  2093. } else {
  2094. std::vector<CInv> vGetData;
  2095. // Download as much as possible, from earliest to latest.
  2096. BOOST_REVERSE_FOREACH(const CBlockIndex *pindex, vToFetch) {
  2097. if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
  2098. // Can't download any more from this peer
  2099. break;
  2100. }
  2101. uint32_t nFetchFlags = GetFetchFlags(pfrom);
  2102. vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
  2103. MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), chainparams.GetConsensus(), pindex);
  2104. LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n",
  2105. pindex->GetBlockHash().ToString(), pfrom->id);
  2106. }
  2107. if (vGetData.size() > 1) {
  2108. LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n",
  2109. pindexLast->GetBlockHash().ToString(), pindexLast->nHeight);
  2110. }
  2111. if (vGetData.size() > 0) {
  2112. if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) {
  2113. // In any case, we want to download using a compact block, not a regular one
  2114. vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash);
  2115. }
  2116. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData));
  2117. }
  2118. }
  2119. }
  2120. }
  2121. }
  2122. else if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing
  2123. {
  2124. std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
  2125. vRecv >> *pblock;
  2126. LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom->id);
  2127. // Process all blocks from whitelisted peers, even if not requested,
  2128. // unless we're still syncing with the network.
  2129. // Such an unrequested block may still be processed, subject to the
  2130. // conditions in AcceptBlock().
  2131. bool forceProcessing = pfrom->fWhitelisted && !IsInitialBlockDownload();
  2132. const uint256 hash(pblock->GetHash());
  2133. {
  2134. LOCK(cs_main);
  2135. // Also always process if we requested the block explicitly, as we may
  2136. // need it even though it is not a candidate for a new best tip.
  2137. forceProcessing |= MarkBlockAsReceived(hash);
  2138. // mapBlockSource is only used for sending reject messages and DoS scores,
  2139. // so the race between here and cs_main in ProcessNewBlock is fine.
  2140. mapBlockSource.emplace(hash, std::make_pair(pfrom->GetId(), true));
  2141. }
  2142. bool fNewBlock = false;
  2143. ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock);
  2144. if (fNewBlock)
  2145. pfrom->nLastBlockTime = GetTime();
  2146. }
  2147. else if (strCommand == NetMsgType::GETADDR)
  2148. {
  2149. // This asymmetric behavior for inbound and outbound connections was introduced
  2150. // to prevent a fingerprinting attack: an attacker can send specific fake addresses
  2151. // to users' AddrMan and later request them by sending getaddr messages.
  2152. // Making nodes which are behind NAT and can only make outgoing connections ignore
  2153. // the getaddr message mitigates the attack.
  2154. if (!pfrom->fInbound) {
  2155. LogPrint(BCLog::NET, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->id);
  2156. return true;
  2157. }
  2158. // Only send one GetAddr response per connection to reduce resource waste
  2159. // and discourage addr stamping of INV announcements.
  2160. if (pfrom->fSentAddr) {
  2161. LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->id);
  2162. return true;
  2163. }
  2164. pfrom->fSentAddr = true;
  2165. pfrom->vAddrToSend.clear();
  2166. std::vector<CAddress> vAddr = connman.GetAddresses();
  2167. FastRandomContext insecure_rand;
  2168. BOOST_FOREACH(const CAddress &addr, vAddr)
  2169. pfrom->PushAddress(addr, insecure_rand);
  2170. }
  2171. else if (strCommand == NetMsgType::MEMPOOL)
  2172. {
  2173. if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted)
  2174. {
  2175. LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId());
  2176. pfrom->fDisconnect = true;
  2177. return true;
  2178. }
  2179. if (connman.OutboundTargetReached(false) && !pfrom->fWhitelisted)
  2180. {
  2181. LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId());
  2182. pfrom->fDisconnect = true;
  2183. return true;
  2184. }
  2185. LOCK(pfrom->cs_inventory);
  2186. pfrom->fSendMempool = true;
  2187. }
  2188. else if (strCommand == NetMsgType::PING)
  2189. {
  2190. if (pfrom->nVersion > BIP0031_VERSION)
  2191. {
  2192. uint64_t nonce = 0;
  2193. vRecv >> nonce;
  2194. // Echo the message back with the nonce. This allows for two useful features:
  2195. //
  2196. // 1) A remote node can quickly check if the connection is operational
  2197. // 2) Remote nodes can measure the latency of the network thread. If this node
  2198. // is overloaded it won't respond to pings quickly and the remote node can
  2199. // avoid sending us more work, like chain download requests.
  2200. //
  2201. // The nonce stops the remote getting confused between different pings: without
  2202. // it, if the remote node sends a ping once per second and this node takes 5
  2203. // seconds to respond to each, the 5th ping the remote sends would appear to
  2204. // return very quickly.
  2205. connman.PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
  2206. }
  2207. }
  2208. else if (strCommand == NetMsgType::PONG)
  2209. {
  2210. int64_t pingUsecEnd = nTimeReceived;
  2211. uint64_t nonce = 0;
  2212. size_t nAvail = vRecv.in_avail();
  2213. bool bPingFinished = false;
  2214. std::string sProblem;
  2215. if (nAvail >= sizeof(nonce)) {
  2216. vRecv >> nonce;
  2217. // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
  2218. if (pfrom->nPingNonceSent != 0) {
  2219. if (nonce == pfrom->nPingNonceSent) {
  2220. // Matching pong received, this ping is no longer outstanding
  2221. bPingFinished = true;
  2222. int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
  2223. if (pingUsecTime > 0) {
  2224. // Successful ping time measurement, replace previous
  2225. pfrom->nPingUsecTime = pingUsecTime;
  2226. pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime.load(), pingUsecTime);
  2227. } else {
  2228. // This should never happen
  2229. sProblem = "Timing mishap";
  2230. }
  2231. } else {
  2232. // Nonce mismatches are normal when pings are overlapping
  2233. sProblem = "Nonce mismatch";
  2234. if (nonce == 0) {
  2235. // This is most likely a bug in another implementation somewhere; cancel this ping
  2236. bPingFinished = true;
  2237. sProblem = "Nonce zero";
  2238. }
  2239. }
  2240. } else {
  2241. sProblem = "Unsolicited pong without ping";
  2242. }
  2243. } else {
  2244. // This is most likely a bug in another implementation somewhere; cancel this ping
  2245. bPingFinished = true;
  2246. sProblem = "Short payload";
  2247. }
  2248. if (!(sProblem.empty())) {
  2249. LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n",
  2250. pfrom->id,
  2251. sProblem,
  2252. pfrom->nPingNonceSent,
  2253. nonce,
  2254. nAvail);
  2255. }
  2256. if (bPingFinished) {
  2257. pfrom->nPingNonceSent = 0;
  2258. }
  2259. }
  2260. else if (strCommand == NetMsgType::FILTERLOAD)
  2261. {
  2262. CBloomFilter filter;
  2263. vRecv >> filter;
  2264. if (!filter.IsWithinSizeConstraints())
  2265. {
  2266. // There is no excuse for sending a too-large filter
  2267. LOCK(cs_main);
  2268. Misbehaving(pfrom->GetId(), 100);
  2269. }
  2270. else
  2271. {
  2272. LOCK(pfrom->cs_filter);
  2273. delete pfrom->pfilter;
  2274. pfrom->pfilter = new CBloomFilter(filter);
  2275. pfrom->pfilter->UpdateEmptyFull();
  2276. pfrom->fRelayTxes = true;
  2277. }
  2278. }
  2279. else if (strCommand == NetMsgType::FILTERADD)
  2280. {
  2281. std::vector<unsigned char> vData;
  2282. vRecv >> vData;
  2283. // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
  2284. // and thus, the maximum size any matched object can have) in a filteradd message
  2285. bool bad = false;
  2286. if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
  2287. bad = true;
  2288. } else {
  2289. LOCK(pfrom->cs_filter);
  2290. if (pfrom->pfilter) {
  2291. pfrom->pfilter->insert(vData);
  2292. } else {
  2293. bad = true;
  2294. }
  2295. }
  2296. if (bad) {
  2297. LOCK(cs_main);
  2298. Misbehaving(pfrom->GetId(), 100);
  2299. }
  2300. }
  2301. else if (strCommand == NetMsgType::FILTERCLEAR)
  2302. {
  2303. LOCK(pfrom->cs_filter);
  2304. if (pfrom->GetLocalServices() & NODE_BLOOM) {
  2305. delete pfrom->pfilter;
  2306. pfrom->pfilter = new CBloomFilter();
  2307. }
  2308. pfrom->fRelayTxes = true;
  2309. }
  2310. else if (strCommand == NetMsgType::FEEFILTER) {
  2311. CAmount newFeeFilter = 0;
  2312. vRecv >> newFeeFilter;
  2313. if (MoneyRange(newFeeFilter)) {
  2314. {
  2315. LOCK(pfrom->cs_feeFilter);
  2316. pfrom->minFeeFilter = newFeeFilter;
  2317. }
  2318. LogPrint(BCLog::NET, "received: feefilter of %s from peer=%d\n", CFeeRate(newFeeFilter).ToString(), pfrom->id);
  2319. }
  2320. }
  2321. else if (strCommand == NetMsgType::NOTFOUND) {
  2322. // We do not care about the NOTFOUND message, but logging an Unknown Command
  2323. // message would be undesirable as we transmit it ourselves.
  2324. }
  2325. else {
  2326. // Ignore unknown commands for extensibility
  2327. LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
  2328. }
  2329. return true;
  2330. }
  2331. static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman& connman)
  2332. {
  2333. AssertLockHeld(cs_main);
  2334. CNodeState &state = *State(pnode->GetId());
  2335. BOOST_FOREACH(const CBlockReject& reject, state.rejects) {
  2336. connman.PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, (std::string)NetMsgType::BLOCK, reject.chRejectCode, reject.strRejectReason, reject.hashBlock));
  2337. }
  2338. state.rejects.clear();
  2339. if (state.fShouldBan) {
  2340. state.fShouldBan = false;
  2341. if (pnode->fWhitelisted)
  2342. LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode->addr.ToString());
  2343. else if (pnode->fAddnode)
  2344. LogPrintf("Warning: not punishing addnoded peer %s!\n", pnode->addr.ToString());
  2345. else {
  2346. pnode->fDisconnect = true;
  2347. if (pnode->addr.IsLocal())
  2348. LogPrintf("Warning: not banning local peer %s!\n", pnode->addr.ToString());
  2349. else
  2350. {
  2351. connman.Ban(pnode->addr, BanReasonNodeMisbehaving);
  2352. }
  2353. }
  2354. return true;
  2355. }
  2356. return false;
  2357. }
  2358. bool ProcessMessages(CNode* pfrom, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
  2359. {
  2360. const CChainParams& chainparams = Params();
  2361. //
  2362. // Message format
  2363. // (4) message start
  2364. // (12) command
  2365. // (4) size
  2366. // (4) checksum
  2367. // (x) data
  2368. //
  2369. bool fMoreWork = false;
  2370. if (!pfrom->vRecvGetData.empty())
  2371. ProcessGetData(pfrom, chainparams.GetConsensus(), connman, interruptMsgProc);
  2372. if (pfrom->fDisconnect)
  2373. return false;
  2374. // this maintains the order of responses
  2375. if (!pfrom->vRecvGetData.empty()) return true;
  2376. // Don't bother if send buffer is too full to respond anyway
  2377. if (pfrom->fPauseSend)
  2378. return false;
  2379. std::list<CNetMessage> msgs;
  2380. {
  2381. LOCK(pfrom->cs_vProcessMsg);
  2382. if (pfrom->vProcessMsg.empty())
  2383. return false;
  2384. // Just take one message
  2385. msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
  2386. pfrom->nProcessQueueSize -= msgs.front().vRecv.size() + CMessageHeader::HEADER_SIZE;
  2387. pfrom->fPauseRecv = pfrom->nProcessQueueSize > connman.GetReceiveFloodSize();
  2388. fMoreWork = !pfrom->vProcessMsg.empty();
  2389. }
  2390. CNetMessage& msg(msgs.front());
  2391. msg.SetVersion(pfrom->GetRecvVersion());
  2392. // Scan for message start
  2393. if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) {
  2394. LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
  2395. pfrom->fDisconnect = true;
  2396. return false;
  2397. }
  2398. // Read header
  2399. CMessageHeader& hdr = msg.hdr;
  2400. if (!hdr.IsValid(chainparams.MessageStart()))
  2401. {
  2402. LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
  2403. return fMoreWork;
  2404. }
  2405. std::string strCommand = hdr.GetCommand();
  2406. // Message size
  2407. unsigned int nMessageSize = hdr.nMessageSize;
  2408. // Checksum
  2409. CDataStream& vRecv = msg.vRecv;
  2410. const uint256& hash = msg.GetMessageHash();
  2411. if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0)
  2412. {
  2413. LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__,
  2414. SanitizeString(strCommand), nMessageSize,
  2415. HexStr(hash.begin(), hash.begin()+CMessageHeader::CHECKSUM_SIZE),
  2416. HexStr(hdr.pchChecksum, hdr.pchChecksum+CMessageHeader::CHECKSUM_SIZE));
  2417. return fMoreWork;
  2418. }
  2419. // Process message
  2420. bool fRet = false;
  2421. try
  2422. {
  2423. fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams, connman, interruptMsgProc);
  2424. if (interruptMsgProc)
  2425. return false;
  2426. if (!pfrom->vRecvGetData.empty())
  2427. fMoreWork = true;
  2428. }
  2429. catch (const std::ios_base::failure& e)
  2430. {
  2431. connman.PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message")));
  2432. if (strstr(e.what(), "end of data"))
  2433. {
  2434. // Allow exceptions from under-length message on vRecv
  2435. LogPrintf("%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
  2436. }
  2437. else if (strstr(e.what(), "size too large"))
  2438. {
  2439. // Allow exceptions from over-long size
  2440. LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
  2441. }
  2442. else if (strstr(e.what(), "non-canonical ReadCompactSize()"))
  2443. {
  2444. // Allow exceptions from non-canonical encoding
  2445. LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
  2446. }
  2447. else
  2448. {
  2449. PrintExceptionContinue(&e, "ProcessMessages()");
  2450. }
  2451. }
  2452. catch (const std::exception& e) {
  2453. PrintExceptionContinue(&e, "ProcessMessages()");
  2454. } catch (...) {
  2455. PrintExceptionContinue(NULL, "ProcessMessages()");
  2456. }
  2457. if (!fRet) {
  2458. LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
  2459. }
  2460. LOCK(cs_main);
  2461. SendRejectsAndCheckIfBanned(pfrom, connman);
  2462. return fMoreWork;
  2463. }
  2464. class CompareInvMempoolOrder
  2465. {
  2466. CTxMemPool *mp;
  2467. public:
  2468. CompareInvMempoolOrder(CTxMemPool *_mempool)
  2469. {
  2470. mp = _mempool;
  2471. }
  2472. bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b)
  2473. {
  2474. /* As std::make_heap produces a max-heap, we want the entries with the
  2475. * fewest ancestors/highest fee to sort later. */
  2476. return mp->CompareDepthAndScore(*b, *a);
  2477. }
  2478. };
  2479. bool SendMessages(CNode* pto, CConnman& connman, const std::atomic<bool>& interruptMsgProc)
  2480. {
  2481. const Consensus::Params& consensusParams = Params().GetConsensus();
  2482. {
  2483. // Don't send anything until the version handshake is complete
  2484. if (!pto->fSuccessfullyConnected || pto->fDisconnect)
  2485. return true;
  2486. // If we get here, the outgoing message serialization version is set and can't change.
  2487. const CNetMsgMaker msgMaker(pto->GetSendVersion());
  2488. //
  2489. // Message: ping
  2490. //
  2491. bool pingSend = false;
  2492. if (pto->fPingQueued) {
  2493. // RPC ping request by user
  2494. pingSend = true;
  2495. }
  2496. if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
  2497. // Ping automatically sent as a latency probe & keepalive.
  2498. pingSend = true;
  2499. }
  2500. if (pingSend) {
  2501. uint64_t nonce = 0;
  2502. while (nonce == 0) {
  2503. GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
  2504. }
  2505. pto->fPingQueued = false;
  2506. pto->nPingUsecStart = GetTimeMicros();
  2507. if (pto->nVersion > BIP0031_VERSION) {
  2508. pto->nPingNonceSent = nonce;
  2509. connman.PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
  2510. } else {
  2511. // Peer is too old to support ping command with nonce, pong will never arrive.
  2512. pto->nPingNonceSent = 0;
  2513. connman.PushMessage(pto, msgMaker.Make(NetMsgType::PING));
  2514. }
  2515. }
  2516. TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
  2517. if (!lockMain)
  2518. return true;
  2519. if (SendRejectsAndCheckIfBanned(pto, connman))
  2520. return true;
  2521. CNodeState &state = *State(pto->GetId());
  2522. // Address refresh broadcast
  2523. int64_t nNow = GetTimeMicros();
  2524. if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
  2525. AdvertiseLocal(pto);
  2526. pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL);
  2527. }
  2528. //
  2529. // Message: addr
  2530. //
  2531. if (pto->nNextAddrSend < nNow) {
  2532. pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL);
  2533. std::vector<CAddress> vAddr;
  2534. vAddr.reserve(pto->vAddrToSend.size());
  2535. BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
  2536. {
  2537. if (!pto->addrKnown.contains(addr.GetKey()))
  2538. {
  2539. pto->addrKnown.insert(addr.GetKey());
  2540. vAddr.push_back(addr);
  2541. // receiver rejects addr messages larger than 1000
  2542. if (vAddr.size() >= 1000)
  2543. {
  2544. connman.PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
  2545. vAddr.clear();
  2546. }
  2547. }
  2548. }
  2549. pto->vAddrToSend.clear();
  2550. if (!vAddr.empty())
  2551. connman.PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
  2552. // we only send the big addr message once
  2553. if (pto->vAddrToSend.capacity() > 40)
  2554. pto->vAddrToSend.shrink_to_fit();
  2555. }
  2556. // Start block sync
  2557. if (pindexBestHeader == NULL)
  2558. pindexBestHeader = chainActive.Tip();
  2559. bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
  2560. if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
  2561. // Only actively request headers from a single peer, unless we're close to today.
  2562. if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
  2563. state.fSyncStarted = true;
  2564. nSyncStarted++;
  2565. const CBlockIndex *pindexStart = pindexBestHeader;
  2566. /* If possible, start at the block preceding the currently
  2567. best known header. This ensures that we always get a
  2568. non-empty list of headers back as long as the peer
  2569. is up-to-date. With a non-empty response, we can initialise
  2570. the peer's known best block. This wouldn't be possible
  2571. if we requested starting at pindexBestHeader and
  2572. got back an empty response. */
  2573. if (pindexStart->pprev)
  2574. pindexStart = pindexStart->pprev;
  2575. LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
  2576. connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256()));
  2577. }
  2578. }
  2579. // Resend wallet transactions that haven't gotten in a block yet
  2580. // Except during reindex, importing and IBD, when old wallet
  2581. // transactions become unconfirmed and spams other nodes.
  2582. if (!fReindex && !fImporting && !IsInitialBlockDownload())
  2583. {
  2584. GetMainSignals().Broadcast(nTimeBestReceived, &connman);
  2585. }
  2586. //
  2587. // Try sending block announcements via headers
  2588. //
  2589. {
  2590. // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our
  2591. // list of block hashes we're relaying, and our peer wants
  2592. // headers announcements, then find the first header
  2593. // not yet known to our peer but would connect, and send.
  2594. // If no header would connect, or if we have too many
  2595. // blocks, or if the peer doesn't want headers, just
  2596. // add all to the inv queue.
  2597. LOCK(pto->cs_inventory);
  2598. std::vector<CBlock> vHeaders;
  2599. bool fRevertToInv = ((!state.fPreferHeaders &&
  2600. (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) ||
  2601. pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE);
  2602. const CBlockIndex *pBestIndex = NULL; // last header queued for delivery
  2603. ProcessBlockAvailability(pto->id); // ensure pindexBestKnownBlock is up-to-date
  2604. if (!fRevertToInv) {
  2605. bool fFoundStartingHeader = false;
  2606. // Try to find first header that our peer doesn't have, and
  2607. // then send all headers past that one. If we come across any
  2608. // headers that aren't on chainActive, give up.
  2609. BOOST_FOREACH(const uint256 &hash, pto->vBlockHashesToAnnounce) {
  2610. BlockMap::iterator mi = mapBlockIndex.find(hash);
  2611. assert(mi != mapBlockIndex.end());
  2612. const CBlockIndex *pindex = mi->second;
  2613. if (chainActive[pindex->nHeight] != pindex) {
  2614. // Bail out if we reorged away from this block
  2615. fRevertToInv = true;
  2616. break;
  2617. }
  2618. if (pBestIndex != NULL && pindex->pprev != pBestIndex) {
  2619. // This means that the list of blocks to announce don't
  2620. // connect to each other.
  2621. // This shouldn't really be possible to hit during
  2622. // regular operation (because reorgs should take us to
  2623. // a chain that has some block not on the prior chain,
  2624. // which should be caught by the prior check), but one
  2625. // way this could happen is by using invalidateblock /
  2626. // reconsiderblock repeatedly on the tip, causing it to
  2627. // be added multiple times to vBlockHashesToAnnounce.
  2628. // Robustly deal with this rare situation by reverting
  2629. // to an inv.
  2630. fRevertToInv = true;
  2631. break;
  2632. }
  2633. pBestIndex = pindex;
  2634. if (fFoundStartingHeader) {
  2635. // add this to the headers message
  2636. vHeaders.push_back(pindex->GetBlockHeader());
  2637. } else if (PeerHasHeader(&state, pindex)) {
  2638. continue; // keep looking for the first new block
  2639. } else if (pindex->pprev == NULL || PeerHasHeader(&state, pindex->pprev)) {
  2640. // Peer doesn't have this header but they do have the prior one.
  2641. // Start sending headers.
  2642. fFoundStartingHeader = true;
  2643. vHeaders.push_back(pindex->GetBlockHeader());
  2644. } else {
  2645. // Peer doesn't have this header or the prior one -- nothing will
  2646. // connect, so bail out.
  2647. fRevertToInv = true;
  2648. break;
  2649. }
  2650. }
  2651. }
  2652. if (!fRevertToInv && !vHeaders.empty()) {
  2653. if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) {
  2654. // We only send up to 1 block as header-and-ids, as otherwise
  2655. // probably means we're doing an initial-ish-sync or they're slow
  2656. LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__,
  2657. vHeaders.front().GetHash().ToString(), pto->id);
  2658. int nSendFlags = state.fWantsCmpctWitness ? 0 : SERIALIZE_TRANSACTION_NO_WITNESS;
  2659. bool fGotBlockFromCache = false;
  2660. {
  2661. LOCK(cs_most_recent_block);
  2662. if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
  2663. if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
  2664. connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
  2665. else {
  2666. CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
  2667. connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
  2668. }
  2669. fGotBlockFromCache = true;
  2670. }
  2671. }
  2672. if (!fGotBlockFromCache) {
  2673. CBlock block;
  2674. bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
  2675. assert(ret);
  2676. CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
  2677. connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
  2678. }
  2679. state.pindexBestHeaderSent = pBestIndex;
  2680. } else if (state.fPreferHeaders) {
  2681. if (vHeaders.size() > 1) {
  2682. LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__,
  2683. vHeaders.size(),
  2684. vHeaders.front().GetHash().ToString(),
  2685. vHeaders.back().GetHash().ToString(), pto->id);
  2686. } else {
  2687. LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
  2688. vHeaders.front().GetHash().ToString(), pto->id);
  2689. }
  2690. connman.PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
  2691. state.pindexBestHeaderSent = pBestIndex;
  2692. } else
  2693. fRevertToInv = true;
  2694. }
  2695. if (fRevertToInv) {
  2696. // If falling back to using an inv, just try to inv the tip.
  2697. // The last entry in vBlockHashesToAnnounce was our tip at some point
  2698. // in the past.
  2699. if (!pto->vBlockHashesToAnnounce.empty()) {
  2700. const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back();
  2701. BlockMap::iterator mi = mapBlockIndex.find(hashToAnnounce);
  2702. assert(mi != mapBlockIndex.end());
  2703. const CBlockIndex *pindex = mi->second;
  2704. // Warn if we're announcing a block that is not on the main chain.
  2705. // This should be very rare and could be optimized out.
  2706. // Just log for now.
  2707. if (chainActive[pindex->nHeight] != pindex) {
  2708. LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n",
  2709. hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString());
  2710. }
  2711. // If the peer's chain has this block, don't inv it back.
  2712. if (!PeerHasHeader(&state, pindex)) {
  2713. pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce));
  2714. LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__,
  2715. pto->id, hashToAnnounce.ToString());
  2716. }
  2717. }
  2718. }
  2719. pto->vBlockHashesToAnnounce.clear();
  2720. }
  2721. //
  2722. // Message: inventory
  2723. //
  2724. std::vector<CInv> vInv;
  2725. {
  2726. LOCK(pto->cs_inventory);
  2727. vInv.reserve(std::max<size_t>(pto->vInventoryBlockToSend.size(), INVENTORY_BROADCAST_MAX));
  2728. // Add blocks
  2729. BOOST_FOREACH(const uint256& hash, pto->vInventoryBlockToSend) {
  2730. vInv.push_back(CInv(MSG_BLOCK, hash));
  2731. if (vInv.size() == MAX_INV_SZ) {
  2732. connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
  2733. vInv.clear();
  2734. }
  2735. }
  2736. pto->vInventoryBlockToSend.clear();
  2737. // Check whether periodic sends should happen
  2738. bool fSendTrickle = pto->fWhitelisted;
  2739. if (pto->nNextInvSend < nNow) {
  2740. fSendTrickle = true;
  2741. // Use half the delay for outbound peers, as there is less privacy concern for them.
  2742. pto->nNextInvSend = PoissonNextSend(nNow, INVENTORY_BROADCAST_INTERVAL >> !pto->fInbound);
  2743. }
  2744. // Time to send but the peer has requested we not relay transactions.
  2745. if (fSendTrickle) {
  2746. LOCK(pto->cs_filter);
  2747. if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear();
  2748. }
  2749. // Respond to BIP35 mempool requests
  2750. if (fSendTrickle && pto->fSendMempool) {
  2751. auto vtxinfo = mempool.infoAll();
  2752. pto->fSendMempool = false;
  2753. CAmount filterrate = 0;
  2754. {
  2755. LOCK(pto->cs_feeFilter);
  2756. filterrate = pto->minFeeFilter;
  2757. }
  2758. LOCK(pto->cs_filter);
  2759. for (const auto& txinfo : vtxinfo) {
  2760. const uint256& hash = txinfo.tx->GetHash();
  2761. CInv inv(MSG_TX, hash);
  2762. pto->setInventoryTxToSend.erase(hash);
  2763. if (filterrate) {
  2764. if (txinfo.feeRate.GetFeePerK() < filterrate)
  2765. continue;
  2766. }
  2767. if (pto->pfilter) {
  2768. if (!pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
  2769. }
  2770. pto->filterInventoryKnown.insert(hash);
  2771. vInv.push_back(inv);
  2772. if (vInv.size() == MAX_INV_SZ) {
  2773. connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
  2774. vInv.clear();
  2775. }
  2776. }
  2777. pto->timeLastMempoolReq = GetTime();
  2778. }
  2779. // Determine transactions to relay
  2780. if (fSendTrickle) {
  2781. // Produce a vector with all candidates for sending
  2782. std::vector<std::set<uint256>::iterator> vInvTx;
  2783. vInvTx.reserve(pto->setInventoryTxToSend.size());
  2784. for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) {
  2785. vInvTx.push_back(it);
  2786. }
  2787. CAmount filterrate = 0;
  2788. {
  2789. LOCK(pto->cs_feeFilter);
  2790. filterrate = pto->minFeeFilter;
  2791. }
  2792. // Topologically and fee-rate sort the inventory we send for privacy and priority reasons.
  2793. // A heap is used so that not all items need sorting if only a few are being sent.
  2794. CompareInvMempoolOrder compareInvMempoolOrder(&mempool);
  2795. std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
  2796. // No reason to drain out at many times the network's capacity,
  2797. // especially since we have many peers and some will draw much shorter delays.
  2798. unsigned int nRelayedTransactions = 0;
  2799. LOCK(pto->cs_filter);
  2800. while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX) {
  2801. // Fetch the top element from the heap
  2802. std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder);
  2803. std::set<uint256>::iterator it = vInvTx.back();
  2804. vInvTx.pop_back();
  2805. uint256 hash = *it;
  2806. // Remove it from the to-be-sent set
  2807. pto->setInventoryTxToSend.erase(it);
  2808. // Check if not in the filter already
  2809. if (pto->filterInventoryKnown.contains(hash)) {
  2810. continue;
  2811. }
  2812. // Not in the mempool anymore? don't bother sending it.
  2813. auto txinfo = mempool.info(hash);
  2814. if (!txinfo.tx) {
  2815. continue;
  2816. }
  2817. if (filterrate && txinfo.feeRate.GetFeePerK() < filterrate) {
  2818. continue;
  2819. }
  2820. if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue;
  2821. // Send
  2822. vInv.push_back(CInv(MSG_TX, hash));
  2823. nRelayedTransactions++;
  2824. {
  2825. // Expire old relay messages
  2826. while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow)
  2827. {
  2828. mapRelay.erase(vRelayExpiration.front().second);
  2829. vRelayExpiration.pop_front();
  2830. }
  2831. auto ret = mapRelay.insert(std::make_pair(hash, std::move(txinfo.tx)));
  2832. if (ret.second) {
  2833. vRelayExpiration.push_back(std::make_pair(nNow + 15 * 60 * 1000000, ret.first));
  2834. }
  2835. }
  2836. if (vInv.size() == MAX_INV_SZ) {
  2837. connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
  2838. vInv.clear();
  2839. }
  2840. pto->filterInventoryKnown.insert(hash);
  2841. }
  2842. }
  2843. }
  2844. if (!vInv.empty())
  2845. connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
  2846. // Detect whether we're stalling
  2847. nNow = GetTimeMicros();
  2848. if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
  2849. // Stalling only triggers when the block download window cannot move. During normal steady state,
  2850. // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
  2851. // should only happen during initial block download.
  2852. LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
  2853. pto->fDisconnect = true;
  2854. return true;
  2855. }
  2856. // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval
  2857. // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout.
  2858. // We compensate for other peers to prevent killing off peers due to our own downstream link
  2859. // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
  2860. // to unreasonably increase our timeout.
  2861. if (state.vBlocksInFlight.size() > 0) {
  2862. QueuedBlock &queuedBlock = state.vBlocksInFlight.front();
  2863. int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0);
  2864. if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) {
  2865. LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->id);
  2866. pto->fDisconnect = true;
  2867. return true;
  2868. }
  2869. }
  2870. //
  2871. // Message: getdata (blocks)
  2872. //
  2873. std::vector<CInv> vGetData;
  2874. if (!pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
  2875. std::vector<const CBlockIndex*> vToDownload;
  2876. NodeId staller = -1;
  2877. FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams);
  2878. BOOST_FOREACH(const CBlockIndex *pindex, vToDownload) {
  2879. uint32_t nFetchFlags = GetFetchFlags(pto);
  2880. vGetData.push_back(CInv(MSG_BLOCK | nFetchFlags, pindex->GetBlockHash()));
  2881. MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), consensusParams, pindex);
  2882. LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
  2883. pindex->nHeight, pto->id);
  2884. }
  2885. if (state.nBlocksInFlight == 0 && staller != -1) {
  2886. if (State(staller)->nStallingSince == 0) {
  2887. State(staller)->nStallingSince = nNow;
  2888. LogPrint(BCLog::NET, "Stall started peer=%d\n", staller);
  2889. }
  2890. }
  2891. }
  2892. //
  2893. // Message: getdata (non-blocks)
  2894. //
  2895. while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
  2896. {
  2897. const CInv& inv = (*pto->mapAskFor.begin()).second;
  2898. if (!AlreadyHave(inv))
  2899. {
  2900. LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->id);
  2901. vGetData.push_back(inv);
  2902. if (vGetData.size() >= 1000)
  2903. {
  2904. connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
  2905. vGetData.clear();
  2906. }
  2907. } else {
  2908. //If we're not going to ask, don't expect a response.
  2909. pto->setAskFor.erase(inv.hash);
  2910. }
  2911. pto->mapAskFor.erase(pto->mapAskFor.begin());
  2912. }
  2913. if (!vGetData.empty())
  2914. connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
  2915. //
  2916. // Message: feefilter
  2917. //
  2918. // We don't want white listed peers to filter txs to us if we have -whitelistforcerelay
  2919. if (pto->nVersion >= FEEFILTER_VERSION && GetBoolArg("-feefilter", DEFAULT_FEEFILTER) &&
  2920. !(pto->fWhitelisted && GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY))) {
  2921. CAmount currentFilter = mempool.GetMinFee(GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFeePerK();
  2922. int64_t timeNow = GetTimeMicros();
  2923. if (timeNow > pto->nextSendTimeFeeFilter) {
  2924. static CFeeRate default_feerate(DEFAULT_MIN_RELAY_TX_FEE);
  2925. static FeeFilterRounder filterRounder(default_feerate);
  2926. CAmount filterToSend = filterRounder.round(currentFilter);
  2927. // We always have a fee filter of at least minRelayTxFee
  2928. filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
  2929. if (filterToSend != pto->lastSentFeeFilter) {
  2930. connman.PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
  2931. pto->lastSentFeeFilter = filterToSend;
  2932. }
  2933. pto->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);
  2934. }
  2935. // If the fee filter has changed substantially and it's still more than MAX_FEEFILTER_CHANGE_DELAY
  2936. // until scheduled broadcast, then move the broadcast to within MAX_FEEFILTER_CHANGE_DELAY.
  2937. else if (timeNow + MAX_FEEFILTER_CHANGE_DELAY * 1000000 < pto->nextSendTimeFeeFilter &&
  2938. (currentFilter < 3 * pto->lastSentFeeFilter / 4 || currentFilter > 4 * pto->lastSentFeeFilter / 3)) {
  2939. pto->nextSendTimeFeeFilter = timeNow + GetRandInt(MAX_FEEFILTER_CHANGE_DELAY) * 1000000;
  2940. }
  2941. }
  2942. }
  2943. return true;
  2944. }
  2945. class CNetProcessingCleanup
  2946. {
  2947. public:
  2948. CNetProcessingCleanup() {}
  2949. ~CNetProcessingCleanup() {
  2950. // orphan transactions
  2951. mapOrphanTransactions.clear();
  2952. mapOrphanTransactionsByPrev.clear();
  2953. }
  2954. } instance_of_cnetprocessingcleanup;