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

main.cpp 199KB

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