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.

main.cpp 179KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 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 "main.h"
  6. #include "arith_uint256.h"
  7. #include "addrman.h"
  8. #include "alert.h"
  9. #include "chainparams.h"
  10. #include "checkpoints.h"
  11. #include "checkqueue.h"
  12. #include "init.h"
  13. #include "merkleblock.h"
  14. #include "net.h"
  15. #include "pow.h"
  16. #include "txdb.h"
  17. #include "txmempool.h"
  18. #include "ui_interface.h"
  19. #include "undo.h"
  20. #include "util.h"
  21. #include "utilmoneystr.h"
  22. #include <sstream>
  23. #include <boost/algorithm/string/replace.hpp>
  24. #include <boost/filesystem.hpp>
  25. #include <boost/filesystem/fstream.hpp>
  26. #include <boost/thread.hpp>
  27. using namespace std;
  28. #if defined(NDEBUG)
  29. # error "Bitcoin cannot be compiled without assertions."
  30. #endif
  31. /**
  32. * Global state
  33. */
  34. CCriticalSection cs_main;
  35. BlockMap mapBlockIndex;
  36. CChain chainActive;
  37. CBlockIndex *pindexBestHeader = NULL;
  38. int64_t nTimeBestReceived = 0;
  39. CWaitableCriticalSection csBestBlock;
  40. CConditionVariable cvBlockChange;
  41. int nScriptCheckThreads = 0;
  42. bool fImporting = false;
  43. bool fReindex = false;
  44. bool fTxIndex = false;
  45. bool fIsBareMultisigStd = true;
  46. unsigned int nCoinCacheSize = 5000;
  47. /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
  48. CFeeRate minRelayTxFee = CFeeRate(1000);
  49. CTxMemPool mempool(::minRelayTxFee);
  50. struct COrphanTx {
  51. CTransaction tx;
  52. NodeId fromPeer;
  53. };
  54. map<uint256, COrphanTx> mapOrphanTransactions;
  55. map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
  56. void EraseOrphansFor(NodeId peer);
  57. /**
  58. * Returns true if there are nRequired or more blocks of minVersion or above
  59. * in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart
  60. * and going backwards.
  61. */
  62. static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired);
  63. /** Constant stuff for coinbase transactions we create: */
  64. CScript COINBASE_FLAGS;
  65. const string strMessageMagic = "Bitcoin Signed Message:\n";
  66. // Internal stuff
  67. namespace {
  68. struct CBlockIndexWorkComparator
  69. {
  70. bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
  71. // First sort by most total work, ...
  72. if (pa->nChainWork > pb->nChainWork) return false;
  73. if (pa->nChainWork < pb->nChainWork) return true;
  74. // ... then by earliest time received, ...
  75. if (pa->nSequenceId < pb->nSequenceId) return false;
  76. if (pa->nSequenceId > pb->nSequenceId) return true;
  77. // Use pointer address as tie breaker (should only happen with blocks
  78. // loaded from disk, as those all have id 0).
  79. if (pa < pb) return false;
  80. if (pa > pb) return true;
  81. // Identical blocks.
  82. return false;
  83. }
  84. };
  85. CBlockIndex *pindexBestInvalid;
  86. /**
  87. * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS or better that are at least
  88. * as good as our current tip. Entries may be failed, though.
  89. */
  90. set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
  91. /** Number of nodes with fSyncStarted. */
  92. int nSyncStarted = 0;
  93. /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions. */
  94. multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
  95. CCriticalSection cs_LastBlockFile;
  96. std::vector<CBlockFileInfo> vinfoBlockFile;
  97. int nLastBlockFile = 0;
  98. /**
  99. * Every received block is assigned a unique and increasing identifier, so we
  100. * know which one to give priority in case of a fork.
  101. */
  102. CCriticalSection cs_nBlockSequenceId;
  103. /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
  104. uint32_t nBlockSequenceId = 1;
  105. /**
  106. * Sources of received blocks, to be able to send them reject messages or ban
  107. * them, if processing happens afterwards. Protected by cs_main.
  108. */
  109. map<uint256, NodeId> mapBlockSource;
  110. /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
  111. struct QueuedBlock {
  112. uint256 hash;
  113. CBlockIndex *pindex; //! Optional.
  114. int64_t nTime; //! Time of "getdata" request in microseconds.
  115. int nValidatedQueuedBefore; //! Number of blocks queued with validated headers (globally) at the time this one is requested.
  116. bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
  117. };
  118. map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
  119. /** Number of blocks in flight with validated headers. */
  120. int nQueuedValidatedHeaders = 0;
  121. /** Number of preferable block download peers. */
  122. int nPreferredDownload = 0;
  123. /** Dirty block index entries. */
  124. set<CBlockIndex*> setDirtyBlockIndex;
  125. /** Dirty block file entries. */
  126. set<int> setDirtyFileInfo;
  127. } // anon namespace
  128. //////////////////////////////////////////////////////////////////////////////
  129. //
  130. // dispatching functions
  131. //
  132. // These functions dispatch to one or all registered wallets
  133. namespace {
  134. struct CMainSignals {
  135. /** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */
  136. boost::signals2::signal<void (const CTransaction &, const CBlock *)> SyncTransaction;
  137. /** Notifies listeners of an erased transaction (currently disabled, requires transaction replacement). */
  138. boost::signals2::signal<void (const uint256 &)> EraseTransaction;
  139. /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */
  140. boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
  141. /** Notifies listeners of a new active block chain. */
  142. boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
  143. /** Notifies listeners about an inventory item being seen on the network. */
  144. boost::signals2::signal<void (const uint256 &)> Inventory;
  145. /** Tells listeners to broadcast their data. */
  146. boost::signals2::signal<void ()> Broadcast;
  147. /** Notifies listeners of a block validation result */
  148. boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked;
  149. } g_signals;
  150. } // anon namespace
  151. void RegisterValidationInterface(CValidationInterface* pwalletIn) {
  152. g_signals.SyncTransaction.connect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
  153. g_signals.EraseTransaction.connect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
  154. g_signals.UpdatedTransaction.connect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
  155. g_signals.SetBestChain.connect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
  156. g_signals.Inventory.connect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
  157. g_signals.Broadcast.connect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
  158. g_signals.BlockChecked.connect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
  159. }
  160. void UnregisterValidationInterface(CValidationInterface* pwalletIn) {
  161. g_signals.BlockChecked.disconnect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
  162. g_signals.Broadcast.disconnect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
  163. g_signals.Inventory.disconnect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
  164. g_signals.SetBestChain.disconnect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
  165. g_signals.UpdatedTransaction.disconnect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
  166. g_signals.EraseTransaction.disconnect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
  167. g_signals.SyncTransaction.disconnect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
  168. }
  169. void UnregisterAllValidationInterfaces() {
  170. g_signals.BlockChecked.disconnect_all_slots();
  171. g_signals.Broadcast.disconnect_all_slots();
  172. g_signals.Inventory.disconnect_all_slots();
  173. g_signals.SetBestChain.disconnect_all_slots();
  174. g_signals.UpdatedTransaction.disconnect_all_slots();
  175. g_signals.EraseTransaction.disconnect_all_slots();
  176. g_signals.SyncTransaction.disconnect_all_slots();
  177. }
  178. void SyncWithWallets(const CTransaction &tx, const CBlock *pblock) {
  179. g_signals.SyncTransaction(tx, pblock);
  180. }
  181. //////////////////////////////////////////////////////////////////////////////
  182. //
  183. // Registration of network node signals.
  184. //
  185. namespace {
  186. struct CBlockReject {
  187. unsigned char chRejectCode;
  188. string strRejectReason;
  189. uint256 hashBlock;
  190. };
  191. /**
  192. * Maintain validation-specific state about nodes, protected by cs_main, instead
  193. * by CNode's own locks. This simplifies asynchronous operation, where
  194. * processing of incoming data is done after the ProcessMessage call returns,
  195. * and we're no longer holding the node's locks.
  196. */
  197. struct CNodeState {
  198. //! Accumulated misbehaviour score for this peer.
  199. int nMisbehavior;
  200. //! Whether this peer should be disconnected and banned (unless whitelisted).
  201. bool fShouldBan;
  202. //! String name of this peer (debugging/logging purposes).
  203. std::string name;
  204. //! List of asynchronously-determined block rejections to notify this peer about.
  205. std::vector<CBlockReject> rejects;
  206. //! The best known block we know this peer has announced.
  207. CBlockIndex *pindexBestKnownBlock;
  208. //! The hash of the last unknown block this peer has announced.
  209. uint256 hashLastUnknownBlock;
  210. //! The last full block we both have.
  211. CBlockIndex *pindexLastCommonBlock;
  212. //! Whether we've started headers synchronization with this peer.
  213. bool fSyncStarted;
  214. //! Since when we're stalling block download progress (in microseconds), or 0.
  215. int64_t nStallingSince;
  216. list<QueuedBlock> vBlocksInFlight;
  217. int nBlocksInFlight;
  218. //! Whether we consider this a preferred download peer.
  219. bool fPreferredDownload;
  220. CNodeState() {
  221. nMisbehavior = 0;
  222. fShouldBan = false;
  223. pindexBestKnownBlock = NULL;
  224. hashLastUnknownBlock.SetNull();
  225. pindexLastCommonBlock = NULL;
  226. fSyncStarted = false;
  227. nStallingSince = 0;
  228. nBlocksInFlight = 0;
  229. fPreferredDownload = false;
  230. }
  231. };
  232. /** Map maintaining per-node state. Requires cs_main. */
  233. map<NodeId, CNodeState> mapNodeState;
  234. // Requires cs_main.
  235. CNodeState *State(NodeId pnode) {
  236. map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
  237. if (it == mapNodeState.end())
  238. return NULL;
  239. return &it->second;
  240. }
  241. int GetHeight()
  242. {
  243. LOCK(cs_main);
  244. return chainActive.Height();
  245. }
  246. void UpdatePreferredDownload(CNode* node, CNodeState* state)
  247. {
  248. nPreferredDownload -= state->fPreferredDownload;
  249. // Whether this node should be marked as a preferred download node.
  250. state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
  251. nPreferredDownload += state->fPreferredDownload;
  252. }
  253. void InitializeNode(NodeId nodeid, const CNode *pnode) {
  254. LOCK(cs_main);
  255. CNodeState &state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
  256. state.name = pnode->addrName;
  257. }
  258. void FinalizeNode(NodeId nodeid) {
  259. LOCK(cs_main);
  260. CNodeState *state = State(nodeid);
  261. if (state->fSyncStarted)
  262. nSyncStarted--;
  263. BOOST_FOREACH(const QueuedBlock& entry, state->vBlocksInFlight)
  264. mapBlocksInFlight.erase(entry.hash);
  265. EraseOrphansFor(nodeid);
  266. nPreferredDownload -= state->fPreferredDownload;
  267. mapNodeState.erase(nodeid);
  268. }
  269. // Requires cs_main.
  270. void MarkBlockAsReceived(const uint256& hash) {
  271. map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
  272. if (itInFlight != mapBlocksInFlight.end()) {
  273. CNodeState *state = State(itInFlight->second.first);
  274. nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
  275. state->vBlocksInFlight.erase(itInFlight->second.second);
  276. state->nBlocksInFlight--;
  277. state->nStallingSince = 0;
  278. mapBlocksInFlight.erase(itInFlight);
  279. }
  280. }
  281. // Requires cs_main.
  282. void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex *pindex = NULL) {
  283. CNodeState *state = State(nodeid);
  284. assert(state != NULL);
  285. // Make sure it's not listed somewhere already.
  286. MarkBlockAsReceived(hash);
  287. QueuedBlock newentry = {hash, pindex, GetTimeMicros(), nQueuedValidatedHeaders, pindex != NULL};
  288. nQueuedValidatedHeaders += newentry.fValidatedHeaders;
  289. list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
  290. state->nBlocksInFlight++;
  291. mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
  292. }
  293. /** Check whether the last unknown block a peer advertized is not yet known. */
  294. void ProcessBlockAvailability(NodeId nodeid) {
  295. CNodeState *state = State(nodeid);
  296. assert(state != NULL);
  297. if (!state->hashLastUnknownBlock.IsNull()) {
  298. BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
  299. if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
  300. if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
  301. state->pindexBestKnownBlock = itOld->second;
  302. state->hashLastUnknownBlock.SetNull();
  303. }
  304. }
  305. }
  306. /** Update tracking information about which blocks a peer is assumed to have. */
  307. void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) {
  308. CNodeState *state = State(nodeid);
  309. assert(state != NULL);
  310. ProcessBlockAvailability(nodeid);
  311. BlockMap::iterator it = mapBlockIndex.find(hash);
  312. if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
  313. // An actually better block was announced.
  314. if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
  315. state->pindexBestKnownBlock = it->second;
  316. } else {
  317. // An unknown block was announced; just assume that the latest one is the best one.
  318. state->hashLastUnknownBlock = hash;
  319. }
  320. }
  321. /** Find the last common ancestor two blocks have.
  322. * Both pa and pb must be non-NULL. */
  323. CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) {
  324. if (pa->nHeight > pb->nHeight) {
  325. pa = pa->GetAncestor(pb->nHeight);
  326. } else if (pb->nHeight > pa->nHeight) {
  327. pb = pb->GetAncestor(pa->nHeight);
  328. }
  329. while (pa != pb && pa && pb) {
  330. pa = pa->pprev;
  331. pb = pb->pprev;
  332. }
  333. // Eventually all chain branches meet at the genesis block.
  334. assert(pa == pb);
  335. return pa;
  336. }
  337. /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
  338. * at most count entries. */
  339. void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) {
  340. if (count == 0)
  341. return;
  342. vBlocks.reserve(vBlocks.size() + count);
  343. CNodeState *state = State(nodeid);
  344. assert(state != NULL);
  345. // Make sure pindexBestKnownBlock is up to date, we'll need it.
  346. ProcessBlockAvailability(nodeid);
  347. if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
  348. // This peer has nothing interesting.
  349. return;
  350. }
  351. if (state->pindexLastCommonBlock == NULL) {
  352. // Bootstrap quickly by guessing a parent of our best tip is the forking point.
  353. // Guessing wrong in either direction is not a problem.
  354. state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
  355. }
  356. // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
  357. // of their current tip anymore. Go back enough to fix that.
  358. state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
  359. if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
  360. return;
  361. std::vector<CBlockIndex*> vToFetch;
  362. CBlockIndex *pindexWalk = state->pindexLastCommonBlock;
  363. // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
  364. // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
  365. // download that next block if the window were 1 larger.
  366. int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
  367. int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
  368. NodeId waitingfor = -1;
  369. while (pindexWalk->nHeight < nMaxHeight) {
  370. // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
  371. // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
  372. // as iterating over ~100 CBlockIndex* entries anyway.
  373. int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
  374. vToFetch.resize(nToFetch);
  375. pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
  376. vToFetch[nToFetch - 1] = pindexWalk;
  377. for (unsigned int i = nToFetch - 1; i > 0; i--) {
  378. vToFetch[i - 1] = vToFetch[i]->pprev;
  379. }
  380. // Iterate over those blocks in vToFetch (in forward direction), adding the ones that
  381. // are not yet downloaded and not in flight to vBlocks. In the mean time, update
  382. // pindexLastCommonBlock as long as all ancestors are already downloaded.
  383. BOOST_FOREACH(CBlockIndex* pindex, vToFetch) {
  384. if (!pindex->IsValid(BLOCK_VALID_TREE)) {
  385. // We consider the chain that this peer is on invalid.
  386. return;
  387. }
  388. if (pindex->nStatus & BLOCK_HAVE_DATA) {
  389. if (pindex->nChainTx)
  390. state->pindexLastCommonBlock = pindex;
  391. } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
  392. // The block is not already downloaded, and not yet in flight.
  393. if (pindex->nHeight > nWindowEnd) {
  394. // We reached the end of the window.
  395. if (vBlocks.size() == 0 && waitingfor != nodeid) {
  396. // We aren't able to fetch anything, but we would be if the download window was one larger.
  397. nodeStaller = waitingfor;
  398. }
  399. return;
  400. }
  401. vBlocks.push_back(pindex);
  402. if (vBlocks.size() == count) {
  403. return;
  404. }
  405. } else if (waitingfor == -1) {
  406. // This is the first already-in-flight block.
  407. waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
  408. }
  409. }
  410. }
  411. }
  412. } // anon namespace
  413. bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) {
  414. LOCK(cs_main);
  415. CNodeState *state = State(nodeid);
  416. if (state == NULL)
  417. return false;
  418. stats.nMisbehavior = state->nMisbehavior;
  419. stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
  420. stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
  421. BOOST_FOREACH(const QueuedBlock& queue, state->vBlocksInFlight) {
  422. if (queue.pindex)
  423. stats.vHeightInFlight.push_back(queue.pindex->nHeight);
  424. }
  425. return true;
  426. }
  427. void RegisterNodeSignals(CNodeSignals& nodeSignals)
  428. {
  429. nodeSignals.GetHeight.connect(&GetHeight);
  430. nodeSignals.ProcessMessages.connect(&ProcessMessages);
  431. nodeSignals.SendMessages.connect(&SendMessages);
  432. nodeSignals.InitializeNode.connect(&InitializeNode);
  433. nodeSignals.FinalizeNode.connect(&FinalizeNode);
  434. }
  435. void UnregisterNodeSignals(CNodeSignals& nodeSignals)
  436. {
  437. nodeSignals.GetHeight.disconnect(&GetHeight);
  438. nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
  439. nodeSignals.SendMessages.disconnect(&SendMessages);
  440. nodeSignals.InitializeNode.disconnect(&InitializeNode);
  441. nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
  442. }
  443. CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
  444. {
  445. // Find the first block the caller has in the main chain
  446. BOOST_FOREACH(const uint256& hash, locator.vHave) {
  447. BlockMap::iterator mi = mapBlockIndex.find(hash);
  448. if (mi != mapBlockIndex.end())
  449. {
  450. CBlockIndex* pindex = (*mi).second;
  451. if (chain.Contains(pindex))
  452. return pindex;
  453. }
  454. }
  455. return chain.Genesis();
  456. }
  457. CCoinsViewCache *pcoinsTip = NULL;
  458. CBlockTreeDB *pblocktree = NULL;
  459. //////////////////////////////////////////////////////////////////////////////
  460. //
  461. // mapOrphanTransactions
  462. //
  463. bool AddOrphanTx(const CTransaction& tx, NodeId peer)
  464. {
  465. uint256 hash = tx.GetHash();
  466. if (mapOrphanTransactions.count(hash))
  467. return false;
  468. // Ignore big transactions, to avoid a
  469. // send-big-orphans memory exhaustion attack. If a peer has a legitimate
  470. // large transaction with a missing parent then we assume
  471. // it will rebroadcast it later, after the parent transaction(s)
  472. // have been mined or received.
  473. // 10,000 orphans, each of which is at most 5,000 bytes big is
  474. // at most 500 megabytes of orphans:
  475. unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
  476. if (sz > 5000)
  477. {
  478. LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
  479. return false;
  480. }
  481. mapOrphanTransactions[hash].tx = tx;
  482. mapOrphanTransactions[hash].fromPeer = peer;
  483. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  484. mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
  485. LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
  486. mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
  487. return true;
  488. }
  489. void static EraseOrphanTx(uint256 hash)
  490. {
  491. map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
  492. if (it == mapOrphanTransactions.end())
  493. return;
  494. BOOST_FOREACH(const CTxIn& txin, it->second.tx.vin)
  495. {
  496. map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
  497. if (itPrev == mapOrphanTransactionsByPrev.end())
  498. continue;
  499. itPrev->second.erase(hash);
  500. if (itPrev->second.empty())
  501. mapOrphanTransactionsByPrev.erase(itPrev);
  502. }
  503. mapOrphanTransactions.erase(it);
  504. }
  505. void EraseOrphansFor(NodeId peer)
  506. {
  507. int nErased = 0;
  508. map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
  509. while (iter != mapOrphanTransactions.end())
  510. {
  511. map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
  512. if (maybeErase->second.fromPeer == peer)
  513. {
  514. EraseOrphanTx(maybeErase->second.tx.GetHash());
  515. ++nErased;
  516. }
  517. }
  518. if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
  519. }
  520. unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
  521. {
  522. unsigned int nEvicted = 0;
  523. while (mapOrphanTransactions.size() > nMaxOrphans)
  524. {
  525. // Evict a random orphan:
  526. uint256 randomhash = GetRandHash();
  527. map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
  528. if (it == mapOrphanTransactions.end())
  529. it = mapOrphanTransactions.begin();
  530. EraseOrphanTx(it->first);
  531. ++nEvicted;
  532. }
  533. return nEvicted;
  534. }
  535. bool IsStandardTx(const CTransaction& tx, string& reason)
  536. {
  537. if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
  538. reason = "version";
  539. return false;
  540. }
  541. // Extremely large transactions with lots of inputs can cost the network
  542. // almost as much to process as they cost the sender in fees, because
  543. // computing signature hashes is O(ninputs*txsize). Limiting transactions
  544. // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
  545. unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
  546. if (sz >= MAX_STANDARD_TX_SIZE) {
  547. reason = "tx-size";
  548. return false;
  549. }
  550. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  551. {
  552. // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
  553. // keys. (remember the 520 byte limit on redeemScript size) That works
  554. // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
  555. // bytes of scriptSig, which we round off to 1650 bytes for some minor
  556. // future-proofing. That's also enough to spend a 20-of-20
  557. // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
  558. // considered standard)
  559. if (txin.scriptSig.size() > 1650) {
  560. reason = "scriptsig-size";
  561. return false;
  562. }
  563. if (!txin.scriptSig.IsPushOnly()) {
  564. reason = "scriptsig-not-pushonly";
  565. return false;
  566. }
  567. }
  568. unsigned int nDataOut = 0;
  569. txnouttype whichType;
  570. BOOST_FOREACH(const CTxOut& txout, tx.vout) {
  571. if (!::IsStandard(txout.scriptPubKey, whichType)) {
  572. reason = "scriptpubkey";
  573. return false;
  574. }
  575. if (whichType == TX_NULL_DATA)
  576. nDataOut++;
  577. else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
  578. reason = "bare-multisig";
  579. return false;
  580. } else if (txout.IsDust(::minRelayTxFee)) {
  581. reason = "dust";
  582. return false;
  583. }
  584. }
  585. // only one OP_RETURN txout is permitted
  586. if (nDataOut > 1) {
  587. reason = "multi-op-return";
  588. return false;
  589. }
  590. return true;
  591. }
  592. bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
  593. {
  594. AssertLockHeld(cs_main);
  595. // Time based nLockTime implemented in 0.1.6
  596. if (tx.nLockTime == 0)
  597. return true;
  598. if (nBlockHeight == 0)
  599. nBlockHeight = chainActive.Height();
  600. if (nBlockTime == 0)
  601. nBlockTime = GetAdjustedTime();
  602. if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
  603. return true;
  604. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  605. if (!txin.IsFinal())
  606. return false;
  607. return true;
  608. }
  609. /**
  610. * Check transaction inputs to mitigate two
  611. * potential denial-of-service attacks:
  612. *
  613. * 1. scriptSigs with extra data stuffed into them,
  614. * not consumed by scriptPubKey (or P2SH script)
  615. * 2. P2SH scripts with a crazy number of expensive
  616. * CHECKSIG/CHECKMULTISIG operations
  617. */
  618. bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
  619. {
  620. if (tx.IsCoinBase())
  621. return true; // Coinbases don't use vin normally
  622. for (unsigned int i = 0; i < tx.vin.size(); i++)
  623. {
  624. const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
  625. vector<vector<unsigned char> > vSolutions;
  626. txnouttype whichType;
  627. // get the scriptPubKey corresponding to this input:
  628. const CScript& prevScript = prev.scriptPubKey;
  629. if (!Solver(prevScript, whichType, vSolutions))
  630. return false;
  631. int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
  632. if (nArgsExpected < 0)
  633. return false;
  634. // Transactions with extra stuff in their scriptSigs are
  635. // non-standard. Note that this EvalScript() call will
  636. // be quick, because if there are any operations
  637. // beside "push data" in the scriptSig
  638. // IsStandardTx() will have already returned false
  639. // and this method isn't called.
  640. vector<vector<unsigned char> > stack;
  641. if (!EvalScript(stack, tx.vin[i].scriptSig, SCRIPT_VERIFY_NONE, BaseSignatureChecker()))
  642. return false;
  643. if (whichType == TX_SCRIPTHASH)
  644. {
  645. if (stack.empty())
  646. return false;
  647. CScript subscript(stack.back().begin(), stack.back().end());
  648. vector<vector<unsigned char> > vSolutions2;
  649. txnouttype whichType2;
  650. if (Solver(subscript, whichType2, vSolutions2))
  651. {
  652. int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
  653. if (tmpExpected < 0)
  654. return false;
  655. nArgsExpected += tmpExpected;
  656. }
  657. else
  658. {
  659. // Any other Script with less than 15 sigops OK:
  660. unsigned int sigops = subscript.GetSigOpCount(true);
  661. // ... extra data left on the stack after execution is OK, too:
  662. return (sigops <= MAX_P2SH_SIGOPS);
  663. }
  664. }
  665. if (stack.size() != (unsigned int)nArgsExpected)
  666. return false;
  667. }
  668. return true;
  669. }
  670. unsigned int GetLegacySigOpCount(const CTransaction& tx)
  671. {
  672. unsigned int nSigOps = 0;
  673. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  674. {
  675. nSigOps += txin.scriptSig.GetSigOpCount(false);
  676. }
  677. BOOST_FOREACH(const CTxOut& txout, tx.vout)
  678. {
  679. nSigOps += txout.scriptPubKey.GetSigOpCount(false);
  680. }
  681. return nSigOps;
  682. }
  683. unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
  684. {
  685. if (tx.IsCoinBase())
  686. return 0;
  687. unsigned int nSigOps = 0;
  688. for (unsigned int i = 0; i < tx.vin.size(); i++)
  689. {
  690. const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
  691. if (prevout.scriptPubKey.IsPayToScriptHash())
  692. nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
  693. }
  694. return nSigOps;
  695. }
  696. bool CheckTransaction(const CTransaction& tx, CValidationState &state)
  697. {
  698. // Basic checks that don't depend on any context
  699. if (tx.vin.empty())
  700. return state.DoS(10, error("CheckTransaction(): vin empty"),
  701. REJECT_INVALID, "bad-txns-vin-empty");
  702. if (tx.vout.empty())
  703. return state.DoS(10, error("CheckTransaction(): vout empty"),
  704. REJECT_INVALID, "bad-txns-vout-empty");
  705. // Size limits
  706. if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
  707. return state.DoS(100, error("CheckTransaction(): size limits failed"),
  708. REJECT_INVALID, "bad-txns-oversize");
  709. // Check for negative or overflow output values
  710. CAmount nValueOut = 0;
  711. BOOST_FOREACH(const CTxOut& txout, tx.vout)
  712. {
  713. if (txout.nValue < 0)
  714. return state.DoS(100, error("CheckTransaction(): txout.nValue negative"),
  715. REJECT_INVALID, "bad-txns-vout-negative");
  716. if (txout.nValue > MAX_MONEY)
  717. return state.DoS(100, error("CheckTransaction(): txout.nValue too high"),
  718. REJECT_INVALID, "bad-txns-vout-toolarge");
  719. nValueOut += txout.nValue;
  720. if (!MoneyRange(nValueOut))
  721. return state.DoS(100, error("CheckTransaction(): txout total out of range"),
  722. REJECT_INVALID, "bad-txns-txouttotal-toolarge");
  723. }
  724. // Check for duplicate inputs
  725. set<COutPoint> vInOutPoints;
  726. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  727. {
  728. if (vInOutPoints.count(txin.prevout))
  729. return state.DoS(100, error("CheckTransaction(): duplicate inputs"),
  730. REJECT_INVALID, "bad-txns-inputs-duplicate");
  731. vInOutPoints.insert(txin.prevout);
  732. }
  733. if (tx.IsCoinBase())
  734. {
  735. if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
  736. return state.DoS(100, error("CheckTransaction(): coinbase script size"),
  737. REJECT_INVALID, "bad-cb-length");
  738. }
  739. else
  740. {
  741. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  742. if (txin.prevout.IsNull())
  743. return state.DoS(10, error("CheckTransaction(): prevout is null"),
  744. REJECT_INVALID, "bad-txns-prevout-null");
  745. }
  746. return true;
  747. }
  748. CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
  749. {
  750. {
  751. LOCK(mempool.cs);
  752. uint256 hash = tx.GetHash();
  753. double dPriorityDelta = 0;
  754. CAmount nFeeDelta = 0;
  755. mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
  756. if (dPriorityDelta > 0 || nFeeDelta > 0)
  757. return 0;
  758. }
  759. CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
  760. if (fAllowFree)
  761. {
  762. // There is a free transaction area in blocks created by most miners,
  763. // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
  764. // to be considered to fall into this category. We don't want to encourage sending
  765. // multiple transactions instead of one big transaction to avoid fees.
  766. if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
  767. nMinFee = 0;
  768. }
  769. if (!MoneyRange(nMinFee))
  770. nMinFee = MAX_MONEY;
  771. return nMinFee;
  772. }
  773. bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
  774. bool* pfMissingInputs, bool fRejectAbsurdFee)
  775. {
  776. AssertLockHeld(cs_main);
  777. if (pfMissingInputs)
  778. *pfMissingInputs = false;
  779. if (!CheckTransaction(tx, state))
  780. return error("AcceptToMemoryPool: CheckTransaction failed");
  781. // Coinbase is only valid in a block, not as a loose transaction
  782. if (tx.IsCoinBase())
  783. return state.DoS(100, error("AcceptToMemoryPool: coinbase as individual tx"),
  784. REJECT_INVALID, "coinbase");
  785. // Rather not work on nonstandard transactions (unless -testnet/-regtest)
  786. string reason;
  787. if (Params().RequireStandard() && !IsStandardTx(tx, reason))
  788. return state.DoS(0,
  789. error("AcceptToMemoryPool: nonstandard transaction: %s", reason),
  790. REJECT_NONSTANDARD, reason);
  791. // Only accept nLockTime-using transactions that can be mined in the next
  792. // block; we don't want our mempool filled up with transactions that can't
  793. // be mined yet.
  794. //
  795. // However, IsFinalTx() is confusing... Without arguments, it uses
  796. // chainActive.Height() to evaluate nLockTime; when a block is accepted,
  797. // chainActive.Height() is set to the value of nHeight in the block.
  798. // However, when IsFinalTx() is called within CBlock::AcceptBlock(), the
  799. // height of the block *being* evaluated is what is used. Thus if we want
  800. // to know if a transaction can be part of the *next* block, we need to
  801. // call IsFinalTx() with one more than chainActive.Height().
  802. //
  803. // Timestamps on the other hand don't get any special treatment, because we
  804. // can't know what timestamp the next block will have, and there aren't
  805. // timestamp applications where it matters.
  806. if (!IsFinalTx(tx, chainActive.Height() + 1))
  807. return state.DoS(0,
  808. error("AcceptToMemoryPool: non-final"),
  809. REJECT_NONSTANDARD, "non-final");
  810. // is it already in the memory pool?
  811. uint256 hash = tx.GetHash();
  812. if (pool.exists(hash))
  813. return false;
  814. // Check for conflicts with in-memory transactions
  815. {
  816. LOCK(pool.cs); // protect pool.mapNextTx
  817. for (unsigned int i = 0; i < tx.vin.size(); i++)
  818. {
  819. COutPoint outpoint = tx.vin[i].prevout;
  820. if (pool.mapNextTx.count(outpoint))
  821. {
  822. // Disable replacement feature for now
  823. return false;
  824. }
  825. }
  826. }
  827. {
  828. CCoinsView dummy;
  829. CCoinsViewCache view(&dummy);
  830. CAmount nValueIn = 0;
  831. {
  832. LOCK(pool.cs);
  833. CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
  834. view.SetBackend(viewMemPool);
  835. // do we already have it?
  836. if (view.HaveCoins(hash))
  837. return false;
  838. // do all inputs exist?
  839. // Note that this does not check for the presence of actual outputs (see the next check for that),
  840. // only helps filling in pfMissingInputs (to determine missing vs spent).
  841. BOOST_FOREACH(const CTxIn txin, tx.vin) {
  842. if (!view.HaveCoins(txin.prevout.hash)) {
  843. if (pfMissingInputs)
  844. *pfMissingInputs = true;
  845. return false;
  846. }
  847. }
  848. // are the actual inputs available?
  849. if (!view.HaveInputs(tx))
  850. return state.Invalid(error("AcceptToMemoryPool: inputs already spent"),
  851. REJECT_DUPLICATE, "bad-txns-inputs-spent");
  852. // Bring the best block into scope
  853. view.GetBestBlock();
  854. nValueIn = view.GetValueIn(tx);
  855. // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
  856. view.SetBackend(dummy);
  857. }
  858. // Check for non-standard pay-to-script-hash in inputs
  859. if (Params().RequireStandard() && !AreInputsStandard(tx, view))
  860. return error("AcceptToMemoryPool: nonstandard transaction input");
  861. // Check that the transaction doesn't have an excessive number of
  862. // sigops, making it impossible to mine. Since the coinbase transaction
  863. // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
  864. // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
  865. // merely non-standard transaction.
  866. unsigned int nSigOps = GetLegacySigOpCount(tx);
  867. nSigOps += GetP2SHSigOpCount(tx, view);
  868. if (nSigOps > MAX_STANDARD_TX_SIGOPS)
  869. return state.DoS(0,
  870. error("AcceptToMemoryPool: too many sigops %s, %d > %d",
  871. hash.ToString(), nSigOps, MAX_STANDARD_TX_SIGOPS),
  872. REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
  873. CAmount nValueOut = tx.GetValueOut();
  874. CAmount nFees = nValueIn-nValueOut;
  875. double dPriority = view.GetPriority(tx, chainActive.Height());
  876. CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
  877. unsigned int nSize = entry.GetTxSize();
  878. // Don't accept it if it can't get into a block
  879. CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
  880. if (fLimitFree && nFees < txMinFee)
  881. return state.DoS(0, error("AcceptToMemoryPool: not enough fees %s, %d < %d",
  882. hash.ToString(), nFees, txMinFee),
  883. REJECT_INSUFFICIENTFEE, "insufficient fee");
  884. // Require that free transactions have sufficient priority to be mined in the next block.
  885. if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
  886. return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
  887. }
  888. // Continuously rate-limit free (really, very-low-fee) transactions
  889. // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
  890. // be annoying or make others' transactions take longer to confirm.
  891. if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize))
  892. {
  893. static CCriticalSection csFreeLimiter;
  894. static double dFreeCount;
  895. static int64_t nLastTime;
  896. int64_t nNow = GetTime();
  897. LOCK(csFreeLimiter);
  898. // Use an exponentially decaying ~10-minute window:
  899. dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
  900. nLastTime = nNow;
  901. // -limitfreerelay unit is thousand-bytes-per-minute
  902. // At default rate it would take over a month to fill 1GB
  903. if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
  904. return state.DoS(0, error("AcceptToMemoryPool: free transaction rejected by rate limiter"),
  905. REJECT_INSUFFICIENTFEE, "rate limited free transaction");
  906. LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
  907. dFreeCount += nSize;
  908. }
  909. if (fRejectAbsurdFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
  910. return error("AcceptToMemoryPool: absurdly high fees %s, %d > %d",
  911. hash.ToString(),
  912. nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
  913. // Check against previous transactions
  914. // This is done last to help prevent CPU exhaustion denial-of-service attacks.
  915. if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true))
  916. {
  917. return error("AcceptToMemoryPool: ConnectInputs failed %s", hash.ToString());
  918. }
  919. // Check again against just the consensus-critical mandatory script
  920. // verification flags, in case of bugs in the standard flags that cause
  921. // transactions to pass as valid when they're actually invalid. For
  922. // instance the STRICTENC flag was incorrectly allowing certain
  923. // CHECKSIG NOT scripts to pass, even though they were invalid.
  924. //
  925. // There is a similar check in CreateNewBlock() to prevent creating
  926. // invalid blocks, however allowing such transactions into the mempool
  927. // can be exploited as a DoS attack.
  928. if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
  929. {
  930. return error("AcceptToMemoryPool: BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
  931. }
  932. // Store transaction in memory
  933. pool.addUnchecked(hash, entry);
  934. }
  935. SyncWithWallets(tx, NULL);
  936. return true;
  937. }
  938. /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
  939. bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
  940. {
  941. CBlockIndex *pindexSlow = NULL;
  942. {
  943. LOCK(cs_main);
  944. {
  945. if (mempool.lookup(hash, txOut))
  946. {
  947. return true;
  948. }
  949. }
  950. if (fTxIndex) {
  951. CDiskTxPos postx;
  952. if (pblocktree->ReadTxIndex(hash, postx)) {
  953. CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
  954. if (file.IsNull())
  955. return error("%s: OpenBlockFile failed", __func__);
  956. CBlockHeader header;
  957. try {
  958. file >> header;
  959. fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
  960. file >> txOut;
  961. } catch (const std::exception& e) {
  962. return error("%s: Deserialize or I/O error - %s", __func__, e.what());
  963. }
  964. hashBlock = header.GetHash();
  965. if (txOut.GetHash() != hash)
  966. return error("%s: txid mismatch", __func__);
  967. return true;
  968. }
  969. }
  970. if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
  971. int nHeight = -1;
  972. {
  973. CCoinsViewCache &view = *pcoinsTip;
  974. const CCoins* coins = view.AccessCoins(hash);
  975. if (coins)
  976. nHeight = coins->nHeight;
  977. }
  978. if (nHeight > 0)
  979. pindexSlow = chainActive[nHeight];
  980. }
  981. }
  982. if (pindexSlow) {
  983. CBlock block;
  984. if (ReadBlockFromDisk(block, pindexSlow)) {
  985. BOOST_FOREACH(const CTransaction &tx, block.vtx) {
  986. if (tx.GetHash() == hash) {
  987. txOut = tx;
  988. hashBlock = pindexSlow->GetBlockHash();
  989. return true;
  990. }
  991. }
  992. }
  993. }
  994. return false;
  995. }
  996. //////////////////////////////////////////////////////////////////////////////
  997. //
  998. // CBlock and CBlockIndex
  999. //
  1000. bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos)
  1001. {
  1002. // Open history file to append
  1003. CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
  1004. if (fileout.IsNull())
  1005. return error("WriteBlockToDisk: OpenBlockFile failed");
  1006. // Write index header
  1007. unsigned int nSize = fileout.GetSerializeSize(block);
  1008. fileout << FLATDATA(Params().MessageStart()) << nSize;
  1009. // Write block
  1010. long fileOutPos = ftell(fileout.Get());
  1011. if (fileOutPos < 0)
  1012. return error("WriteBlockToDisk: ftell failed");
  1013. pos.nPos = (unsigned int)fileOutPos;
  1014. fileout << block;
  1015. return true;
  1016. }
  1017. bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
  1018. {
  1019. block.SetNull();
  1020. // Open history file to read
  1021. CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
  1022. if (filein.IsNull())
  1023. return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
  1024. // Read block
  1025. try {
  1026. filein >> block;
  1027. }
  1028. catch (const std::exception& e) {
  1029. return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
  1030. }
  1031. // Check the header
  1032. if (!CheckProofOfWork(block.GetHash(), block.nBits))
  1033. return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
  1034. return true;
  1035. }
  1036. bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
  1037. {
  1038. if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
  1039. return false;
  1040. if (block.GetHash() != pindex->GetBlockHash())
  1041. return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
  1042. pindex->ToString(), pindex->GetBlockPos().ToString());
  1043. return true;
  1044. }
  1045. CAmount GetBlockValue(int nHeight, const CAmount& nFees)
  1046. {
  1047. CAmount nSubsidy = 50 * COIN;
  1048. int halvings = nHeight / Params().SubsidyHalvingInterval();
  1049. // Force block reward to zero when right shift is undefined.
  1050. if (halvings >= 64)
  1051. return nFees;
  1052. // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
  1053. nSubsidy >>= halvings;
  1054. return nSubsidy + nFees;
  1055. }
  1056. bool IsInitialBlockDownload()
  1057. {
  1058. LOCK(cs_main);
  1059. if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
  1060. return true;
  1061. static bool lockIBDState = false;
  1062. if (lockIBDState)
  1063. return false;
  1064. bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
  1065. pindexBestHeader->GetBlockTime() < GetTime() - 24 * 60 * 60);
  1066. if (!state)
  1067. lockIBDState = true;
  1068. return state;
  1069. }
  1070. bool fLargeWorkForkFound = false;
  1071. bool fLargeWorkInvalidChainFound = false;
  1072. CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
  1073. void CheckForkWarningConditions()
  1074. {
  1075. AssertLockHeld(cs_main);
  1076. // Before we get past initial download, we cannot reliably alert about forks
  1077. // (we assume we don't get stuck on a fork before the last checkpoint)
  1078. if (IsInitialBlockDownload())
  1079. return;
  1080. // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
  1081. // of our head, drop it
  1082. if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
  1083. pindexBestForkTip = NULL;
  1084. if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
  1085. {
  1086. if (!fLargeWorkForkFound && pindexBestForkBase)
  1087. {
  1088. std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
  1089. pindexBestForkBase->phashBlock->ToString() + std::string("'");
  1090. CAlert::Notify(warning, true);
  1091. }
  1092. if (pindexBestForkTip && pindexBestForkBase)
  1093. {
  1094. LogPrintf("CheckForkWarningConditions: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n",
  1095. pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
  1096. pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
  1097. fLargeWorkForkFound = true;
  1098. }
  1099. else
  1100. {
  1101. LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
  1102. fLargeWorkInvalidChainFound = true;
  1103. }
  1104. }
  1105. else
  1106. {
  1107. fLargeWorkForkFound = false;
  1108. fLargeWorkInvalidChainFound = false;
  1109. }
  1110. }
  1111. void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
  1112. {
  1113. AssertLockHeld(cs_main);
  1114. // If we are on a fork that is sufficiently large, set a warning flag
  1115. CBlockIndex* pfork = pindexNewForkTip;
  1116. CBlockIndex* plonger = chainActive.Tip();
  1117. while (pfork && pfork != plonger)
  1118. {
  1119. while (plonger && plonger->nHeight > pfork->nHeight)
  1120. plonger = plonger->pprev;
  1121. if (pfork == plonger)
  1122. break;
  1123. pfork = pfork->pprev;
  1124. }
  1125. // We define a condition which we should warn the user about as a fork of at least 7 blocks
  1126. // who's tip is within 72 blocks (+/- 12 hours if no one mines it) of ours
  1127. // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
  1128. // hash rate operating on the fork.
  1129. // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
  1130. // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
  1131. // the 7-block condition and from this always have the most-likely-to-cause-warning fork
  1132. if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
  1133. pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
  1134. chainActive.Height() - pindexNewForkTip->nHeight < 72)
  1135. {
  1136. pindexBestForkTip = pindexNewForkTip;
  1137. pindexBestForkBase = pfork;
  1138. }
  1139. CheckForkWarningConditions();
  1140. }
  1141. // Requires cs_main.
  1142. void Misbehaving(NodeId pnode, int howmuch)
  1143. {
  1144. if (howmuch == 0)
  1145. return;
  1146. CNodeState *state = State(pnode);
  1147. if (state == NULL)
  1148. return;
  1149. state->nMisbehavior += howmuch;
  1150. int banscore = GetArg("-banscore", 100);
  1151. if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
  1152. {
  1153. LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
  1154. state->fShouldBan = true;
  1155. } else
  1156. LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
  1157. }
  1158. void static InvalidChainFound(CBlockIndex* pindexNew)
  1159. {
  1160. if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
  1161. pindexBestInvalid = pindexNew;
  1162. LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
  1163. pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
  1164. log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
  1165. pindexNew->GetBlockTime()));
  1166. LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
  1167. chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
  1168. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
  1169. CheckForkWarningConditions();
  1170. }
  1171. void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
  1172. int nDoS = 0;
  1173. if (state.IsInvalid(nDoS)) {
  1174. std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
  1175. if (it != mapBlockSource.end() && State(it->second)) {
  1176. CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
  1177. State(it->second)->rejects.push_back(reject);
  1178. if (nDoS > 0)
  1179. Misbehaving(it->second, nDoS);
  1180. }
  1181. }
  1182. if (!state.CorruptionPossible()) {
  1183. pindex->nStatus |= BLOCK_FAILED_VALID;
  1184. setDirtyBlockIndex.insert(pindex);
  1185. setBlockIndexCandidates.erase(pindex);
  1186. InvalidChainFound(pindex);
  1187. }
  1188. }
  1189. void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
  1190. {
  1191. // mark inputs spent
  1192. if (!tx.IsCoinBase()) {
  1193. txundo.vprevout.reserve(tx.vin.size());
  1194. BOOST_FOREACH(const CTxIn &txin, tx.vin) {
  1195. CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
  1196. unsigned nPos = txin.prevout.n;
  1197. if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
  1198. assert(false);
  1199. // mark an outpoint spent, and construct undo information
  1200. txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
  1201. coins->Spend(nPos);
  1202. if (coins->vout.size() == 0) {
  1203. CTxInUndo& undo = txundo.vprevout.back();
  1204. undo.nHeight = coins->nHeight;
  1205. undo.fCoinBase = coins->fCoinBase;
  1206. undo.nVersion = coins->nVersion;
  1207. }
  1208. }
  1209. }
  1210. // add outputs
  1211. inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
  1212. }
  1213. void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
  1214. {
  1215. CTxUndo txundo;
  1216. UpdateCoins(tx, state, inputs, txundo, nHeight);
  1217. }
  1218. bool CScriptCheck::operator()() {
  1219. const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
  1220. if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
  1221. return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
  1222. }
  1223. return true;
  1224. }
  1225. bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
  1226. {
  1227. if (!tx.IsCoinBase())
  1228. {
  1229. if (pvChecks)
  1230. pvChecks->reserve(tx.vin.size());
  1231. // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
  1232. // for an attacker to attempt to split the network.
  1233. if (!inputs.HaveInputs(tx))
  1234. return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
  1235. // While checking, GetBestBlock() refers to the parent block.
  1236. // This is also true for mempool checks.
  1237. CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
  1238. int nSpendHeight = pindexPrev->nHeight + 1;
  1239. CAmount nValueIn = 0;
  1240. CAmount nFees = 0;
  1241. for (unsigned int i = 0; i < tx.vin.size(); i++)
  1242. {
  1243. const COutPoint &prevout = tx.vin[i].prevout;
  1244. const CCoins *coins = inputs.AccessCoins(prevout.hash);
  1245. assert(coins);
  1246. // If prev is coinbase, check that it's matured
  1247. if (coins->IsCoinBase()) {
  1248. if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
  1249. return state.Invalid(
  1250. error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
  1251. REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
  1252. }
  1253. // Check for negative or overflow input values
  1254. nValueIn += coins->vout[prevout.n].nValue;
  1255. if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
  1256. return state.DoS(100, error("CheckInputs(): txin values out of range"),
  1257. REJECT_INVALID, "bad-txns-inputvalues-outofrange");
  1258. }
  1259. if (nValueIn < tx.GetValueOut())
  1260. return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
  1261. tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
  1262. REJECT_INVALID, "bad-txns-in-belowout");
  1263. // Tally transaction fees
  1264. CAmount nTxFee = nValueIn - tx.GetValueOut();
  1265. if (nTxFee < 0)
  1266. return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
  1267. REJECT_INVALID, "bad-txns-fee-negative");
  1268. nFees += nTxFee;
  1269. if (!MoneyRange(nFees))
  1270. return state.DoS(100, error("CheckInputs(): nFees out of range"),
  1271. REJECT_INVALID, "bad-txns-fee-outofrange");
  1272. // The first loop above does all the inexpensive checks.
  1273. // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
  1274. // Helps prevent CPU exhaustion attacks.
  1275. // Skip ECDSA signature verification when connecting blocks
  1276. // before the last block chain checkpoint. This is safe because block merkle hashes are
  1277. // still computed and checked, and any change will be caught at the next checkpoint.
  1278. if (fScriptChecks) {
  1279. for (unsigned int i = 0; i < tx.vin.size(); i++) {
  1280. const COutPoint &prevout = tx.vin[i].prevout;
  1281. const CCoins* coins = inputs.AccessCoins(prevout.hash);
  1282. assert(coins);
  1283. // Verify signature
  1284. CScriptCheck check(*coins, tx, i, flags, cacheStore);
  1285. if (pvChecks) {
  1286. pvChecks->push_back(CScriptCheck());
  1287. check.swap(pvChecks->back());
  1288. } else if (!check()) {
  1289. if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
  1290. // Check whether the failure was caused by a
  1291. // non-mandatory script verification check, such as
  1292. // non-standard DER encodings or non-null dummy
  1293. // arguments; if so, don't trigger DoS protection to
  1294. // avoid splitting the network between upgraded and
  1295. // non-upgraded nodes.
  1296. CScriptCheck check(*coins, tx, i,
  1297. flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
  1298. if (check())
  1299. return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
  1300. }
  1301. // Failures of other flags indicate a transaction that is
  1302. // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
  1303. // such nodes as they are not following the protocol. That
  1304. // said during an upgrade careful thought should be taken
  1305. // as to the correct behavior - we may want to continue
  1306. // peering with non-upgraded nodes even after a soft-fork
  1307. // super-majority vote has passed.
  1308. return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
  1309. }
  1310. }
  1311. }
  1312. }
  1313. return true;
  1314. }
  1315. namespace {
  1316. bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock)
  1317. {
  1318. // Open history file to append
  1319. CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
  1320. if (fileout.IsNull())
  1321. return error("%s: OpenUndoFile failed", __func__);
  1322. // Write index header
  1323. unsigned int nSize = fileout.GetSerializeSize(blockundo);
  1324. fileout << FLATDATA(Params().MessageStart()) << nSize;
  1325. // Write undo data
  1326. long fileOutPos = ftell(fileout.Get());
  1327. if (fileOutPos < 0)
  1328. return error("%s: ftell failed", __func__);
  1329. pos.nPos = (unsigned int)fileOutPos;
  1330. fileout << blockundo;
  1331. // calculate & write checksum
  1332. CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
  1333. hasher << hashBlock;
  1334. hasher << blockundo;
  1335. fileout << hasher.GetHash();
  1336. return true;
  1337. }
  1338. bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
  1339. {
  1340. // Open history file to read
  1341. CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
  1342. if (filein.IsNull())
  1343. return error("%s: OpenBlockFile failed", __func__);
  1344. // Read block
  1345. uint256 hashChecksum;
  1346. try {
  1347. filein >> blockundo;
  1348. filein >> hashChecksum;
  1349. }
  1350. catch (const std::exception& e) {
  1351. return error("%s: Deserialize or I/O error - %s", __func__, e.what());
  1352. }
  1353. // Verify checksum
  1354. CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
  1355. hasher << hashBlock;
  1356. hasher << blockundo;
  1357. if (hashChecksum != hasher.GetHash())
  1358. return error("%s: Checksum mismatch", __func__);
  1359. return true;
  1360. }
  1361. } // anon namespace
  1362. /**
  1363. * Apply the undo operation of a CTxInUndo to the given chain state.
  1364. * @param undo The undo object.
  1365. * @param view The coins view to which to apply the changes.
  1366. * @param out The out point that corresponds to the tx input.
  1367. * @return True on success.
  1368. */
  1369. static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
  1370. {
  1371. bool fClean = true;
  1372. CCoinsModifier coins = view.ModifyCoins(out.hash);
  1373. if (undo.nHeight != 0) {
  1374. // undo data contains height: this is the last output of the prevout tx being spent
  1375. if (!coins->IsPruned())
  1376. fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
  1377. coins->Clear();
  1378. coins->fCoinBase = undo.fCoinBase;
  1379. coins->nHeight = undo.nHeight;
  1380. coins->nVersion = undo.nVersion;
  1381. } else {
  1382. if (coins->IsPruned())
  1383. fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
  1384. }
  1385. if (coins->IsAvailable(out.n))
  1386. fClean = fClean && error("%s: undo data overwriting existing output", __func__);
  1387. if (coins->vout.size() < out.n+1)
  1388. coins->vout.resize(out.n+1);
  1389. coins->vout[out.n] = undo.txout;
  1390. return fClean;
  1391. }
  1392. bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
  1393. {
  1394. assert(pindex->GetBlockHash() == view.GetBestBlock());
  1395. if (pfClean)
  1396. *pfClean = false;
  1397. bool fClean = true;
  1398. CBlockUndo blockUndo;
  1399. CDiskBlockPos pos = pindex->GetUndoPos();
  1400. if (pos.IsNull())
  1401. return error("DisconnectBlock(): no undo data available");
  1402. if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
  1403. return error("DisconnectBlock(): failure reading undo data");
  1404. if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
  1405. return error("DisconnectBlock(): block and undo data inconsistent");
  1406. // undo transactions in reverse order
  1407. for (int i = block.vtx.size() - 1; i >= 0; i--) {
  1408. const CTransaction &tx = block.vtx[i];
  1409. uint256 hash = tx.GetHash();
  1410. // Check that all outputs are available and match the outputs in the block itself
  1411. // exactly.
  1412. {
  1413. CCoinsModifier outs = view.ModifyCoins(hash);
  1414. outs->ClearUnspendable();
  1415. CCoins outsBlock(tx, pindex->nHeight);
  1416. // The CCoins serialization does not serialize negative numbers.
  1417. // No network rules currently depend on the version here, so an inconsistency is harmless
  1418. // but it must be corrected before txout nversion ever influences a network rule.
  1419. if (outsBlock.nVersion < 0)
  1420. outs->nVersion = outsBlock.nVersion;
  1421. if (*outs != outsBlock)
  1422. fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
  1423. // remove outputs
  1424. outs->Clear();
  1425. }
  1426. // restore inputs
  1427. if (i > 0) { // not coinbases
  1428. const CTxUndo &txundo = blockUndo.vtxundo[i-1];
  1429. if (txundo.vprevout.size() != tx.vin.size())
  1430. return error("DisconnectBlock(): transaction and undo data inconsistent");
  1431. for (unsigned int j = tx.vin.size(); j-- > 0;) {
  1432. const COutPoint &out = tx.vin[j].prevout;
  1433. const CTxInUndo &undo = txundo.vprevout[j];
  1434. if (!ApplyTxInUndo(undo, view, out))
  1435. fClean = false;
  1436. }
  1437. }
  1438. }
  1439. // move best block pointer to prevout block
  1440. view.SetBestBlock(pindex->pprev->GetBlockHash());
  1441. if (pfClean) {
  1442. *pfClean = fClean;
  1443. return true;
  1444. }
  1445. return fClean;
  1446. }
  1447. void static FlushBlockFile(bool fFinalize = false)
  1448. {
  1449. LOCK(cs_LastBlockFile);
  1450. CDiskBlockPos posOld(nLastBlockFile, 0);
  1451. FILE *fileOld = OpenBlockFile(posOld);
  1452. if (fileOld) {
  1453. if (fFinalize)
  1454. TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
  1455. FileCommit(fileOld);
  1456. fclose(fileOld);
  1457. }
  1458. fileOld = OpenUndoFile(posOld);
  1459. if (fileOld) {
  1460. if (fFinalize)
  1461. TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
  1462. FileCommit(fileOld);
  1463. fclose(fileOld);
  1464. }
  1465. }
  1466. bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
  1467. static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
  1468. void ThreadScriptCheck() {
  1469. RenameThread("bitcoin-scriptch");
  1470. scriptcheckqueue.Thread();
  1471. }
  1472. static int64_t nTimeVerify = 0;
  1473. static int64_t nTimeConnect = 0;
  1474. static int64_t nTimeIndex = 0;
  1475. static int64_t nTimeCallbacks = 0;
  1476. static int64_t nTimeTotal = 0;
  1477. bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
  1478. {
  1479. AssertLockHeld(cs_main);
  1480. // Check it again in case a previous version let a bad block in
  1481. if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
  1482. return false;
  1483. // verify that the view's current state corresponds to the previous block
  1484. uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
  1485. assert(hashPrevBlock == view.GetBestBlock());
  1486. // Special case for the genesis block, skipping connection of its transactions
  1487. // (its coinbase is unspendable)
  1488. if (block.GetHash() == Params().HashGenesisBlock()) {
  1489. if (!fJustCheck)
  1490. view.SetBestBlock(pindex->GetBlockHash());
  1491. return true;
  1492. }
  1493. bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
  1494. // Do not allow blocks that contain transactions which 'overwrite' older transactions,
  1495. // unless those are already completely spent.
  1496. // If such overwrites are allowed, coinbases and transactions depending upon those
  1497. // can be duplicated to remove the ability to spend the first instance -- even after
  1498. // being sent to another address.
  1499. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
  1500. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
  1501. // already refuses previously-known transaction ids entirely.
  1502. // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
  1503. // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
  1504. // two in the chain that violate it. This prevents exploiting the issue against nodes in their
  1505. // initial block download.
  1506. bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
  1507. !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
  1508. (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
  1509. if (fEnforceBIP30) {
  1510. BOOST_FOREACH(const CTransaction& tx, block.vtx) {
  1511. const CCoins* coins = view.AccessCoins(tx.GetHash());
  1512. if (coins && !coins->IsPruned())
  1513. return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
  1514. REJECT_INVALID, "bad-txns-BIP30");
  1515. }
  1516. }
  1517. // BIP16 didn't become active until Apr 1 2012
  1518. int64_t nBIP16SwitchTime = 1333238400;
  1519. bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
  1520. unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
  1521. // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, when 75% of the network has upgraded:
  1522. if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, Params().EnforceBlockUpgradeMajority())) {
  1523. flags |= SCRIPT_VERIFY_DERSIG;
  1524. }
  1525. CBlockUndo blockundo;
  1526. CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
  1527. int64_t nTimeStart = GetTimeMicros();
  1528. CAmount nFees = 0;
  1529. int nInputs = 0;
  1530. unsigned int nSigOps = 0;
  1531. CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
  1532. std::vector<std::pair<uint256, CDiskTxPos> > vPos;
  1533. vPos.reserve(block.vtx.size());
  1534. blockundo.vtxundo.reserve(block.vtx.size() - 1);
  1535. for (unsigned int i = 0; i < block.vtx.size(); i++)
  1536. {
  1537. const CTransaction &tx = block.vtx[i];
  1538. nInputs += tx.vin.size();
  1539. nSigOps += GetLegacySigOpCount(tx);
  1540. if (nSigOps > MAX_BLOCK_SIGOPS)
  1541. return state.DoS(100, error("ConnectBlock(): too many sigops"),
  1542. REJECT_INVALID, "bad-blk-sigops");
  1543. if (!tx.IsCoinBase())
  1544. {
  1545. if (!view.HaveInputs(tx))
  1546. return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
  1547. REJECT_INVALID, "bad-txns-inputs-missingorspent");
  1548. if (fStrictPayToScriptHash)
  1549. {
  1550. // Add in sigops done by pay-to-script-hash inputs;
  1551. // this is to prevent a "rogue miner" from creating
  1552. // an incredibly-expensive-to-validate block.
  1553. nSigOps += GetP2SHSigOpCount(tx, view);
  1554. if (nSigOps > MAX_BLOCK_SIGOPS)
  1555. return state.DoS(100, error("ConnectBlock(): too many sigops"),
  1556. REJECT_INVALID, "bad-blk-sigops");
  1557. }
  1558. nFees += view.GetValueIn(tx)-tx.GetValueOut();
  1559. std::vector<CScriptCheck> vChecks;
  1560. if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
  1561. return false;
  1562. control.Add(vChecks);
  1563. }
  1564. CTxUndo undoDummy;
  1565. if (i > 0) {
  1566. blockundo.vtxundo.push_back(CTxUndo());
  1567. }
  1568. UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
  1569. vPos.push_back(std::make_pair(tx.GetHash(), pos));
  1570. pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
  1571. }
  1572. int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
  1573. LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs-1), nTimeConnect * 0.000001);
  1574. if (block.vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
  1575. return state.DoS(100,
  1576. error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
  1577. block.vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)),
  1578. REJECT_INVALID, "bad-cb-amount");
  1579. if (!control.Wait())
  1580. return state.DoS(100, false);
  1581. int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
  1582. LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs-1), nTimeVerify * 0.000001);
  1583. if (fJustCheck)
  1584. return true;
  1585. // Write undo information to disk
  1586. if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
  1587. {
  1588. if (pindex->GetUndoPos().IsNull()) {
  1589. CDiskBlockPos pos;
  1590. if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
  1591. return error("ConnectBlock(): FindUndoPos failed");
  1592. if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash()))
  1593. return state.Abort("Failed to write undo data");
  1594. // update nUndoPos in block index
  1595. pindex->nUndoPos = pos.nPos;
  1596. pindex->nStatus |= BLOCK_HAVE_UNDO;
  1597. }
  1598. pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
  1599. setDirtyBlockIndex.insert(pindex);
  1600. }
  1601. if (fTxIndex)
  1602. if (!pblocktree->WriteTxIndex(vPos))
  1603. return state.Abort("Failed to write transaction index");
  1604. // add this block to the view's block chain
  1605. view.SetBestBlock(pindex->GetBlockHash());
  1606. int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
  1607. LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
  1608. // Watch for changes to the previous coinbase transaction.
  1609. static uint256 hashPrevBestCoinBase;
  1610. g_signals.UpdatedTransaction(hashPrevBestCoinBase);
  1611. hashPrevBestCoinBase = block.vtx[0].GetHash();
  1612. int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
  1613. LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
  1614. return true;
  1615. }
  1616. enum FlushStateMode {
  1617. FLUSH_STATE_IF_NEEDED,
  1618. FLUSH_STATE_PERIODIC,
  1619. FLUSH_STATE_ALWAYS
  1620. };
  1621. /**
  1622. * Update the on-disk chain state.
  1623. * The caches and indexes are flushed if either they're too large, forceWrite is set, or
  1624. * fast is not set and it's been a while since the last write.
  1625. */
  1626. bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
  1627. LOCK(cs_main);
  1628. static int64_t nLastWrite = 0;
  1629. try {
  1630. if ((mode == FLUSH_STATE_ALWAYS) ||
  1631. ((mode == FLUSH_STATE_PERIODIC || mode == FLUSH_STATE_IF_NEEDED) && pcoinsTip->GetCacheSize() > nCoinCacheSize) ||
  1632. (mode == FLUSH_STATE_PERIODIC && GetTimeMicros() > nLastWrite + DATABASE_WRITE_INTERVAL * 1000000)) {
  1633. // Typical CCoins structures on disk are around 100 bytes in size.
  1634. // Pushing a new one to the database can cause it to be written
  1635. // twice (once in the log, and once in the tables). This is already
  1636. // an overestimation, as most will delete an existing entry or
  1637. // overwrite one. Still, use a conservative safety factor of 2.
  1638. if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
  1639. return state.Error("out of disk space");
  1640. // First make sure all block and undo data is flushed to disk.
  1641. FlushBlockFile();
  1642. // Then update all block file information (which may refer to block and undo files).
  1643. {
  1644. std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
  1645. vFiles.reserve(setDirtyFileInfo.size());
  1646. for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
  1647. vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
  1648. setDirtyFileInfo.erase(it++);
  1649. }
  1650. std::vector<const CBlockIndex*> vBlocks;
  1651. vBlocks.reserve(setDirtyBlockIndex.size());
  1652. for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
  1653. vBlocks.push_back(*it);
  1654. setDirtyBlockIndex.erase(it++);
  1655. }
  1656. if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
  1657. return state.Abort("Files to write to block index database");
  1658. }
  1659. }
  1660. // Finally flush the chainstate (which may refer to block index entries).
  1661. if (!pcoinsTip->Flush())
  1662. return state.Abort("Failed to write to coin database");
  1663. // Update best block in wallet (so we can detect restored wallets).
  1664. if (mode != FLUSH_STATE_IF_NEEDED) {
  1665. g_signals.SetBestChain(chainActive.GetLocator());
  1666. }
  1667. nLastWrite = GetTimeMicros();
  1668. }
  1669. } catch (const std::runtime_error& e) {
  1670. return state.Abort(std::string("System error while flushing: ") + e.what());
  1671. }
  1672. return true;
  1673. }
  1674. void FlushStateToDisk() {
  1675. CValidationState state;
  1676. FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
  1677. }
  1678. /** Update chainActive and related internal data structures. */
  1679. void static UpdateTip(CBlockIndex *pindexNew) {
  1680. chainActive.SetTip(pindexNew);
  1681. // New best block
  1682. nTimeBestReceived = GetTime();
  1683. mempool.AddTransactionsUpdated(1);
  1684. LogPrintf("UpdateTip: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%u\n",
  1685. chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
  1686. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
  1687. Checkpoints::GuessVerificationProgress(chainActive.Tip()), (unsigned int)pcoinsTip->GetCacheSize());
  1688. cvBlockChange.notify_all();
  1689. // Check the version of the last 100 blocks to see if we need to upgrade:
  1690. static bool fWarned = false;
  1691. if (!IsInitialBlockDownload() && !fWarned)
  1692. {
  1693. int nUpgraded = 0;
  1694. const CBlockIndex* pindex = chainActive.Tip();
  1695. for (int i = 0; i < 100 && pindex != NULL; i++)
  1696. {
  1697. if (pindex->nVersion > CBlock::CURRENT_VERSION)
  1698. ++nUpgraded;
  1699. pindex = pindex->pprev;
  1700. }
  1701. if (nUpgraded > 0)
  1702. LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
  1703. if (nUpgraded > 100/2)
  1704. {
  1705. // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
  1706. strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
  1707. CAlert::Notify(strMiscWarning, true);
  1708. fWarned = true;
  1709. }
  1710. }
  1711. }
  1712. /** Disconnect chainActive's tip. */
  1713. bool static DisconnectTip(CValidationState &state) {
  1714. CBlockIndex *pindexDelete = chainActive.Tip();
  1715. assert(pindexDelete);
  1716. mempool.check(pcoinsTip);
  1717. // Read block from disk.
  1718. CBlock block;
  1719. if (!ReadBlockFromDisk(block, pindexDelete))
  1720. return state.Abort("Failed to read block");
  1721. // Apply the block atomically to the chain state.
  1722. int64_t nStart = GetTimeMicros();
  1723. {
  1724. CCoinsViewCache view(pcoinsTip);
  1725. if (!DisconnectBlock(block, state, pindexDelete, view))
  1726. return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
  1727. assert(view.Flush());
  1728. }
  1729. LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
  1730. // Write the chain state to disk, if necessary.
  1731. if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
  1732. return false;
  1733. // Resurrect mempool transactions from the disconnected block.
  1734. BOOST_FOREACH(const CTransaction &tx, block.vtx) {
  1735. // ignore validation errors in resurrected transactions
  1736. list<CTransaction> removed;
  1737. CValidationState stateDummy;
  1738. if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
  1739. mempool.remove(tx, removed, true);
  1740. }
  1741. mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
  1742. mempool.check(pcoinsTip);
  1743. // Update chainActive and related variables.
  1744. UpdateTip(pindexDelete->pprev);
  1745. // Let wallets know transactions went from 1-confirmed to
  1746. // 0-confirmed or conflicted:
  1747. BOOST_FOREACH(const CTransaction &tx, block.vtx) {
  1748. SyncWithWallets(tx, NULL);
  1749. }
  1750. return true;
  1751. }
  1752. static int64_t nTimeReadFromDisk = 0;
  1753. static int64_t nTimeConnectTotal = 0;
  1754. static int64_t nTimeFlush = 0;
  1755. static int64_t nTimeChainState = 0;
  1756. static int64_t nTimePostConnect = 0;
  1757. /**
  1758. * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
  1759. * corresponding to pindexNew, to bypass loading it again from disk.
  1760. */
  1761. bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
  1762. assert(pindexNew->pprev == chainActive.Tip());
  1763. mempool.check(pcoinsTip);
  1764. // Read block from disk.
  1765. int64_t nTime1 = GetTimeMicros();
  1766. CBlock block;
  1767. if (!pblock) {
  1768. if (!ReadBlockFromDisk(block, pindexNew))
  1769. return state.Abort("Failed to read block");
  1770. pblock = &block;
  1771. }
  1772. // Apply the block atomically to the chain state.
  1773. int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
  1774. int64_t nTime3;
  1775. LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
  1776. {
  1777. CCoinsViewCache view(pcoinsTip);
  1778. CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
  1779. bool rv = ConnectBlock(*pblock, state, pindexNew, view);
  1780. g_signals.BlockChecked(*pblock, state);
  1781. if (!rv) {
  1782. if (state.IsInvalid())
  1783. InvalidBlockFound(pindexNew, state);
  1784. return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
  1785. }
  1786. mapBlockSource.erase(inv.hash);
  1787. nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
  1788. LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
  1789. assert(view.Flush());
  1790. }
  1791. int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
  1792. LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
  1793. // Write the chain state to disk, if necessary.
  1794. if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
  1795. return false;
  1796. int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
  1797. LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
  1798. // Remove conflicting transactions from the mempool.
  1799. list<CTransaction> txConflicted;
  1800. mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted);
  1801. mempool.check(pcoinsTip);
  1802. // Update chainActive & related variables.
  1803. UpdateTip(pindexNew);
  1804. // Tell wallet about transactions that went from mempool
  1805. // to conflicted:
  1806. BOOST_FOREACH(const CTransaction &tx, txConflicted) {
  1807. SyncWithWallets(tx, NULL);
  1808. }
  1809. // ... and about transactions that got confirmed:
  1810. BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
  1811. SyncWithWallets(tx, pblock);
  1812. }
  1813. int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
  1814. LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
  1815. LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
  1816. return true;
  1817. }
  1818. /**
  1819. * Return the tip of the chain with the most work in it, that isn't
  1820. * known to be invalid (it's however far from certain to be valid).
  1821. */
  1822. static CBlockIndex* FindMostWorkChain() {
  1823. do {
  1824. CBlockIndex *pindexNew = NULL;
  1825. // Find the best candidate header.
  1826. {
  1827. std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
  1828. if (it == setBlockIndexCandidates.rend())
  1829. return NULL;
  1830. pindexNew = *it;
  1831. }
  1832. // Check whether all blocks on the path between the currently active chain and the candidate are valid.
  1833. // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
  1834. CBlockIndex *pindexTest = pindexNew;
  1835. bool fInvalidAncestor = false;
  1836. while (pindexTest && !chainActive.Contains(pindexTest)) {
  1837. assert(pindexTest->nStatus & BLOCK_HAVE_DATA);
  1838. assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
  1839. if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
  1840. // Candidate has an invalid ancestor, remove entire chain from the set.
  1841. if (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
  1842. pindexBestInvalid = pindexNew;
  1843. CBlockIndex *pindexFailed = pindexNew;
  1844. while (pindexTest != pindexFailed) {
  1845. pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
  1846. setBlockIndexCandidates.erase(pindexFailed);
  1847. pindexFailed = pindexFailed->pprev;
  1848. }
  1849. setBlockIndexCandidates.erase(pindexTest);
  1850. fInvalidAncestor = true;
  1851. break;
  1852. }
  1853. pindexTest = pindexTest->pprev;
  1854. }
  1855. if (!fInvalidAncestor)
  1856. return pindexNew;
  1857. } while(true);
  1858. }
  1859. /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
  1860. static void PruneBlockIndexCandidates() {
  1861. // Note that we can't delete the current block itself, as we may need to return to it later in case a
  1862. // reorganization to a better block fails.
  1863. std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
  1864. while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
  1865. setBlockIndexCandidates.erase(it++);
  1866. }
  1867. // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
  1868. assert(!setBlockIndexCandidates.empty());
  1869. }
  1870. /**
  1871. * Try to make some progress towards making pindexMostWork the active block.
  1872. * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
  1873. */
  1874. static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
  1875. AssertLockHeld(cs_main);
  1876. bool fInvalidFound = false;
  1877. const CBlockIndex *pindexOldTip = chainActive.Tip();
  1878. const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
  1879. // Disconnect active blocks which are no longer in the best chain.
  1880. while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
  1881. if (!DisconnectTip(state))
  1882. return false;
  1883. }
  1884. // Build list of new blocks to connect.
  1885. std::vector<CBlockIndex*> vpindexToConnect;
  1886. bool fContinue = true;
  1887. int nHeight = pindexFork ? pindexFork->nHeight : -1;
  1888. while (fContinue && nHeight != pindexMostWork->nHeight) {
  1889. // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
  1890. // a few blocks along the way.
  1891. int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
  1892. vpindexToConnect.clear();
  1893. vpindexToConnect.reserve(nTargetHeight - nHeight);
  1894. CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
  1895. while (pindexIter && pindexIter->nHeight != nHeight) {
  1896. vpindexToConnect.push_back(pindexIter);
  1897. pindexIter = pindexIter->pprev;
  1898. }
  1899. nHeight = nTargetHeight;
  1900. // Connect new blocks.
  1901. BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
  1902. if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
  1903. if (state.IsInvalid()) {
  1904. // The block violates a consensus rule.
  1905. if (!state.CorruptionPossible())
  1906. InvalidChainFound(vpindexToConnect.back());
  1907. state = CValidationState();
  1908. fInvalidFound = true;
  1909. fContinue = false;
  1910. break;
  1911. } else {
  1912. // A system error occurred (disk space, database error, ...).
  1913. return false;
  1914. }
  1915. } else {
  1916. PruneBlockIndexCandidates();
  1917. if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
  1918. // We're in a better position than we were. Return temporarily to release the lock.
  1919. fContinue = false;
  1920. break;
  1921. }
  1922. }
  1923. }
  1924. }
  1925. // Callbacks/notifications for a new best chain.
  1926. if (fInvalidFound)
  1927. CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
  1928. else
  1929. CheckForkWarningConditions();
  1930. return true;
  1931. }
  1932. /**
  1933. * Make the best chain active, in multiple steps. The result is either failure
  1934. * or an activated best chain. pblock is either NULL or a pointer to a block
  1935. * that is already loaded (to avoid loading it again from disk).
  1936. */
  1937. bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
  1938. CBlockIndex *pindexNewTip = NULL;
  1939. CBlockIndex *pindexMostWork = NULL;
  1940. do {
  1941. boost::this_thread::interruption_point();
  1942. bool fInitialDownload;
  1943. {
  1944. LOCK(cs_main);
  1945. pindexMostWork = FindMostWorkChain();
  1946. // Whether we have anything to do at all.
  1947. if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
  1948. return true;
  1949. if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
  1950. return false;
  1951. pindexNewTip = chainActive.Tip();
  1952. fInitialDownload = IsInitialBlockDownload();
  1953. }
  1954. // When we reach this point, we switched to a new tip (stored in pindexNewTip).
  1955. // Notifications/callbacks that can run without cs_main
  1956. if (!fInitialDownload) {
  1957. uint256 hashNewTip = pindexNewTip->GetBlockHash();
  1958. // Relay inventory, but don't relay old inventory during initial block download.
  1959. int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
  1960. {
  1961. LOCK(cs_vNodes);
  1962. BOOST_FOREACH(CNode* pnode, vNodes)
  1963. if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
  1964. pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
  1965. }
  1966. // Notify external listeners about the new tip.
  1967. uiInterface.NotifyBlockTip(hashNewTip);
  1968. }
  1969. } while(pindexMostWork != chainActive.Tip());
  1970. // Write changes periodically to disk, after relay.
  1971. if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
  1972. return false;
  1973. }
  1974. return true;
  1975. }
  1976. bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
  1977. AssertLockHeld(cs_main);
  1978. // Mark the block itself as invalid.
  1979. pindex->nStatus |= BLOCK_FAILED_VALID;
  1980. setDirtyBlockIndex.insert(pindex);
  1981. setBlockIndexCandidates.erase(pindex);
  1982. while (chainActive.Contains(pindex)) {
  1983. CBlockIndex *pindexWalk = chainActive.Tip();
  1984. pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
  1985. setDirtyBlockIndex.insert(pindexWalk);
  1986. setBlockIndexCandidates.erase(pindexWalk);
  1987. // ActivateBestChain considers blocks already in chainActive
  1988. // unconditionally valid already, so force disconnect away from it.
  1989. if (!DisconnectTip(state)) {
  1990. return false;
  1991. }
  1992. }
  1993. // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
  1994. // add them again.
  1995. BlockMap::iterator it = mapBlockIndex.begin();
  1996. while (it != mapBlockIndex.end()) {
  1997. if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
  1998. setBlockIndexCandidates.insert(it->second);
  1999. }
  2000. it++;
  2001. }
  2002. InvalidChainFound(pindex);
  2003. return true;
  2004. }
  2005. bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
  2006. AssertLockHeld(cs_main);
  2007. int nHeight = pindex->nHeight;
  2008. // Remove the invalidity flag from this block and all its descendants.
  2009. BlockMap::iterator it = mapBlockIndex.begin();
  2010. while (it != mapBlockIndex.end()) {
  2011. if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
  2012. it->second->nStatus &= ~BLOCK_FAILED_MASK;
  2013. setDirtyBlockIndex.insert(it->second);
  2014. if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
  2015. setBlockIndexCandidates.insert(it->second);
  2016. }
  2017. if (it->second == pindexBestInvalid) {
  2018. // Reset invalid block marker if it was pointing to one of those.
  2019. pindexBestInvalid = NULL;
  2020. }
  2021. }
  2022. it++;
  2023. }
  2024. // Remove the invalidity flag from all ancestors too.
  2025. while (pindex != NULL) {
  2026. if (pindex->nStatus & BLOCK_FAILED_MASK) {
  2027. pindex->nStatus &= ~BLOCK_FAILED_MASK;
  2028. setDirtyBlockIndex.insert(pindex);
  2029. }
  2030. pindex = pindex->pprev;
  2031. }
  2032. return true;
  2033. }
  2034. CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
  2035. {
  2036. // Check for duplicate
  2037. uint256 hash = block.GetHash();
  2038. BlockMap::iterator it = mapBlockIndex.find(hash);
  2039. if (it != mapBlockIndex.end())
  2040. return it->second;
  2041. // Construct new block index object
  2042. CBlockIndex* pindexNew = new CBlockIndex(block);
  2043. assert(pindexNew);
  2044. // We assign the sequence id to blocks only when the full data is available,
  2045. // to avoid miners withholding blocks but broadcasting headers, to get a
  2046. // competitive advantage.
  2047. pindexNew->nSequenceId = 0;
  2048. BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  2049. pindexNew->phashBlock = &((*mi).first);
  2050. BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
  2051. if (miPrev != mapBlockIndex.end())
  2052. {
  2053. pindexNew->pprev = (*miPrev).second;
  2054. pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
  2055. pindexNew->BuildSkip();
  2056. }
  2057. pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
  2058. pindexNew->RaiseValidity(BLOCK_VALID_TREE);
  2059. if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
  2060. pindexBestHeader = pindexNew;
  2061. setDirtyBlockIndex.insert(pindexNew);
  2062. return pindexNew;
  2063. }
  2064. /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
  2065. bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
  2066. {
  2067. pindexNew->nTx = block.vtx.size();
  2068. pindexNew->nChainTx = 0;
  2069. pindexNew->nFile = pos.nFile;
  2070. pindexNew->nDataPos = pos.nPos;
  2071. pindexNew->nUndoPos = 0;
  2072. pindexNew->nStatus |= BLOCK_HAVE_DATA;
  2073. pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
  2074. {
  2075. LOCK(cs_nBlockSequenceId);
  2076. pindexNew->nSequenceId = nBlockSequenceId++;
  2077. }
  2078. setDirtyBlockIndex.insert(pindexNew);
  2079. if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
  2080. // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
  2081. deque<CBlockIndex*> queue;
  2082. queue.push_back(pindexNew);
  2083. // Recursively process any descendant blocks that now may be eligible to be connected.
  2084. while (!queue.empty()) {
  2085. CBlockIndex *pindex = queue.front();
  2086. queue.pop_front();
  2087. pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
  2088. setBlockIndexCandidates.insert(pindex);
  2089. std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
  2090. while (range.first != range.second) {
  2091. std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
  2092. queue.push_back(it->second);
  2093. range.first++;
  2094. mapBlocksUnlinked.erase(it);
  2095. }
  2096. }
  2097. } else {
  2098. if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
  2099. mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
  2100. }
  2101. }
  2102. return true;
  2103. }
  2104. bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
  2105. {
  2106. LOCK(cs_LastBlockFile);
  2107. unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
  2108. if (vinfoBlockFile.size() <= nFile) {
  2109. vinfoBlockFile.resize(nFile + 1);
  2110. }
  2111. if (!fKnown) {
  2112. while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
  2113. LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
  2114. FlushBlockFile(true);
  2115. nFile++;
  2116. if (vinfoBlockFile.size() <= nFile) {
  2117. vinfoBlockFile.resize(nFile + 1);
  2118. }
  2119. }
  2120. pos.nFile = nFile;
  2121. pos.nPos = vinfoBlockFile[nFile].nSize;
  2122. }
  2123. nLastBlockFile = nFile;
  2124. vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
  2125. if (fKnown)
  2126. vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
  2127. else
  2128. vinfoBlockFile[nFile].nSize += nAddSize;
  2129. if (!fKnown) {
  2130. unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
  2131. unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
  2132. if (nNewChunks > nOldChunks) {
  2133. if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
  2134. FILE *file = OpenBlockFile(pos);
  2135. if (file) {
  2136. LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
  2137. AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
  2138. fclose(file);
  2139. }
  2140. }
  2141. else
  2142. return state.Error("out of disk space");
  2143. }
  2144. }
  2145. setDirtyFileInfo.insert(nFile);
  2146. return true;
  2147. }
  2148. bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
  2149. {
  2150. pos.nFile = nFile;
  2151. LOCK(cs_LastBlockFile);
  2152. unsigned int nNewSize;
  2153. pos.nPos = vinfoBlockFile[nFile].nUndoSize;
  2154. nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
  2155. setDirtyFileInfo.insert(nFile);
  2156. unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
  2157. unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
  2158. if (nNewChunks > nOldChunks) {
  2159. if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
  2160. FILE *file = OpenUndoFile(pos);
  2161. if (file) {
  2162. LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
  2163. AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
  2164. fclose(file);
  2165. }
  2166. }
  2167. else
  2168. return state.Error("out of disk space");
  2169. }
  2170. return true;
  2171. }
  2172. bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
  2173. {
  2174. // Check proof of work matches claimed amount
  2175. if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits))
  2176. return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
  2177. REJECT_INVALID, "high-hash");
  2178. // Check timestamp
  2179. if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
  2180. return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
  2181. REJECT_INVALID, "time-too-new");
  2182. return true;
  2183. }
  2184. bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
  2185. {
  2186. // These are checks that are independent of context.
  2187. // Check that the header is valid (particularly PoW). This is mostly
  2188. // redundant with the call in AcceptBlockHeader.
  2189. if (!CheckBlockHeader(block, state, fCheckPOW))
  2190. return false;
  2191. // Check the merkle root.
  2192. if (fCheckMerkleRoot) {
  2193. bool mutated;
  2194. uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
  2195. if (block.hashMerkleRoot != hashMerkleRoot2)
  2196. return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
  2197. REJECT_INVALID, "bad-txnmrklroot", true);
  2198. // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
  2199. // of transactions in a block without affecting the merkle root of a block,
  2200. // while still invalidating it.
  2201. if (mutated)
  2202. return state.DoS(100, error("CheckBlock(): duplicate transaction"),
  2203. REJECT_INVALID, "bad-txns-duplicate", true);
  2204. }
  2205. // All potential-corruption validation must be done before we do any
  2206. // transaction validation, as otherwise we may mark the header as invalid
  2207. // because we receive the wrong transactions for it.
  2208. // Size limits
  2209. if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
  2210. return state.DoS(100, error("CheckBlock(): size limits failed"),
  2211. REJECT_INVALID, "bad-blk-length");
  2212. // First transaction must be coinbase, the rest must not be
  2213. if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
  2214. return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
  2215. REJECT_INVALID, "bad-cb-missing");
  2216. for (unsigned int i = 1; i < block.vtx.size(); i++)
  2217. if (block.vtx[i].IsCoinBase())
  2218. return state.DoS(100, error("CheckBlock(): more than one coinbase"),
  2219. REJECT_INVALID, "bad-cb-multiple");
  2220. // Check transactions
  2221. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  2222. if (!CheckTransaction(tx, state))
  2223. return error("CheckBlock(): CheckTransaction failed");
  2224. unsigned int nSigOps = 0;
  2225. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  2226. {
  2227. nSigOps += GetLegacySigOpCount(tx);
  2228. }
  2229. if (nSigOps > MAX_BLOCK_SIGOPS)
  2230. return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
  2231. REJECT_INVALID, "bad-blk-sigops", true);
  2232. return true;
  2233. }
  2234. bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
  2235. {
  2236. uint256 hash = block.GetHash();
  2237. if (hash == Params().HashGenesisBlock())
  2238. return true;
  2239. assert(pindexPrev);
  2240. int nHeight = pindexPrev->nHeight+1;
  2241. // Check proof of work
  2242. if ((block.nBits != GetNextWorkRequired(pindexPrev, &block)))
  2243. return state.DoS(100, error("%s: incorrect proof of work", __func__),
  2244. REJECT_INVALID, "bad-diffbits");
  2245. // Check timestamp against prev
  2246. if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
  2247. return state.Invalid(error("%s: block's timestamp is too early", __func__),
  2248. REJECT_INVALID, "time-too-old");
  2249. // Check that the block chain matches the known block chain up to a checkpoint
  2250. if (!Checkpoints::CheckBlock(nHeight, hash))
  2251. return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),
  2252. REJECT_CHECKPOINT, "checkpoint mismatch");
  2253. // Don't accept any forks from the main chain prior to last checkpoint
  2254. CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint();
  2255. if (pcheckpoint && nHeight < pcheckpoint->nHeight)
  2256. return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
  2257. // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
  2258. if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, Params().RejectBlockOutdatedMajority()))
  2259. {
  2260. return state.Invalid(error("%s: rejected nVersion=1 block", __func__),
  2261. REJECT_OBSOLETE, "bad-version");
  2262. }
  2263. // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
  2264. if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, Params().RejectBlockOutdatedMajority()))
  2265. {
  2266. return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
  2267. REJECT_OBSOLETE, "bad-version");
  2268. }
  2269. return true;
  2270. }
  2271. bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
  2272. {
  2273. const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
  2274. // Check that all transactions are finalized
  2275. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  2276. if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) {
  2277. return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
  2278. }
  2279. // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
  2280. // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
  2281. if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, Params().EnforceBlockUpgradeMajority()))
  2282. {
  2283. CScript expect = CScript() << nHeight;
  2284. if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
  2285. !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
  2286. return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
  2287. }
  2288. }
  2289. return true;
  2290. }
  2291. bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
  2292. {
  2293. AssertLockHeld(cs_main);
  2294. // Check for duplicate
  2295. uint256 hash = block.GetHash();
  2296. BlockMap::iterator miSelf = mapBlockIndex.find(hash);
  2297. CBlockIndex *pindex = NULL;
  2298. if (miSelf != mapBlockIndex.end()) {
  2299. // Block header is already known.
  2300. pindex = miSelf->second;
  2301. if (ppindex)
  2302. *ppindex = pindex;
  2303. if (pindex->nStatus & BLOCK_FAILED_MASK)
  2304. return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
  2305. return true;
  2306. }
  2307. if (!CheckBlockHeader(block, state))
  2308. return false;
  2309. // Get prev block index
  2310. CBlockIndex* pindexPrev = NULL;
  2311. if (hash != Params().HashGenesisBlock()) {
  2312. BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
  2313. if (mi == mapBlockIndex.end())
  2314. return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
  2315. pindexPrev = (*mi).second;
  2316. if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
  2317. return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
  2318. }
  2319. if (!ContextualCheckBlockHeader(block, state, pindexPrev))
  2320. return false;
  2321. if (pindex == NULL)
  2322. pindex = AddToBlockIndex(block);
  2323. if (ppindex)
  2324. *ppindex = pindex;
  2325. return true;
  2326. }
  2327. bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp)
  2328. {
  2329. AssertLockHeld(cs_main);
  2330. CBlockIndex *&pindex = *ppindex;
  2331. if (!AcceptBlockHeader(block, state, &pindex))
  2332. return false;
  2333. if (pindex->nStatus & BLOCK_HAVE_DATA) {
  2334. // TODO: deal better with duplicate blocks.
  2335. // return state.DoS(20, error("AcceptBlock(): already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()), REJECT_DUPLICATE, "duplicate");
  2336. return true;
  2337. }
  2338. if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
  2339. if (state.IsInvalid() && !state.CorruptionPossible()) {
  2340. pindex->nStatus |= BLOCK_FAILED_VALID;
  2341. setDirtyBlockIndex.insert(pindex);
  2342. }
  2343. return false;
  2344. }
  2345. int nHeight = pindex->nHeight;
  2346. // Write block to history file
  2347. try {
  2348. unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
  2349. CDiskBlockPos blockPos;
  2350. if (dbp != NULL)
  2351. blockPos = *dbp;
  2352. if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
  2353. return error("AcceptBlock(): FindBlockPos failed");
  2354. if (dbp == NULL)
  2355. if (!WriteBlockToDisk(block, blockPos))
  2356. return state.Abort("Failed to write block");
  2357. if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
  2358. return error("AcceptBlock(): ReceivedBlockTransactions failed");
  2359. } catch (const std::runtime_error& e) {
  2360. return state.Abort(std::string("System error: ") + e.what());
  2361. }
  2362. return true;
  2363. }
  2364. static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired)
  2365. {
  2366. unsigned int nToCheck = Params().ToCheckBlockUpgradeMajority();
  2367. unsigned int nFound = 0;
  2368. for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
  2369. {
  2370. if (pstart->nVersion >= minVersion)
  2371. ++nFound;
  2372. pstart = pstart->pprev;
  2373. }
  2374. return (nFound >= nRequired);
  2375. }
  2376. bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
  2377. {
  2378. // Preliminary checks
  2379. bool checked = CheckBlock(*pblock, state);
  2380. {
  2381. LOCK(cs_main);
  2382. MarkBlockAsReceived(pblock->GetHash());
  2383. if (!checked) {
  2384. return error("%s: CheckBlock FAILED", __func__);
  2385. }
  2386. // Store to disk
  2387. CBlockIndex *pindex = NULL;
  2388. bool ret = AcceptBlock(*pblock, state, &pindex, dbp);
  2389. if (pindex && pfrom) {
  2390. mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
  2391. }
  2392. if (!ret)
  2393. return error("%s: AcceptBlock FAILED", __func__);
  2394. }
  2395. if (!ActivateBestChain(state, pblock))
  2396. return error("%s: ActivateBestChain failed", __func__);
  2397. return true;
  2398. }
  2399. bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
  2400. {
  2401. AssertLockHeld(cs_main);
  2402. assert(pindexPrev == chainActive.Tip());
  2403. CCoinsViewCache viewNew(pcoinsTip);
  2404. CBlockIndex indexDummy(block);
  2405. indexDummy.pprev = pindexPrev;
  2406. indexDummy.nHeight = pindexPrev->nHeight + 1;
  2407. // NOTE: CheckBlockHeader is called by CheckBlock
  2408. if (!ContextualCheckBlockHeader(block, state, pindexPrev))
  2409. return false;
  2410. if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
  2411. return false;
  2412. if (!ContextualCheckBlock(block, state, pindexPrev))
  2413. return false;
  2414. if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
  2415. return false;
  2416. assert(state.IsValid());
  2417. return true;
  2418. }
  2419. bool AbortNode(const std::string &strMessage, const std::string &userMessage) {
  2420. strMiscWarning = strMessage;
  2421. LogPrintf("*** %s\n", strMessage);
  2422. uiInterface.ThreadSafeMessageBox(
  2423. userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
  2424. "", CClientUIInterface::MSG_ERROR);
  2425. StartShutdown();
  2426. return false;
  2427. }
  2428. bool CheckDiskSpace(uint64_t nAdditionalBytes)
  2429. {
  2430. uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
  2431. // Check for nMinDiskSpace bytes (currently 50MB)
  2432. if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
  2433. return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
  2434. return true;
  2435. }
  2436. FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
  2437. {
  2438. if (pos.IsNull())
  2439. return NULL;
  2440. boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
  2441. boost::filesystem::create_directories(path.parent_path());
  2442. FILE* file = fopen(path.string().c_str(), "rb+");
  2443. if (!file && !fReadOnly)
  2444. file = fopen(path.string().c_str(), "wb+");
  2445. if (!file) {
  2446. LogPrintf("Unable to open file %s\n", path.string());
  2447. return NULL;
  2448. }
  2449. if (pos.nPos) {
  2450. if (fseek(file, pos.nPos, SEEK_SET)) {
  2451. LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
  2452. fclose(file);
  2453. return NULL;
  2454. }
  2455. }
  2456. return file;
  2457. }
  2458. FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
  2459. return OpenDiskFile(pos, "blk", fReadOnly);
  2460. }
  2461. FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
  2462. return OpenDiskFile(pos, "rev", fReadOnly);
  2463. }
  2464. boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
  2465. {
  2466. return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
  2467. }
  2468. CBlockIndex * InsertBlockIndex(uint256 hash)
  2469. {
  2470. if (hash.IsNull())
  2471. return NULL;
  2472. // Return existing
  2473. BlockMap::iterator mi = mapBlockIndex.find(hash);
  2474. if (mi != mapBlockIndex.end())
  2475. return (*mi).second;
  2476. // Create new
  2477. CBlockIndex* pindexNew = new CBlockIndex();
  2478. if (!pindexNew)
  2479. throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
  2480. mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  2481. pindexNew->phashBlock = &((*mi).first);
  2482. return pindexNew;
  2483. }
  2484. bool static LoadBlockIndexDB()
  2485. {
  2486. if (!pblocktree->LoadBlockIndexGuts())
  2487. return false;
  2488. boost::this_thread::interruption_point();
  2489. // Calculate nChainWork
  2490. vector<pair<int, CBlockIndex*> > vSortedByHeight;
  2491. vSortedByHeight.reserve(mapBlockIndex.size());
  2492. BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
  2493. {
  2494. CBlockIndex* pindex = item.second;
  2495. vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
  2496. }
  2497. sort(vSortedByHeight.begin(), vSortedByHeight.end());
  2498. BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
  2499. {
  2500. CBlockIndex* pindex = item.second;
  2501. pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
  2502. if (pindex->nStatus & BLOCK_HAVE_DATA) {
  2503. if (pindex->pprev) {
  2504. if (pindex->pprev->nChainTx) {
  2505. pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
  2506. } else {
  2507. pindex->nChainTx = 0;
  2508. mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
  2509. }
  2510. } else {
  2511. pindex->nChainTx = pindex->nTx;
  2512. }
  2513. }
  2514. if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
  2515. setBlockIndexCandidates.insert(pindex);
  2516. if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
  2517. pindexBestInvalid = pindex;
  2518. if (pindex->pprev)
  2519. pindex->BuildSkip();
  2520. if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
  2521. pindexBestHeader = pindex;
  2522. }
  2523. // Load block file info
  2524. pblocktree->ReadLastBlockFile(nLastBlockFile);
  2525. vinfoBlockFile.resize(nLastBlockFile + 1);
  2526. LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
  2527. for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
  2528. pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
  2529. }
  2530. LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
  2531. for (int nFile = nLastBlockFile + 1; true; nFile++) {
  2532. CBlockFileInfo info;
  2533. if (pblocktree->ReadBlockFileInfo(nFile, info)) {
  2534. vinfoBlockFile.push_back(info);
  2535. } else {
  2536. break;
  2537. }
  2538. }
  2539. // Check presence of blk files
  2540. LogPrintf("Checking all blk files are present...\n");
  2541. set<int> setBlkDataFiles;
  2542. BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
  2543. {
  2544. CBlockIndex* pindex = item.second;
  2545. if (pindex->nStatus & BLOCK_HAVE_DATA) {
  2546. setBlkDataFiles.insert(pindex->nFile);
  2547. }
  2548. }
  2549. for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
  2550. {
  2551. CDiskBlockPos pos(*it, 0);
  2552. if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
  2553. return false;
  2554. }
  2555. }
  2556. // Check whether we need to continue reindexing
  2557. bool fReindexing = false;
  2558. pblocktree->ReadReindexing(fReindexing);
  2559. fReindex |= fReindexing;
  2560. // Check whether we have a transaction index
  2561. pblocktree->ReadFlag("txindex", fTxIndex);
  2562. LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
  2563. // Load pointer to end of best chain
  2564. BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
  2565. if (it == mapBlockIndex.end())
  2566. return true;
  2567. chainActive.SetTip(it->second);
  2568. PruneBlockIndexCandidates();
  2569. LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n",
  2570. chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
  2571. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
  2572. Checkpoints::GuessVerificationProgress(chainActive.Tip()));
  2573. return true;
  2574. }
  2575. CVerifyDB::CVerifyDB()
  2576. {
  2577. uiInterface.ShowProgress(_("Verifying blocks..."), 0);
  2578. }
  2579. CVerifyDB::~CVerifyDB()
  2580. {
  2581. uiInterface.ShowProgress("", 100);
  2582. }
  2583. bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
  2584. {
  2585. LOCK(cs_main);
  2586. if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
  2587. return true;
  2588. // Verify blocks in the best chain
  2589. if (nCheckDepth <= 0)
  2590. nCheckDepth = 1000000000; // suffices until the year 19000
  2591. if (nCheckDepth > chainActive.Height())
  2592. nCheckDepth = chainActive.Height();
  2593. nCheckLevel = std::max(0, std::min(4, nCheckLevel));
  2594. LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
  2595. CCoinsViewCache coins(coinsview);
  2596. CBlockIndex* pindexState = chainActive.Tip();
  2597. CBlockIndex* pindexFailure = NULL;
  2598. int nGoodTransactions = 0;
  2599. CValidationState state;
  2600. for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
  2601. {
  2602. boost::this_thread::interruption_point();
  2603. uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
  2604. if (pindex->nHeight < chainActive.Height()-nCheckDepth)
  2605. break;
  2606. CBlock block;
  2607. // check level 0: read from disk
  2608. if (!ReadBlockFromDisk(block, pindex))
  2609. return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  2610. // check level 1: verify block validity
  2611. if (nCheckLevel >= 1 && !CheckBlock(block, state))
  2612. return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  2613. // check level 2: verify undo validity
  2614. if (nCheckLevel >= 2 && pindex) {
  2615. CBlockUndo undo;
  2616. CDiskBlockPos pos = pindex->GetUndoPos();
  2617. if (!pos.IsNull()) {
  2618. if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
  2619. return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  2620. }
  2621. }
  2622. // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
  2623. if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= nCoinCacheSize) {
  2624. bool fClean = true;
  2625. if (!DisconnectBlock(block, state, pindex, coins, &fClean))
  2626. return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  2627. pindexState = pindex->pprev;
  2628. if (!fClean) {
  2629. nGoodTransactions = 0;
  2630. pindexFailure = pindex;
  2631. } else
  2632. nGoodTransactions += block.vtx.size();
  2633. }
  2634. if (ShutdownRequested())
  2635. return true;
  2636. }
  2637. if (pindexFailure)
  2638. return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
  2639. // check level 4: try reconnecting blocks
  2640. if (nCheckLevel >= 4) {
  2641. CBlockIndex *pindex = pindexState;
  2642. while (pindex != chainActive.Tip()) {
  2643. boost::this_thread::interruption_point();
  2644. uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
  2645. pindex = chainActive.Next(pindex);
  2646. CBlock block;
  2647. if (!ReadBlockFromDisk(block, pindex))
  2648. return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  2649. if (!ConnectBlock(block, state, pindex, coins))
  2650. return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  2651. }
  2652. }
  2653. LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
  2654. return true;
  2655. }
  2656. void UnloadBlockIndex()
  2657. {
  2658. LOCK(cs_main);
  2659. setBlockIndexCandidates.clear();
  2660. chainActive.SetTip(NULL);
  2661. pindexBestInvalid = NULL;
  2662. pindexBestHeader = NULL;
  2663. mempool.clear();
  2664. mapOrphanTransactions.clear();
  2665. mapOrphanTransactionsByPrev.clear();
  2666. nSyncStarted = 0;
  2667. mapBlocksUnlinked.clear();
  2668. vinfoBlockFile.clear();
  2669. nLastBlockFile = 0;
  2670. nBlockSequenceId = 1;
  2671. mapBlockSource.clear();
  2672. mapBlocksInFlight.clear();
  2673. nQueuedValidatedHeaders = 0;
  2674. nPreferredDownload = 0;
  2675. setDirtyBlockIndex.clear();
  2676. setDirtyFileInfo.clear();
  2677. mapNodeState.clear();
  2678. BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
  2679. delete entry.second;
  2680. }
  2681. mapBlockIndex.clear();
  2682. }
  2683. bool LoadBlockIndex()
  2684. {
  2685. // Load block index from databases
  2686. if (!fReindex && !LoadBlockIndexDB())
  2687. return false;
  2688. return true;
  2689. }
  2690. bool InitBlockIndex() {
  2691. LOCK(cs_main);
  2692. // Check whether we're already initialized
  2693. if (chainActive.Genesis() != NULL)
  2694. return true;
  2695. // Use the provided setting for -txindex in the new database
  2696. fTxIndex = GetBoolArg("-txindex", false);
  2697. pblocktree->WriteFlag("txindex", fTxIndex);
  2698. LogPrintf("Initializing databases...\n");
  2699. // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
  2700. if (!fReindex) {
  2701. try {
  2702. CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
  2703. // Start new block file
  2704. unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
  2705. CDiskBlockPos blockPos;
  2706. CValidationState state;
  2707. if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
  2708. return error("LoadBlockIndex(): FindBlockPos failed");
  2709. if (!WriteBlockToDisk(block, blockPos))
  2710. return error("LoadBlockIndex(): writing genesis block to disk failed");
  2711. CBlockIndex *pindex = AddToBlockIndex(block);
  2712. if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
  2713. return error("LoadBlockIndex(): genesis block not accepted");
  2714. if (!ActivateBestChain(state, &block))
  2715. return error("LoadBlockIndex(): genesis block cannot be activated");
  2716. // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
  2717. return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
  2718. } catch (const std::runtime_error& e) {
  2719. return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
  2720. }
  2721. }
  2722. return true;
  2723. }
  2724. bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
  2725. {
  2726. // Map of disk positions for blocks with unknown parent (only used for reindex)
  2727. static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
  2728. int64_t nStart = GetTimeMillis();
  2729. int nLoaded = 0;
  2730. try {
  2731. // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
  2732. CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
  2733. uint64_t nRewind = blkdat.GetPos();
  2734. while (!blkdat.eof()) {
  2735. boost::this_thread::interruption_point();
  2736. blkdat.SetPos(nRewind);
  2737. nRewind++; // start one byte further next time, in case of failure
  2738. blkdat.SetLimit(); // remove former limit
  2739. unsigned int nSize = 0;
  2740. try {
  2741. // locate a header
  2742. unsigned char buf[MESSAGE_START_SIZE];
  2743. blkdat.FindByte(Params().MessageStart()[0]);
  2744. nRewind = blkdat.GetPos()+1;
  2745. blkdat >> FLATDATA(buf);
  2746. if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
  2747. continue;
  2748. // read size
  2749. blkdat >> nSize;
  2750. if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
  2751. continue;
  2752. } catch (const std::exception&) {
  2753. // no valid block header found; don't complain
  2754. break;
  2755. }
  2756. try {
  2757. // read block
  2758. uint64_t nBlockPos = blkdat.GetPos();
  2759. if (dbp)
  2760. dbp->nPos = nBlockPos;
  2761. blkdat.SetLimit(nBlockPos + nSize);
  2762. blkdat.SetPos(nBlockPos);
  2763. CBlock block;
  2764. blkdat >> block;
  2765. nRewind = blkdat.GetPos();
  2766. // detect out of order blocks, and store them for later
  2767. uint256 hash = block.GetHash();
  2768. if (hash != Params().HashGenesisBlock() && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
  2769. LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
  2770. block.hashPrevBlock.ToString());
  2771. if (dbp)
  2772. mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
  2773. continue;
  2774. }
  2775. // process in case the block isn't known yet
  2776. if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
  2777. CValidationState state;
  2778. if (ProcessNewBlock(state, NULL, &block, dbp))
  2779. nLoaded++;
  2780. if (state.IsError())
  2781. break;
  2782. } else if (hash != Params().HashGenesisBlock() && mapBlockIndex[hash]->nHeight % 1000 == 0) {
  2783. LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
  2784. }
  2785. // Recursively process earlier encountered successors of this block
  2786. deque<uint256> queue;
  2787. queue.push_back(hash);
  2788. while (!queue.empty()) {
  2789. uint256 head = queue.front();
  2790. queue.pop_front();
  2791. std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
  2792. while (range.first != range.second) {
  2793. std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
  2794. if (ReadBlockFromDisk(block, it->second))
  2795. {
  2796. LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
  2797. head.ToString());
  2798. CValidationState dummy;
  2799. if (ProcessNewBlock(dummy, NULL, &block, &it->second))
  2800. {
  2801. nLoaded++;
  2802. queue.push_back(block.GetHash());
  2803. }
  2804. }
  2805. range.first++;
  2806. mapBlocksUnknownParent.erase(it);
  2807. }
  2808. }
  2809. } catch (const std::exception& e) {
  2810. LogPrintf("%s: Deserialize or I/O error - %s", __func__, e.what());
  2811. }
  2812. }
  2813. } catch (const std::runtime_error& e) {
  2814. AbortNode(std::string("System error: ") + e.what());
  2815. }
  2816. if (nLoaded > 0)
  2817. LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
  2818. return nLoaded > 0;
  2819. }
  2820. //////////////////////////////////////////////////////////////////////////////
  2821. //
  2822. // CAlert
  2823. //
  2824. string GetWarnings(string strFor)
  2825. {
  2826. int nPriority = 0;
  2827. string strStatusBar;
  2828. string strRPC;
  2829. if (!CLIENT_VERSION_IS_RELEASE)
  2830. strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
  2831. if (GetBoolArg("-testsafemode", false))
  2832. strStatusBar = strRPC = "testsafemode enabled";
  2833. // Misc warnings like out of disk space and clock is wrong
  2834. if (strMiscWarning != "")
  2835. {
  2836. nPriority = 1000;
  2837. strStatusBar = strMiscWarning;
  2838. }
  2839. if (fLargeWorkForkFound)
  2840. {
  2841. nPriority = 2000;
  2842. strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
  2843. }
  2844. else if (fLargeWorkInvalidChainFound)
  2845. {
  2846. nPriority = 2000;
  2847. strStatusBar = strRPC = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
  2848. }
  2849. // Alerts
  2850. {
  2851. LOCK(cs_mapAlerts);
  2852. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  2853. {
  2854. const CAlert& alert = item.second;
  2855. if (alert.AppliesToMe() && alert.nPriority > nPriority)
  2856. {
  2857. nPriority = alert.nPriority;
  2858. strStatusBar = alert.strStatusBar;
  2859. }
  2860. }
  2861. }
  2862. if (strFor == "statusbar")
  2863. return strStatusBar;
  2864. else if (strFor == "rpc")
  2865. return strRPC;
  2866. assert(!"GetWarnings(): invalid parameter");
  2867. return "error";
  2868. }
  2869. //////////////////////////////////////////////////////////////////////////////
  2870. //
  2871. // Messages
  2872. //
  2873. bool static AlreadyHave(const CInv& inv)
  2874. {
  2875. switch (inv.type)
  2876. {
  2877. case MSG_TX:
  2878. {
  2879. bool txInMap = false;
  2880. txInMap = mempool.exists(inv.hash);
  2881. return txInMap || mapOrphanTransactions.count(inv.hash) ||
  2882. pcoinsTip->HaveCoins(inv.hash);
  2883. }
  2884. case MSG_BLOCK:
  2885. return mapBlockIndex.count(inv.hash);
  2886. }
  2887. // Don't know what it is, just say we already got one
  2888. return true;
  2889. }
  2890. void static ProcessGetData(CNode* pfrom)
  2891. {
  2892. std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
  2893. vector<CInv> vNotFound;
  2894. LOCK(cs_main);
  2895. while (it != pfrom->vRecvGetData.end()) {
  2896. // Don't bother if send buffer is too full to respond anyway
  2897. if (pfrom->nSendSize >= SendBufferSize())
  2898. break;
  2899. const CInv &inv = *it;
  2900. {
  2901. boost::this_thread::interruption_point();
  2902. it++;
  2903. if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
  2904. {
  2905. bool send = false;
  2906. BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
  2907. if (mi != mapBlockIndex.end())
  2908. {
  2909. if (chainActive.Contains(mi->second)) {
  2910. send = true;
  2911. } else {
  2912. // To prevent fingerprinting attacks, only send blocks outside of the active
  2913. // chain if they are valid, and no more than a month older than the best header
  2914. // chain we know about.
  2915. send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
  2916. (mi->second->GetBlockTime() > pindexBestHeader->GetBlockTime() - 30 * 24 * 60 * 60);
  2917. if (!send) {
  2918. LogPrintf("ProcessGetData(): ignoring request from peer=%i for old block that isn't in the main chain\n", pfrom->GetId());
  2919. }
  2920. }
  2921. }
  2922. if (send)
  2923. {
  2924. // Send block from disk
  2925. CBlock block;
  2926. if (!ReadBlockFromDisk(block, (*mi).second))
  2927. assert(!"cannot load block from disk");
  2928. if (inv.type == MSG_BLOCK)
  2929. pfrom->PushMessage("block", block);
  2930. else // MSG_FILTERED_BLOCK)
  2931. {
  2932. LOCK(pfrom->cs_filter);
  2933. if (pfrom->pfilter)
  2934. {
  2935. CMerkleBlock merkleBlock(block, *pfrom->pfilter);
  2936. pfrom->PushMessage("merkleblock", merkleBlock);
  2937. // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
  2938. // This avoids hurting performance by pointlessly requiring a round-trip
  2939. // Note that there is currently no way for a node to request any single transactions we didnt send here -
  2940. // they must either disconnect and retry or request the full block.
  2941. // Thus, the protocol spec specified allows for us to provide duplicate txn here,
  2942. // however we MUST always provide at least what the remote peer needs
  2943. typedef std::pair<unsigned int, uint256> PairType;
  2944. BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
  2945. if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
  2946. pfrom->PushMessage("tx", block.vtx[pair.first]);
  2947. }
  2948. // else
  2949. // no response
  2950. }
  2951. // Trigger them to send a getblocks request for the next batch of inventory
  2952. if (inv.hash == pfrom->hashContinue)
  2953. {
  2954. // Bypass PushInventory, this must send even if redundant,
  2955. // and we want it right after the last block so they don't
  2956. // wait for other stuff first.
  2957. vector<CInv> vInv;
  2958. vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
  2959. pfrom->PushMessage("inv", vInv);
  2960. pfrom->hashContinue.SetNull();
  2961. }
  2962. }
  2963. }
  2964. else if (inv.IsKnownType())
  2965. {
  2966. // Send stream from relay memory
  2967. bool pushed = false;
  2968. {
  2969. LOCK(cs_mapRelay);
  2970. map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
  2971. if (mi != mapRelay.end()) {
  2972. pfrom->PushMessage(inv.GetCommand(), (*mi).second);
  2973. pushed = true;
  2974. }
  2975. }
  2976. if (!pushed && inv.type == MSG_TX) {
  2977. CTransaction tx;
  2978. if (mempool.lookup(inv.hash, tx)) {
  2979. CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
  2980. ss.reserve(1000);
  2981. ss << tx;
  2982. pfrom->PushMessage("tx", ss);
  2983. pushed = true;
  2984. }
  2985. }
  2986. if (!pushed) {
  2987. vNotFound.push_back(inv);
  2988. }
  2989. }
  2990. // Track requests for our stuff.
  2991. g_signals.Inventory(inv.hash);
  2992. if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
  2993. break;
  2994. }
  2995. }
  2996. pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
  2997. if (!vNotFound.empty()) {
  2998. // Let the peer know that we didn't find what it asked for, so it doesn't
  2999. // have to wait around forever. Currently only SPV clients actually care
  3000. // about this message: it's needed when they are recursively walking the
  3001. // dependencies of relevant unconfirmed transactions. SPV clients want to
  3002. // do that because they want to know about (and store and rebroadcast and
  3003. // risk analyze) the dependencies of transactions relevant to them, without
  3004. // having to download the entire memory pool.
  3005. pfrom->PushMessage("notfound", vNotFound);
  3006. }
  3007. }
  3008. bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
  3009. {
  3010. RandAddSeedPerfmon();
  3011. LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
  3012. if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
  3013. {
  3014. LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
  3015. return true;
  3016. }
  3017. if (strCommand == "version")
  3018. {
  3019. // Each connection can only send one version message
  3020. if (pfrom->nVersion != 0)
  3021. {
  3022. pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
  3023. Misbehaving(pfrom->GetId(), 1);
  3024. return false;
  3025. }
  3026. int64_t nTime;
  3027. CAddress addrMe;
  3028. CAddress addrFrom;
  3029. uint64_t nNonce = 1;
  3030. vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
  3031. if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
  3032. {
  3033. // disconnect from peers older than this proto version
  3034. LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
  3035. pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
  3036. strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
  3037. pfrom->fDisconnect = true;
  3038. return false;
  3039. }
  3040. if (pfrom->nVersion == 10300)
  3041. pfrom->nVersion = 300;
  3042. if (!vRecv.empty())
  3043. vRecv >> addrFrom >> nNonce;
  3044. if (!vRecv.empty()) {
  3045. vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
  3046. pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
  3047. }
  3048. if (!vRecv.empty())
  3049. vRecv >> pfrom->nStartingHeight;
  3050. if (!vRecv.empty())
  3051. vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
  3052. else
  3053. pfrom->fRelayTxes = true;
  3054. // Disconnect if we connected to ourself
  3055. if (nNonce == nLocalHostNonce && nNonce > 1)
  3056. {
  3057. LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
  3058. pfrom->fDisconnect = true;
  3059. return true;
  3060. }
  3061. pfrom->addrLocal = addrMe;
  3062. if (pfrom->fInbound && addrMe.IsRoutable())
  3063. {
  3064. SeenLocal(addrMe);
  3065. }
  3066. // Be shy and don't send version until we hear
  3067. if (pfrom->fInbound)
  3068. pfrom->PushVersion();
  3069. pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
  3070. // Potentially mark this peer as a preferred download peer.
  3071. UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
  3072. // Change version
  3073. pfrom->PushMessage("verack");
  3074. pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
  3075. if (!pfrom->fInbound)
  3076. {
  3077. // Advertise our address
  3078. if (fListen && !IsInitialBlockDownload())
  3079. {
  3080. CAddress addr = GetLocalAddress(&pfrom->addr);
  3081. if (addr.IsRoutable())
  3082. {
  3083. pfrom->PushAddress(addr);
  3084. } else if (IsPeerAddrLocalGood(pfrom)) {
  3085. addr.SetIP(pfrom->addrLocal);
  3086. pfrom->PushAddress(addr);
  3087. }
  3088. }
  3089. // Get recent addresses
  3090. if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
  3091. {
  3092. pfrom->PushMessage("getaddr");
  3093. pfrom->fGetAddr = true;
  3094. }
  3095. addrman.Good(pfrom->addr);
  3096. } else {
  3097. if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
  3098. {
  3099. addrman.Add(addrFrom, addrFrom);
  3100. addrman.Good(addrFrom);
  3101. }
  3102. }
  3103. // Relay alerts
  3104. {
  3105. LOCK(cs_mapAlerts);
  3106. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  3107. item.second.RelayTo(pfrom);
  3108. }
  3109. pfrom->fSuccessfullyConnected = true;
  3110. string remoteAddr;
  3111. if (fLogIPs)
  3112. remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
  3113. LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
  3114. pfrom->cleanSubVer, pfrom->nVersion,
  3115. pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
  3116. remoteAddr);
  3117. int64_t nTimeOffset = nTime - GetTime();
  3118. pfrom->nTimeOffset = nTimeOffset;
  3119. AddTimeData(pfrom->addr, nTimeOffset);
  3120. }
  3121. else if (pfrom->nVersion == 0)
  3122. {
  3123. // Must have a version message before anything else
  3124. Misbehaving(pfrom->GetId(), 1);
  3125. return false;
  3126. }
  3127. else if (strCommand == "verack")
  3128. {
  3129. pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
  3130. }
  3131. else if (strCommand == "addr")
  3132. {
  3133. vector<CAddress> vAddr;
  3134. vRecv >> vAddr;
  3135. // Don't want addr from older versions unless seeding
  3136. if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
  3137. return true;
  3138. if (vAddr.size() > 1000)
  3139. {
  3140. Misbehaving(pfrom->GetId(), 20);
  3141. return error("message addr size() = %u", vAddr.size());
  3142. }
  3143. // Store the new addresses
  3144. vector<CAddress> vAddrOk;
  3145. int64_t nNow = GetAdjustedTime();
  3146. int64_t nSince = nNow - 10 * 60;
  3147. BOOST_FOREACH(CAddress& addr, vAddr)
  3148. {
  3149. boost::this_thread::interruption_point();
  3150. if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
  3151. addr.nTime = nNow - 5 * 24 * 60 * 60;
  3152. pfrom->AddAddressKnown(addr);
  3153. bool fReachable = IsReachable(addr);
  3154. if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
  3155. {
  3156. // Relay to a limited number of other nodes
  3157. {
  3158. LOCK(cs_vNodes);
  3159. // Use deterministic randomness to send to the same nodes for 24 hours
  3160. // at a time so the setAddrKnowns of the chosen nodes prevent repeats
  3161. static uint256 hashSalt;
  3162. if (hashSalt.IsNull())
  3163. hashSalt = GetRandHash();
  3164. uint64_t hashAddr = addr.GetHash();
  3165. uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
  3166. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  3167. multimap<uint256, CNode*> mapMix;
  3168. BOOST_FOREACH(CNode* pnode, vNodes)
  3169. {
  3170. if (pnode->nVersion < CADDR_TIME_VERSION)
  3171. continue;
  3172. unsigned int nPointer;
  3173. memcpy(&nPointer, &pnode, sizeof(nPointer));
  3174. uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
  3175. hashKey = Hash(BEGIN(hashKey), END(hashKey));
  3176. mapMix.insert(make_pair(hashKey, pnode));
  3177. }
  3178. int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
  3179. for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
  3180. ((*mi).second)->PushAddress(addr);
  3181. }
  3182. }
  3183. // Do not store addresses outside our network
  3184. if (fReachable)
  3185. vAddrOk.push_back(addr);
  3186. }
  3187. addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
  3188. if (vAddr.size() < 1000)
  3189. pfrom->fGetAddr = false;
  3190. if (pfrom->fOneShot)
  3191. pfrom->fDisconnect = true;
  3192. }
  3193. else if (strCommand == "inv")
  3194. {
  3195. vector<CInv> vInv;
  3196. vRecv >> vInv;
  3197. if (vInv.size() > MAX_INV_SZ)
  3198. {
  3199. Misbehaving(pfrom->GetId(), 20);
  3200. return error("message inv size() = %u", vInv.size());
  3201. }
  3202. LOCK(cs_main);
  3203. std::vector<CInv> vToFetch;
  3204. for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
  3205. {
  3206. const CInv &inv = vInv[nInv];
  3207. boost::this_thread::interruption_point();
  3208. pfrom->AddInventoryKnown(inv);
  3209. bool fAlreadyHave = AlreadyHave(inv);
  3210. LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
  3211. if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
  3212. pfrom->AskFor(inv);
  3213. if (inv.type == MSG_BLOCK) {
  3214. UpdateBlockAvailability(pfrom->GetId(), inv.hash);
  3215. if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
  3216. // First request the headers preceeding the announced block. In the normal fully-synced
  3217. // case where a new block is announced that succeeds the current tip (no reorganization),
  3218. // there are no such headers.
  3219. // Secondly, and only when we are close to being synced, we request the announced block directly,
  3220. // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
  3221. // time the block arrives, the header chain leading up to it is already validated. Not
  3222. // doing this will result in the received block being rejected as an orphan in case it is
  3223. // not a direct successor.
  3224. pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
  3225. CNodeState *nodestate = State(pfrom->GetId());
  3226. if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - Params().TargetSpacing() * 20 &&
  3227. nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
  3228. vToFetch.push_back(inv);
  3229. // Mark block as in flight already, even though the actual "getdata" message only goes out
  3230. // later (within the same cs_main lock, though).
  3231. MarkBlockAsInFlight(pfrom->GetId(), inv.hash);
  3232. }
  3233. LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
  3234. }
  3235. }
  3236. // Track requests for our stuff
  3237. g_signals.Inventory(inv.hash);
  3238. if (pfrom->nSendSize > (SendBufferSize() * 2)) {
  3239. Misbehaving(pfrom->GetId(), 50);
  3240. return error("send buffer size() = %u", pfrom->nSendSize);
  3241. }
  3242. }
  3243. if (!vToFetch.empty())
  3244. pfrom->PushMessage("getdata", vToFetch);
  3245. }
  3246. else if (strCommand == "getdata")
  3247. {
  3248. vector<CInv> vInv;
  3249. vRecv >> vInv;
  3250. if (vInv.size() > MAX_INV_SZ)
  3251. {
  3252. Misbehaving(pfrom->GetId(), 20);
  3253. return error("message getdata size() = %u", vInv.size());
  3254. }
  3255. if (fDebug || (vInv.size() != 1))
  3256. LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
  3257. if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
  3258. LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
  3259. pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
  3260. ProcessGetData(pfrom);
  3261. }
  3262. else if (strCommand == "getblocks")
  3263. {
  3264. CBlockLocator locator;
  3265. uint256 hashStop;
  3266. vRecv >> locator >> hashStop;
  3267. LOCK(cs_main);
  3268. // Find the last block the caller has in the main chain
  3269. CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
  3270. // Send the rest of the chain
  3271. if (pindex)
  3272. pindex = chainActive.Next(pindex);
  3273. int nLimit = 500;
  3274. LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
  3275. for (; pindex; pindex = chainActive.Next(pindex))
  3276. {
  3277. if (pindex->GetBlockHash() == hashStop)
  3278. {
  3279. LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  3280. break;
  3281. }
  3282. pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
  3283. if (--nLimit <= 0)
  3284. {
  3285. // When this block is requested, we'll send an inv that'll make them
  3286. // getblocks the next batch of inventory.
  3287. LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  3288. pfrom->hashContinue = pindex->GetBlockHash();
  3289. break;
  3290. }
  3291. }
  3292. }
  3293. else if (strCommand == "getheaders")
  3294. {
  3295. CBlockLocator locator;
  3296. uint256 hashStop;
  3297. vRecv >> locator >> hashStop;
  3298. LOCK(cs_main);
  3299. CBlockIndex* pindex = NULL;
  3300. if (locator.IsNull())
  3301. {
  3302. // If locator is null, return the hashStop block
  3303. BlockMap::iterator mi = mapBlockIndex.find(hashStop);
  3304. if (mi == mapBlockIndex.end())
  3305. return true;
  3306. pindex = (*mi).second;
  3307. }
  3308. else
  3309. {
  3310. // Find the last block the caller has in the main chain
  3311. pindex = FindForkInGlobalIndex(chainActive, locator);
  3312. if (pindex)
  3313. pindex = chainActive.Next(pindex);
  3314. }
  3315. // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
  3316. vector<CBlock> vHeaders;
  3317. int nLimit = MAX_HEADERS_RESULTS;
  3318. LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
  3319. for (; pindex; pindex = chainActive.Next(pindex))
  3320. {
  3321. vHeaders.push_back(pindex->GetBlockHeader());
  3322. if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
  3323. break;
  3324. }
  3325. pfrom->PushMessage("headers", vHeaders);
  3326. }
  3327. else if (strCommand == "tx")
  3328. {
  3329. vector<uint256> vWorkQueue;
  3330. vector<uint256> vEraseQueue;
  3331. CTransaction tx;
  3332. vRecv >> tx;
  3333. CInv inv(MSG_TX, tx.GetHash());
  3334. pfrom->AddInventoryKnown(inv);
  3335. LOCK(cs_main);
  3336. bool fMissingInputs = false;
  3337. CValidationState state;
  3338. mapAlreadyAskedFor.erase(inv);
  3339. if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
  3340. {
  3341. mempool.check(pcoinsTip);
  3342. RelayTransaction(tx);
  3343. vWorkQueue.push_back(inv.hash);
  3344. vEraseQueue.push_back(inv.hash);
  3345. LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
  3346. pfrom->id, pfrom->cleanSubVer,
  3347. tx.GetHash().ToString(),
  3348. mempool.mapTx.size());
  3349. // Recursively process any orphan transactions that depended on this one
  3350. set<NodeId> setMisbehaving;
  3351. for (unsigned int i = 0; i < vWorkQueue.size(); i++)
  3352. {
  3353. map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
  3354. if (itByPrev == mapOrphanTransactionsByPrev.end())
  3355. continue;
  3356. for (set<uint256>::iterator mi = itByPrev->second.begin();
  3357. mi != itByPrev->second.end();
  3358. ++mi)
  3359. {
  3360. const uint256& orphanHash = *mi;
  3361. const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
  3362. NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
  3363. bool fMissingInputs2 = false;
  3364. // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
  3365. // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
  3366. // anyone relaying LegitTxX banned)
  3367. CValidationState stateDummy;
  3368. vEraseQueue.push_back(orphanHash);
  3369. if (setMisbehaving.count(fromPeer))
  3370. continue;
  3371. if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
  3372. {
  3373. LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
  3374. RelayTransaction(orphanTx);
  3375. vWorkQueue.push_back(orphanHash);
  3376. }
  3377. else if (!fMissingInputs2)
  3378. {
  3379. int nDos = 0;
  3380. if (stateDummy.IsInvalid(nDos) && nDos > 0)
  3381. {
  3382. // Punish peer that gave us an invalid orphan tx
  3383. Misbehaving(fromPeer, nDos);
  3384. setMisbehaving.insert(fromPeer);
  3385. LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
  3386. }
  3387. // too-little-fee orphan
  3388. LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
  3389. }
  3390. mempool.check(pcoinsTip);
  3391. }
  3392. }
  3393. BOOST_FOREACH(uint256 hash, vEraseQueue)
  3394. EraseOrphanTx(hash);
  3395. }
  3396. else if (fMissingInputs)
  3397. {
  3398. AddOrphanTx(tx, pfrom->GetId());
  3399. // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
  3400. unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
  3401. unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
  3402. if (nEvicted > 0)
  3403. LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
  3404. } else if (pfrom->fWhitelisted) {
  3405. // Always relay transactions received from whitelisted peers, even
  3406. // if they are already in the mempool (allowing the node to function
  3407. // as a gateway for nodes hidden behind it).
  3408. RelayTransaction(tx);
  3409. }
  3410. int nDoS = 0;
  3411. if (state.IsInvalid(nDoS))
  3412. {
  3413. LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
  3414. pfrom->id, pfrom->cleanSubVer,
  3415. state.GetRejectReason());
  3416. pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
  3417. state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
  3418. if (nDoS > 0)
  3419. Misbehaving(pfrom->GetId(), nDoS);
  3420. }
  3421. }
  3422. else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
  3423. {
  3424. std::vector<CBlockHeader> headers;
  3425. // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
  3426. unsigned int nCount = ReadCompactSize(vRecv);
  3427. if (nCount > MAX_HEADERS_RESULTS) {
  3428. Misbehaving(pfrom->GetId(), 20);
  3429. return error("headers message size = %u", nCount);
  3430. }
  3431. headers.resize(nCount);
  3432. for (unsigned int n = 0; n < nCount; n++) {
  3433. vRecv >> headers[n];
  3434. ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
  3435. }
  3436. LOCK(cs_main);
  3437. if (nCount == 0) {
  3438. // Nothing interesting. Stop asking this peers for more headers.
  3439. return true;
  3440. }
  3441. CBlockIndex *pindexLast = NULL;
  3442. BOOST_FOREACH(const CBlockHeader& header, headers) {
  3443. CValidationState state;
  3444. if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
  3445. Misbehaving(pfrom->GetId(), 20);
  3446. return error("non-continuous headers sequence");
  3447. }
  3448. if (!AcceptBlockHeader(header, state, &pindexLast)) {
  3449. int nDoS;
  3450. if (state.IsInvalid(nDoS)) {
  3451. if (nDoS > 0)
  3452. Misbehaving(pfrom->GetId(), nDoS);
  3453. return error("invalid header received");
  3454. }
  3455. }
  3456. }
  3457. if (pindexLast)
  3458. UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
  3459. if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
  3460. // Headers message had its maximum size; the peer may have more headers.
  3461. // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
  3462. // from there instead.
  3463. LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
  3464. pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
  3465. }
  3466. }
  3467. else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
  3468. {
  3469. CBlock block;
  3470. vRecv >> block;
  3471. CInv inv(MSG_BLOCK, block.GetHash());
  3472. LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
  3473. pfrom->AddInventoryKnown(inv);
  3474. CValidationState state;
  3475. ProcessNewBlock(state, pfrom, &block);
  3476. int nDoS;
  3477. if (state.IsInvalid(nDoS)) {
  3478. pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
  3479. state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
  3480. if (nDoS > 0) {
  3481. LOCK(cs_main);
  3482. Misbehaving(pfrom->GetId(), nDoS);
  3483. }
  3484. }
  3485. }
  3486. // This asymmetric behavior for inbound and outbound connections was introduced
  3487. // to prevent a fingerprinting attack: an attacker can send specific fake addresses
  3488. // to users' AddrMan and later request them by sending getaddr messages.
  3489. // Making users (which are behind NAT and can only make outgoing connections) ignore
  3490. // getaddr message mitigates the attack.
  3491. else if ((strCommand == "getaddr") && (pfrom->fInbound))
  3492. {
  3493. pfrom->vAddrToSend.clear();
  3494. vector<CAddress> vAddr = addrman.GetAddr();
  3495. BOOST_FOREACH(const CAddress &addr, vAddr)
  3496. pfrom->PushAddress(addr);
  3497. }
  3498. else if (strCommand == "mempool")
  3499. {
  3500. LOCK2(cs_main, pfrom->cs_filter);
  3501. std::vector<uint256> vtxid;
  3502. mempool.queryHashes(vtxid);
  3503. vector<CInv> vInv;
  3504. BOOST_FOREACH(uint256& hash, vtxid) {
  3505. CInv inv(MSG_TX, hash);
  3506. CTransaction tx;
  3507. bool fInMemPool = mempool.lookup(hash, tx);
  3508. if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
  3509. if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
  3510. (!pfrom->pfilter))
  3511. vInv.push_back(inv);
  3512. if (vInv.size() == MAX_INV_SZ) {
  3513. pfrom->PushMessage("inv", vInv);
  3514. vInv.clear();
  3515. }
  3516. }
  3517. if (vInv.size() > 0)
  3518. pfrom->PushMessage("inv", vInv);
  3519. }
  3520. else if (strCommand == "ping")
  3521. {
  3522. if (pfrom->nVersion > BIP0031_VERSION)
  3523. {
  3524. uint64_t nonce = 0;
  3525. vRecv >> nonce;
  3526. // Echo the message back with the nonce. This allows for two useful features:
  3527. //
  3528. // 1) A remote node can quickly check if the connection is operational
  3529. // 2) Remote nodes can measure the latency of the network thread. If this node
  3530. // is overloaded it won't respond to pings quickly and the remote node can
  3531. // avoid sending us more work, like chain download requests.
  3532. //
  3533. // The nonce stops the remote getting confused between different pings: without
  3534. // it, if the remote node sends a ping once per second and this node takes 5
  3535. // seconds to respond to each, the 5th ping the remote sends would appear to
  3536. // return very quickly.
  3537. pfrom->PushMessage("pong", nonce);
  3538. }
  3539. }
  3540. else if (strCommand == "pong")
  3541. {
  3542. int64_t pingUsecEnd = nTimeReceived;
  3543. uint64_t nonce = 0;
  3544. size_t nAvail = vRecv.in_avail();
  3545. bool bPingFinished = false;
  3546. std::string sProblem;
  3547. if (nAvail >= sizeof(nonce)) {
  3548. vRecv >> nonce;
  3549. // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
  3550. if (pfrom->nPingNonceSent != 0) {
  3551. if (nonce == pfrom->nPingNonceSent) {
  3552. // Matching pong received, this ping is no longer outstanding
  3553. bPingFinished = true;
  3554. int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
  3555. if (pingUsecTime > 0) {
  3556. // Successful ping time measurement, replace previous
  3557. pfrom->nPingUsecTime = pingUsecTime;
  3558. } else {
  3559. // This should never happen
  3560. sProblem = "Timing mishap";
  3561. }
  3562. } else {
  3563. // Nonce mismatches are normal when pings are overlapping
  3564. sProblem = "Nonce mismatch";
  3565. if (nonce == 0) {
  3566. // This is most likely a bug in another implementation somewhere, cancel this ping
  3567. bPingFinished = true;
  3568. sProblem = "Nonce zero";
  3569. }
  3570. }
  3571. } else {
  3572. sProblem = "Unsolicited pong without ping";
  3573. }
  3574. } else {
  3575. // This is most likely a bug in another implementation somewhere, cancel this ping
  3576. bPingFinished = true;
  3577. sProblem = "Short payload";
  3578. }
  3579. if (!(sProblem.empty())) {
  3580. LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
  3581. pfrom->id,
  3582. pfrom->cleanSubVer,
  3583. sProblem,
  3584. pfrom->nPingNonceSent,
  3585. nonce,
  3586. nAvail);
  3587. }
  3588. if (bPingFinished) {
  3589. pfrom->nPingNonceSent = 0;
  3590. }
  3591. }
  3592. else if (strCommand == "alert")
  3593. {
  3594. CAlert alert;
  3595. vRecv >> alert;
  3596. uint256 alertHash = alert.GetHash();
  3597. if (pfrom->setKnown.count(alertHash) == 0)
  3598. {
  3599. if (alert.ProcessAlert())
  3600. {
  3601. // Relay
  3602. pfrom->setKnown.insert(alertHash);
  3603. {
  3604. LOCK(cs_vNodes);
  3605. BOOST_FOREACH(CNode* pnode, vNodes)
  3606. alert.RelayTo(pnode);
  3607. }
  3608. }
  3609. else {
  3610. // Small DoS penalty so peers that send us lots of
  3611. // duplicate/expired/invalid-signature/whatever alerts
  3612. // eventually get banned.
  3613. // This isn't a Misbehaving(100) (immediate ban) because the
  3614. // peer might be an older or different implementation with
  3615. // a different signature key, etc.
  3616. Misbehaving(pfrom->GetId(), 10);
  3617. }
  3618. }
  3619. }
  3620. else if (strCommand == "filterload")
  3621. {
  3622. CBloomFilter filter;
  3623. vRecv >> filter;
  3624. if (!filter.IsWithinSizeConstraints())
  3625. // There is no excuse for sending a too-large filter
  3626. Misbehaving(pfrom->GetId(), 100);
  3627. else
  3628. {
  3629. LOCK(pfrom->cs_filter);
  3630. delete pfrom->pfilter;
  3631. pfrom->pfilter = new CBloomFilter(filter);
  3632. pfrom->pfilter->UpdateEmptyFull();
  3633. }
  3634. pfrom->fRelayTxes = true;
  3635. }
  3636. else if (strCommand == "filteradd")
  3637. {
  3638. vector<unsigned char> vData;
  3639. vRecv >> vData;
  3640. // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
  3641. // and thus, the maximum size any matched object can have) in a filteradd message
  3642. if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
  3643. {
  3644. Misbehaving(pfrom->GetId(), 100);
  3645. } else {
  3646. LOCK(pfrom->cs_filter);
  3647. if (pfrom->pfilter)
  3648. pfrom->pfilter->insert(vData);
  3649. else
  3650. Misbehaving(pfrom->GetId(), 100);
  3651. }
  3652. }
  3653. else if (strCommand == "filterclear")
  3654. {
  3655. LOCK(pfrom->cs_filter);
  3656. delete pfrom->pfilter;
  3657. pfrom->pfilter = new CBloomFilter();
  3658. pfrom->fRelayTxes = true;
  3659. }
  3660. else if (strCommand == "reject")
  3661. {
  3662. if (fDebug) {
  3663. try {
  3664. string strMsg; unsigned char ccode; string strReason;
  3665. vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
  3666. ostringstream ss;
  3667. ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
  3668. if (strMsg == "block" || strMsg == "tx")
  3669. {
  3670. uint256 hash;
  3671. vRecv >> hash;
  3672. ss << ": hash " << hash.ToString();
  3673. }
  3674. LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
  3675. } catch (const std::ios_base::failure&) {
  3676. // Avoid feedback loops by preventing reject messages from triggering a new reject message.
  3677. LogPrint("net", "Unparseable reject message received\n");
  3678. }
  3679. }
  3680. }
  3681. else
  3682. {
  3683. // Ignore unknown commands for extensibility
  3684. LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
  3685. }
  3686. // Update the last seen time for this node's address
  3687. if (pfrom->fNetworkNode)
  3688. if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
  3689. AddressCurrentlyConnected(pfrom->addr);
  3690. return true;
  3691. }
  3692. // requires LOCK(cs_vRecvMsg)
  3693. bool ProcessMessages(CNode* pfrom)
  3694. {
  3695. //if (fDebug)
  3696. // LogPrintf("ProcessMessages(%u messages)\n", pfrom->vRecvMsg.size());
  3697. //
  3698. // Message format
  3699. // (4) message start
  3700. // (12) command
  3701. // (4) size
  3702. // (4) checksum
  3703. // (x) data
  3704. //
  3705. bool fOk = true;
  3706. if (!pfrom->vRecvGetData.empty())
  3707. ProcessGetData(pfrom);
  3708. // this maintains the order of responses
  3709. if (!pfrom->vRecvGetData.empty()) return fOk;
  3710. std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
  3711. while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
  3712. // Don't bother if send buffer is too full to respond anyway
  3713. if (pfrom->nSendSize >= SendBufferSize())
  3714. break;
  3715. // get next message
  3716. CNetMessage& msg = *it;
  3717. //if (fDebug)
  3718. // LogPrintf("ProcessMessages(message %u msgsz, %u bytes, complete:%s)\n",
  3719. // msg.hdr.nMessageSize, msg.vRecv.size(),
  3720. // msg.complete() ? "Y" : "N");
  3721. // end, if an incomplete message is found
  3722. if (!msg.complete())
  3723. break;
  3724. // at this point, any failure means we can delete the current message
  3725. it++;
  3726. // Scan for message start
  3727. if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
  3728. LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
  3729. fOk = false;
  3730. break;
  3731. }
  3732. // Read header
  3733. CMessageHeader& hdr = msg.hdr;
  3734. if (!hdr.IsValid(Params().MessageStart()))
  3735. {
  3736. LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
  3737. continue;
  3738. }
  3739. string strCommand = hdr.GetCommand();
  3740. // Message size
  3741. unsigned int nMessageSize = hdr.nMessageSize;
  3742. // Checksum
  3743. CDataStream& vRecv = msg.vRecv;
  3744. uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
  3745. unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
  3746. if (nChecksum != hdr.nChecksum)
  3747. {
  3748. LogPrintf("ProcessMessages(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
  3749. SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
  3750. continue;
  3751. }
  3752. // Process message
  3753. bool fRet = false;
  3754. try
  3755. {
  3756. fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
  3757. boost::this_thread::interruption_point();
  3758. }
  3759. catch (const std::ios_base::failure& e)
  3760. {
  3761. pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
  3762. if (strstr(e.what(), "end of data"))
  3763. {
  3764. // Allow exceptions from under-length message on vRecv
  3765. LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", SanitizeString(strCommand), nMessageSize, e.what());
  3766. }
  3767. else if (strstr(e.what(), "size too large"))
  3768. {
  3769. // Allow exceptions from over-long size
  3770. LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught\n", SanitizeString(strCommand), nMessageSize, e.what());
  3771. }
  3772. else
  3773. {
  3774. PrintExceptionContinue(&e, "ProcessMessages()");
  3775. }
  3776. }
  3777. catch (const boost::thread_interrupted&) {
  3778. throw;
  3779. }
  3780. catch (const std::exception& e) {
  3781. PrintExceptionContinue(&e, "ProcessMessages()");
  3782. } catch (...) {
  3783. PrintExceptionContinue(NULL, "ProcessMessages()");
  3784. }
  3785. if (!fRet)
  3786. LogPrintf("ProcessMessage(%s, %u bytes) FAILED peer=%d\n", SanitizeString(strCommand), nMessageSize, pfrom->id);
  3787. break;
  3788. }
  3789. // In case the connection got shut down, its receive buffer was wiped
  3790. if (!pfrom->fDisconnect)
  3791. pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
  3792. return fOk;
  3793. }
  3794. bool SendMessages(CNode* pto, bool fSendTrickle)
  3795. {
  3796. {
  3797. // Don't send anything until we get their version message
  3798. if (pto->nVersion == 0)
  3799. return true;
  3800. //
  3801. // Message: ping
  3802. //
  3803. bool pingSend = false;
  3804. if (pto->fPingQueued) {
  3805. // RPC ping request by user
  3806. pingSend = true;
  3807. }
  3808. if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
  3809. // Ping automatically sent as a latency probe & keepalive.
  3810. pingSend = true;
  3811. }
  3812. if (pingSend) {
  3813. uint64_t nonce = 0;
  3814. while (nonce == 0) {
  3815. GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
  3816. }
  3817. pto->fPingQueued = false;
  3818. pto->nPingUsecStart = GetTimeMicros();
  3819. if (pto->nVersion > BIP0031_VERSION) {
  3820. pto->nPingNonceSent = nonce;
  3821. pto->PushMessage("ping", nonce);
  3822. } else {
  3823. // Peer is too old to support ping command with nonce, pong will never arrive.
  3824. pto->nPingNonceSent = 0;
  3825. pto->PushMessage("ping");
  3826. }
  3827. }
  3828. TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
  3829. if (!lockMain)
  3830. return true;
  3831. // Address refresh broadcast
  3832. static int64_t nLastRebroadcast;
  3833. if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
  3834. {
  3835. LOCK(cs_vNodes);
  3836. BOOST_FOREACH(CNode* pnode, vNodes)
  3837. {
  3838. // Periodically clear setAddrKnown to allow refresh broadcasts
  3839. if (nLastRebroadcast)
  3840. pnode->setAddrKnown.clear();
  3841. // Rebroadcast our address
  3842. AdvertizeLocal(pnode);
  3843. }
  3844. if (!vNodes.empty())
  3845. nLastRebroadcast = GetTime();
  3846. }
  3847. //
  3848. // Message: addr
  3849. //
  3850. if (fSendTrickle)
  3851. {
  3852. vector<CAddress> vAddr;
  3853. vAddr.reserve(pto->vAddrToSend.size());
  3854. BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
  3855. {
  3856. // returns true if wasn't already contained in the set
  3857. if (pto->setAddrKnown.insert(addr).second)
  3858. {
  3859. vAddr.push_back(addr);
  3860. // receiver rejects addr messages larger than 1000
  3861. if (vAddr.size() >= 1000)
  3862. {
  3863. pto->PushMessage("addr", vAddr);
  3864. vAddr.clear();
  3865. }
  3866. }
  3867. }
  3868. pto->vAddrToSend.clear();
  3869. if (!vAddr.empty())
  3870. pto->PushMessage("addr", vAddr);
  3871. }
  3872. CNodeState &state = *State(pto->GetId());
  3873. if (state.fShouldBan) {
  3874. if (pto->fWhitelisted)
  3875. LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
  3876. else {
  3877. pto->fDisconnect = true;
  3878. if (pto->addr.IsLocal())
  3879. LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
  3880. else
  3881. {
  3882. CNode::Ban(pto->addr);
  3883. }
  3884. }
  3885. state.fShouldBan = false;
  3886. }
  3887. BOOST_FOREACH(const CBlockReject& reject, state.rejects)
  3888. pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
  3889. state.rejects.clear();
  3890. // Start block sync
  3891. if (pindexBestHeader == NULL)
  3892. pindexBestHeader = chainActive.Tip();
  3893. 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.
  3894. if (!state.fSyncStarted && !pto->fClient && fFetch && !fImporting && !fReindex) {
  3895. // Only actively request headers from a single peer, unless we're close to today.
  3896. if (nSyncStarted == 0 || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
  3897. state.fSyncStarted = true;
  3898. nSyncStarted++;
  3899. CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
  3900. LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
  3901. pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
  3902. }
  3903. }
  3904. // Resend wallet transactions that haven't gotten in a block yet
  3905. // Except during reindex, importing and IBD, when old wallet
  3906. // transactions become unconfirmed and spams other nodes.
  3907. if (!fReindex && !fImporting && !IsInitialBlockDownload())
  3908. {
  3909. g_signals.Broadcast();
  3910. }
  3911. //
  3912. // Message: inventory
  3913. //
  3914. vector<CInv> vInv;
  3915. vector<CInv> vInvWait;
  3916. {
  3917. LOCK(pto->cs_inventory);
  3918. vInv.reserve(pto->vInventoryToSend.size());
  3919. vInvWait.reserve(pto->vInventoryToSend.size());
  3920. BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
  3921. {
  3922. if (pto->setInventoryKnown.count(inv))
  3923. continue;
  3924. // trickle out tx inv to protect privacy
  3925. if (inv.type == MSG_TX && !fSendTrickle)
  3926. {
  3927. // 1/4 of tx invs blast to all immediately
  3928. static uint256 hashSalt;
  3929. if (hashSalt.IsNull())
  3930. hashSalt = GetRandHash();
  3931. uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
  3932. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  3933. bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
  3934. if (fTrickleWait)
  3935. {
  3936. vInvWait.push_back(inv);
  3937. continue;
  3938. }
  3939. }
  3940. // returns true if wasn't already contained in the set
  3941. if (pto->setInventoryKnown.insert(inv).second)
  3942. {
  3943. vInv.push_back(inv);
  3944. if (vInv.size() >= 1000)
  3945. {
  3946. pto->PushMessage("inv", vInv);
  3947. vInv.clear();
  3948. }
  3949. }
  3950. }
  3951. pto->vInventoryToSend = vInvWait;
  3952. }
  3953. if (!vInv.empty())
  3954. pto->PushMessage("inv", vInv);
  3955. // Detect whether we're stalling
  3956. int64_t nNow = GetTimeMicros();
  3957. if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
  3958. // Stalling only triggers when the block download window cannot move. During normal steady state,
  3959. // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
  3960. // should only happen during initial block download.
  3961. LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
  3962. pto->fDisconnect = true;
  3963. }
  3964. // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
  3965. // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
  3966. // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
  3967. // being saturated. We only count validated in-flight blocks so peers can't advertize nonexisting block hashes
  3968. // to unreasonably increase our timeout.
  3969. if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0 && state.vBlocksInFlight.front().nTime < nNow - 500000 * Params().TargetSpacing() * (4 + state.vBlocksInFlight.front().nValidatedQueuedBefore)) {
  3970. LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", state.vBlocksInFlight.front().hash.ToString(), pto->id);
  3971. pto->fDisconnect = true;
  3972. }
  3973. //
  3974. // Message: getdata (blocks)
  3975. //
  3976. vector<CInv> vGetData;
  3977. if (!pto->fDisconnect && !pto->fClient && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
  3978. vector<CBlockIndex*> vToDownload;
  3979. NodeId staller = -1;
  3980. FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
  3981. BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
  3982. vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
  3983. MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
  3984. LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
  3985. pindex->nHeight, pto->id);
  3986. }
  3987. if (state.nBlocksInFlight == 0 && staller != -1) {
  3988. if (State(staller)->nStallingSince == 0) {
  3989. State(staller)->nStallingSince = nNow;
  3990. LogPrint("net", "Stall started peer=%d\n", staller);
  3991. }
  3992. }
  3993. }
  3994. //
  3995. // Message: getdata (non-blocks)
  3996. //
  3997. while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
  3998. {
  3999. const CInv& inv = (*pto->mapAskFor.begin()).second;
  4000. if (!AlreadyHave(inv))
  4001. {
  4002. if (fDebug)
  4003. LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
  4004. vGetData.push_back(inv);
  4005. if (vGetData.size() >= 1000)
  4006. {
  4007. pto->PushMessage("getdata", vGetData);
  4008. vGetData.clear();
  4009. }
  4010. }
  4011. pto->mapAskFor.erase(pto->mapAskFor.begin());
  4012. }
  4013. if (!vGetData.empty())
  4014. pto->PushMessage("getdata", vGetData);
  4015. }
  4016. return true;
  4017. }
  4018. std::string CBlockFileInfo::ToString() const {
  4019. return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
  4020. }
  4021. class CMainCleanup
  4022. {
  4023. public:
  4024. CMainCleanup() {}
  4025. ~CMainCleanup() {
  4026. // block headers
  4027. BlockMap::iterator it1 = mapBlockIndex.begin();
  4028. for (; it1 != mapBlockIndex.end(); it1++)
  4029. delete (*it1).second;
  4030. mapBlockIndex.clear();
  4031. // orphan transactions
  4032. mapOrphanTransactions.clear();
  4033. mapOrphanTransactionsByPrev.clear();
  4034. }
  4035. } instance_of_cmaincleanup;