Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

main.cpp 159KB

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