You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.cpp 167KB

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