Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

main.cpp 177KB

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