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

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