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

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