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

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