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 149KB

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