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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998
  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. unsigned int nCoinCacheSize = 5000;
  51. uint64_t nPruneTarget = 0;
  52. /** Fees smaller than this (in satoshi) are considered zero fee (for relaying and mining) */
  53. CFeeRate minRelayTxFee = CFeeRate(1000);
  54. CTxMemPool mempool(::minRelayTxFee);
  55. struct COrphanTx {
  56. CTransaction tx;
  57. NodeId fromPeer;
  58. };
  59. map<uint256, COrphanTx> mapOrphanTransactions;
  60. map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
  61. void EraseOrphansFor(NodeId peer);
  62. /**
  63. * Returns true if there are nRequired or more blocks of minVersion or above
  64. * in the last Params().ToCheckBlockUpgradeMajority() blocks, starting at pstart
  65. * and going backwards.
  66. */
  67. static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired);
  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());
  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);
  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 GetBlockValue(int nHeight, const CAmount& nFees)
  1017. {
  1018. CAmount nSubsidy = 50 * COIN;
  1019. int halvings = nHeight / Params().SubsidyHalvingInterval();
  1020. // Force block reward to zero when right shift is undefined.
  1021. if (halvings >= 64)
  1022. return nFees;
  1023. // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
  1024. nSubsidy >>= halvings;
  1025. return nSubsidy + nFees;
  1026. }
  1027. bool IsInitialBlockDownload()
  1028. {
  1029. LOCK(cs_main);
  1030. if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
  1031. return true;
  1032. static bool lockIBDState = false;
  1033. if (lockIBDState)
  1034. return false;
  1035. bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
  1036. pindexBestHeader->GetBlockTime() < GetTime() - 24 * 60 * 60);
  1037. if (!state)
  1038. lockIBDState = true;
  1039. return state;
  1040. }
  1041. bool fLargeWorkForkFound = false;
  1042. bool fLargeWorkInvalidChainFound = false;
  1043. CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
  1044. void CheckForkWarningConditions()
  1045. {
  1046. AssertLockHeld(cs_main);
  1047. // Before we get past initial download, we cannot reliably alert about forks
  1048. // (we assume we don't get stuck on a fork before the last checkpoint)
  1049. if (IsInitialBlockDownload())
  1050. return;
  1051. // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
  1052. // of our head, drop it
  1053. if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
  1054. pindexBestForkTip = NULL;
  1055. if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
  1056. {
  1057. if (!fLargeWorkForkFound && pindexBestForkBase)
  1058. {
  1059. std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
  1060. pindexBestForkBase->phashBlock->ToString() + std::string("'");
  1061. CAlert::Notify(warning, true);
  1062. }
  1063. if (pindexBestForkTip && pindexBestForkBase)
  1064. {
  1065. 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__,
  1066. pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
  1067. pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
  1068. fLargeWorkForkFound = true;
  1069. }
  1070. else
  1071. {
  1072. LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
  1073. fLargeWorkInvalidChainFound = true;
  1074. }
  1075. }
  1076. else
  1077. {
  1078. fLargeWorkForkFound = false;
  1079. fLargeWorkInvalidChainFound = false;
  1080. }
  1081. }
  1082. void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
  1083. {
  1084. AssertLockHeld(cs_main);
  1085. // If we are on a fork that is sufficiently large, set a warning flag
  1086. CBlockIndex* pfork = pindexNewForkTip;
  1087. CBlockIndex* plonger = chainActive.Tip();
  1088. while (pfork && pfork != plonger)
  1089. {
  1090. while (plonger && plonger->nHeight > pfork->nHeight)
  1091. plonger = plonger->pprev;
  1092. if (pfork == plonger)
  1093. break;
  1094. pfork = pfork->pprev;
  1095. }
  1096. // We define a condition where we should warn the user about as a fork of at least 7 blocks
  1097. // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
  1098. // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
  1099. // hash rate operating on the fork.
  1100. // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
  1101. // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
  1102. // the 7-block condition and from this always have the most-likely-to-cause-warning fork
  1103. if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
  1104. pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
  1105. chainActive.Height() - pindexNewForkTip->nHeight < 72)
  1106. {
  1107. pindexBestForkTip = pindexNewForkTip;
  1108. pindexBestForkBase = pfork;
  1109. }
  1110. CheckForkWarningConditions();
  1111. }
  1112. // Requires cs_main.
  1113. void Misbehaving(NodeId pnode, int howmuch)
  1114. {
  1115. if (howmuch == 0)
  1116. return;
  1117. CNodeState *state = State(pnode);
  1118. if (state == NULL)
  1119. return;
  1120. state->nMisbehavior += howmuch;
  1121. int banscore = GetArg("-banscore", 100);
  1122. if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore)
  1123. {
  1124. LogPrintf("%s: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
  1125. state->fShouldBan = true;
  1126. } else
  1127. LogPrintf("%s: %s (%d -> %d)\n", __func__, state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
  1128. }
  1129. void static InvalidChainFound(CBlockIndex* pindexNew)
  1130. {
  1131. if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
  1132. pindexBestInvalid = pindexNew;
  1133. LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
  1134. pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
  1135. log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
  1136. pindexNew->GetBlockTime()));
  1137. LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
  1138. chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
  1139. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
  1140. CheckForkWarningConditions();
  1141. }
  1142. void static InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
  1143. int nDoS = 0;
  1144. if (state.IsInvalid(nDoS)) {
  1145. std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
  1146. if (it != mapBlockSource.end() && State(it->second)) {
  1147. CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
  1148. State(it->second)->rejects.push_back(reject);
  1149. if (nDoS > 0)
  1150. Misbehaving(it->second, nDoS);
  1151. }
  1152. }
  1153. if (!state.CorruptionPossible()) {
  1154. pindex->nStatus |= BLOCK_FAILED_VALID;
  1155. setDirtyBlockIndex.insert(pindex);
  1156. setBlockIndexCandidates.erase(pindex);
  1157. InvalidChainFound(pindex);
  1158. }
  1159. }
  1160. void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight)
  1161. {
  1162. // mark inputs spent
  1163. if (!tx.IsCoinBase()) {
  1164. txundo.vprevout.reserve(tx.vin.size());
  1165. BOOST_FOREACH(const CTxIn &txin, tx.vin) {
  1166. CCoinsModifier coins = inputs.ModifyCoins(txin.prevout.hash);
  1167. unsigned nPos = txin.prevout.n;
  1168. if (nPos >= coins->vout.size() || coins->vout[nPos].IsNull())
  1169. assert(false);
  1170. // mark an outpoint spent, and construct undo information
  1171. txundo.vprevout.push_back(CTxInUndo(coins->vout[nPos]));
  1172. coins->Spend(nPos);
  1173. if (coins->vout.size() == 0) {
  1174. CTxInUndo& undo = txundo.vprevout.back();
  1175. undo.nHeight = coins->nHeight;
  1176. undo.fCoinBase = coins->fCoinBase;
  1177. undo.nVersion = coins->nVersion;
  1178. }
  1179. }
  1180. }
  1181. // add outputs
  1182. inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
  1183. }
  1184. void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, int nHeight)
  1185. {
  1186. CTxUndo txundo;
  1187. UpdateCoins(tx, state, inputs, txundo, nHeight);
  1188. }
  1189. bool CScriptCheck::operator()() {
  1190. const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
  1191. if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
  1192. return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
  1193. }
  1194. return true;
  1195. }
  1196. bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck> *pvChecks)
  1197. {
  1198. if (!tx.IsCoinBase())
  1199. {
  1200. if (pvChecks)
  1201. pvChecks->reserve(tx.vin.size());
  1202. // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
  1203. // for an attacker to attempt to split the network.
  1204. if (!inputs.HaveInputs(tx))
  1205. return state.Invalid(error("CheckInputs(): %s inputs unavailable", tx.GetHash().ToString()));
  1206. // While checking, GetBestBlock() refers to the parent block.
  1207. // This is also true for mempool checks.
  1208. CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
  1209. int nSpendHeight = pindexPrev->nHeight + 1;
  1210. CAmount nValueIn = 0;
  1211. CAmount nFees = 0;
  1212. for (unsigned int i = 0; i < tx.vin.size(); i++)
  1213. {
  1214. const COutPoint &prevout = tx.vin[i].prevout;
  1215. const CCoins *coins = inputs.AccessCoins(prevout.hash);
  1216. assert(coins);
  1217. // If prev is coinbase, check that it's matured
  1218. if (coins->IsCoinBase()) {
  1219. if (nSpendHeight - coins->nHeight < COINBASE_MATURITY)
  1220. return state.Invalid(
  1221. error("CheckInputs(): tried to spend coinbase at depth %d", nSpendHeight - coins->nHeight),
  1222. REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
  1223. }
  1224. // Check for negative or overflow input values
  1225. nValueIn += coins->vout[prevout.n].nValue;
  1226. if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
  1227. return state.DoS(100, error("CheckInputs(): txin values out of range"),
  1228. REJECT_INVALID, "bad-txns-inputvalues-outofrange");
  1229. }
  1230. if (nValueIn < tx.GetValueOut())
  1231. return state.DoS(100, error("CheckInputs(): %s value in (%s) < value out (%s)",
  1232. tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
  1233. REJECT_INVALID, "bad-txns-in-belowout");
  1234. // Tally transaction fees
  1235. CAmount nTxFee = nValueIn - tx.GetValueOut();
  1236. if (nTxFee < 0)
  1237. return state.DoS(100, error("CheckInputs(): %s nTxFee < 0", tx.GetHash().ToString()),
  1238. REJECT_INVALID, "bad-txns-fee-negative");
  1239. nFees += nTxFee;
  1240. if (!MoneyRange(nFees))
  1241. return state.DoS(100, error("CheckInputs(): nFees out of range"),
  1242. REJECT_INVALID, "bad-txns-fee-outofrange");
  1243. // The first loop above does all the inexpensive checks.
  1244. // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
  1245. // Helps prevent CPU exhaustion attacks.
  1246. // Skip ECDSA signature verification when connecting blocks
  1247. // before the last block chain checkpoint. This is safe because block merkle hashes are
  1248. // still computed and checked, and any change will be caught at the next checkpoint.
  1249. if (fScriptChecks) {
  1250. for (unsigned int i = 0; i < tx.vin.size(); i++) {
  1251. const COutPoint &prevout = tx.vin[i].prevout;
  1252. const CCoins* coins = inputs.AccessCoins(prevout.hash);
  1253. assert(coins);
  1254. // Verify signature
  1255. CScriptCheck check(*coins, tx, i, flags, cacheStore);
  1256. if (pvChecks) {
  1257. pvChecks->push_back(CScriptCheck());
  1258. check.swap(pvChecks->back());
  1259. } else if (!check()) {
  1260. if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
  1261. // Check whether the failure was caused by a
  1262. // non-mandatory script verification check, such as
  1263. // non-standard DER encodings or non-null dummy
  1264. // arguments; if so, don't trigger DoS protection to
  1265. // avoid splitting the network between upgraded and
  1266. // non-upgraded nodes.
  1267. CScriptCheck check(*coins, tx, i,
  1268. flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
  1269. if (check())
  1270. return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
  1271. }
  1272. // Failures of other flags indicate a transaction that is
  1273. // invalid in new blocks, e.g. a invalid P2SH. We DoS ban
  1274. // such nodes as they are not following the protocol. That
  1275. // said during an upgrade careful thought should be taken
  1276. // as to the correct behavior - we may want to continue
  1277. // peering with non-upgraded nodes even after a soft-fork
  1278. // super-majority vote has passed.
  1279. return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
  1280. }
  1281. }
  1282. }
  1283. }
  1284. return true;
  1285. }
  1286. namespace {
  1287. bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock)
  1288. {
  1289. // Open history file to append
  1290. CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
  1291. if (fileout.IsNull())
  1292. return error("%s: OpenUndoFile failed", __func__);
  1293. // Write index header
  1294. unsigned int nSize = fileout.GetSerializeSize(blockundo);
  1295. fileout << FLATDATA(Params().MessageStart()) << nSize;
  1296. // Write undo data
  1297. long fileOutPos = ftell(fileout.Get());
  1298. if (fileOutPos < 0)
  1299. return error("%s: ftell failed", __func__);
  1300. pos.nPos = (unsigned int)fileOutPos;
  1301. fileout << blockundo;
  1302. // calculate & write checksum
  1303. CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
  1304. hasher << hashBlock;
  1305. hasher << blockundo;
  1306. fileout << hasher.GetHash();
  1307. return true;
  1308. }
  1309. bool UndoReadFromDisk(CBlockUndo& blockundo, const CDiskBlockPos& pos, const uint256& hashBlock)
  1310. {
  1311. // Open history file to read
  1312. CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
  1313. if (filein.IsNull())
  1314. return error("%s: OpenBlockFile failed", __func__);
  1315. // Read block
  1316. uint256 hashChecksum;
  1317. try {
  1318. filein >> blockundo;
  1319. filein >> hashChecksum;
  1320. }
  1321. catch (const std::exception& e) {
  1322. return error("%s: Deserialize or I/O error - %s", __func__, e.what());
  1323. }
  1324. // Verify checksum
  1325. CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
  1326. hasher << hashBlock;
  1327. hasher << blockundo;
  1328. if (hashChecksum != hasher.GetHash())
  1329. return error("%s: Checksum mismatch", __func__);
  1330. return true;
  1331. }
  1332. } // anon namespace
  1333. /**
  1334. * Apply the undo operation of a CTxInUndo to the given chain state.
  1335. * @param undo The undo object.
  1336. * @param view The coins view to which to apply the changes.
  1337. * @param out The out point that corresponds to the tx input.
  1338. * @return True on success.
  1339. */
  1340. static bool ApplyTxInUndo(const CTxInUndo& undo, CCoinsViewCache& view, const COutPoint& out)
  1341. {
  1342. bool fClean = true;
  1343. CCoinsModifier coins = view.ModifyCoins(out.hash);
  1344. if (undo.nHeight != 0) {
  1345. // undo data contains height: this is the last output of the prevout tx being spent
  1346. if (!coins->IsPruned())
  1347. fClean = fClean && error("%s: undo data overwriting existing transaction", __func__);
  1348. coins->Clear();
  1349. coins->fCoinBase = undo.fCoinBase;
  1350. coins->nHeight = undo.nHeight;
  1351. coins->nVersion = undo.nVersion;
  1352. } else {
  1353. if (coins->IsPruned())
  1354. fClean = fClean && error("%s: undo data adding output to missing transaction", __func__);
  1355. }
  1356. if (coins->IsAvailable(out.n))
  1357. fClean = fClean && error("%s: undo data overwriting existing output", __func__);
  1358. if (coins->vout.size() < out.n+1)
  1359. coins->vout.resize(out.n+1);
  1360. coins->vout[out.n] = undo.txout;
  1361. return fClean;
  1362. }
  1363. bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
  1364. {
  1365. assert(pindex->GetBlockHash() == view.GetBestBlock());
  1366. if (pfClean)
  1367. *pfClean = false;
  1368. bool fClean = true;
  1369. CBlockUndo blockUndo;
  1370. CDiskBlockPos pos = pindex->GetUndoPos();
  1371. if (pos.IsNull())
  1372. return error("DisconnectBlock(): no undo data available");
  1373. if (!UndoReadFromDisk(blockUndo, pos, pindex->pprev->GetBlockHash()))
  1374. return error("DisconnectBlock(): failure reading undo data");
  1375. if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
  1376. return error("DisconnectBlock(): block and undo data inconsistent");
  1377. // undo transactions in reverse order
  1378. for (int i = block.vtx.size() - 1; i >= 0; i--) {
  1379. const CTransaction &tx = block.vtx[i];
  1380. uint256 hash = tx.GetHash();
  1381. // Check that all outputs are available and match the outputs in the block itself
  1382. // exactly.
  1383. {
  1384. CCoinsModifier outs = view.ModifyCoins(hash);
  1385. outs->ClearUnspendable();
  1386. CCoins outsBlock(tx, pindex->nHeight);
  1387. // The CCoins serialization does not serialize negative numbers.
  1388. // No network rules currently depend on the version here, so an inconsistency is harmless
  1389. // but it must be corrected before txout nversion ever influences a network rule.
  1390. if (outsBlock.nVersion < 0)
  1391. outs->nVersion = outsBlock.nVersion;
  1392. if (*outs != outsBlock)
  1393. fClean = fClean && error("DisconnectBlock(): added transaction mismatch? database corrupted");
  1394. // remove outputs
  1395. outs->Clear();
  1396. }
  1397. // restore inputs
  1398. if (i > 0) { // not coinbases
  1399. const CTxUndo &txundo = blockUndo.vtxundo[i-1];
  1400. if (txundo.vprevout.size() != tx.vin.size())
  1401. return error("DisconnectBlock(): transaction and undo data inconsistent");
  1402. for (unsigned int j = tx.vin.size(); j-- > 0;) {
  1403. const COutPoint &out = tx.vin[j].prevout;
  1404. const CTxInUndo &undo = txundo.vprevout[j];
  1405. if (!ApplyTxInUndo(undo, view, out))
  1406. fClean = false;
  1407. }
  1408. }
  1409. }
  1410. // move best block pointer to prevout block
  1411. view.SetBestBlock(pindex->pprev->GetBlockHash());
  1412. if (pfClean) {
  1413. *pfClean = fClean;
  1414. return true;
  1415. }
  1416. return fClean;
  1417. }
  1418. void static FlushBlockFile(bool fFinalize = false)
  1419. {
  1420. LOCK(cs_LastBlockFile);
  1421. CDiskBlockPos posOld(nLastBlockFile, 0);
  1422. FILE *fileOld = OpenBlockFile(posOld);
  1423. if (fileOld) {
  1424. if (fFinalize)
  1425. TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
  1426. FileCommit(fileOld);
  1427. fclose(fileOld);
  1428. }
  1429. fileOld = OpenUndoFile(posOld);
  1430. if (fileOld) {
  1431. if (fFinalize)
  1432. TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
  1433. FileCommit(fileOld);
  1434. fclose(fileOld);
  1435. }
  1436. }
  1437. bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
  1438. static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
  1439. void ThreadScriptCheck() {
  1440. RenameThread("bitcoin-scriptch");
  1441. scriptcheckqueue.Thread();
  1442. }
  1443. static int64_t nTimeVerify = 0;
  1444. static int64_t nTimeConnect = 0;
  1445. static int64_t nTimeIndex = 0;
  1446. static int64_t nTimeCallbacks = 0;
  1447. static int64_t nTimeTotal = 0;
  1448. bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
  1449. {
  1450. const CChainParams& chainparams = Params();
  1451. AssertLockHeld(cs_main);
  1452. // Check it again in case a previous version let a bad block in
  1453. if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
  1454. return false;
  1455. // verify that the view's current state corresponds to the previous block
  1456. uint256 hashPrevBlock = pindex->pprev == NULL ? uint256() : pindex->pprev->GetBlockHash();
  1457. assert(hashPrevBlock == view.GetBestBlock());
  1458. // Special case for the genesis block, skipping connection of its transactions
  1459. // (its coinbase is unspendable)
  1460. if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
  1461. if (!fJustCheck)
  1462. view.SetBestBlock(pindex->GetBlockHash());
  1463. return true;
  1464. }
  1465. bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
  1466. // Do not allow blocks that contain transactions which 'overwrite' older transactions,
  1467. // unless those are already completely spent.
  1468. // If such overwrites are allowed, coinbases and transactions depending upon those
  1469. // can be duplicated to remove the ability to spend the first instance -- even after
  1470. // being sent to another address.
  1471. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
  1472. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
  1473. // already refuses previously-known transaction ids entirely.
  1474. // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
  1475. // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
  1476. // two in the chain that violate it. This prevents exploiting the issue against nodes during their
  1477. // initial block download.
  1478. bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
  1479. !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
  1480. (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
  1481. if (fEnforceBIP30) {
  1482. BOOST_FOREACH(const CTransaction& tx, block.vtx) {
  1483. const CCoins* coins = view.AccessCoins(tx.GetHash());
  1484. if (coins && !coins->IsPruned())
  1485. return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
  1486. REJECT_INVALID, "bad-txns-BIP30");
  1487. }
  1488. }
  1489. // BIP16 didn't become active until Apr 1 2012
  1490. int64_t nBIP16SwitchTime = 1333238400;
  1491. bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
  1492. unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
  1493. // Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, when 75% of the network has upgraded:
  1494. if (block.nVersion >= 3 && IsSuperMajority(3, pindex->pprev, Params().EnforceBlockUpgradeMajority())) {
  1495. flags |= SCRIPT_VERIFY_DERSIG;
  1496. }
  1497. CBlockUndo blockundo;
  1498. CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
  1499. int64_t nTimeStart = GetTimeMicros();
  1500. CAmount nFees = 0;
  1501. int nInputs = 0;
  1502. unsigned int nSigOps = 0;
  1503. CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
  1504. std::vector<std::pair<uint256, CDiskTxPos> > vPos;
  1505. vPos.reserve(block.vtx.size());
  1506. blockundo.vtxundo.reserve(block.vtx.size() - 1);
  1507. for (unsigned int i = 0; i < block.vtx.size(); i++)
  1508. {
  1509. const CTransaction &tx = block.vtx[i];
  1510. nInputs += tx.vin.size();
  1511. nSigOps += GetLegacySigOpCount(tx);
  1512. if (nSigOps > MAX_BLOCK_SIGOPS)
  1513. return state.DoS(100, error("ConnectBlock(): too many sigops"),
  1514. REJECT_INVALID, "bad-blk-sigops");
  1515. if (!tx.IsCoinBase())
  1516. {
  1517. if (!view.HaveInputs(tx))
  1518. return state.DoS(100, error("ConnectBlock(): inputs missing/spent"),
  1519. REJECT_INVALID, "bad-txns-inputs-missingorspent");
  1520. if (fStrictPayToScriptHash)
  1521. {
  1522. // Add in sigops done by pay-to-script-hash inputs;
  1523. // this is to prevent a "rogue miner" from creating
  1524. // an incredibly-expensive-to-validate block.
  1525. nSigOps += GetP2SHSigOpCount(tx, view);
  1526. if (nSigOps > MAX_BLOCK_SIGOPS)
  1527. return state.DoS(100, error("ConnectBlock(): too many sigops"),
  1528. REJECT_INVALID, "bad-blk-sigops");
  1529. }
  1530. nFees += view.GetValueIn(tx)-tx.GetValueOut();
  1531. std::vector<CScriptCheck> vChecks;
  1532. if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
  1533. return false;
  1534. control.Add(vChecks);
  1535. }
  1536. CTxUndo undoDummy;
  1537. if (i > 0) {
  1538. blockundo.vtxundo.push_back(CTxUndo());
  1539. }
  1540. UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
  1541. vPos.push_back(std::make_pair(tx.GetHash(), pos));
  1542. pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
  1543. }
  1544. int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart;
  1545. 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);
  1546. if (block.vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
  1547. return state.DoS(100,
  1548. error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
  1549. block.vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)),
  1550. REJECT_INVALID, "bad-cb-amount");
  1551. if (!control.Wait())
  1552. return state.DoS(100, false);
  1553. int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart;
  1554. 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);
  1555. if (fJustCheck)
  1556. return true;
  1557. // Write undo information to disk
  1558. if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS))
  1559. {
  1560. if (pindex->GetUndoPos().IsNull()) {
  1561. CDiskBlockPos pos;
  1562. if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
  1563. return error("ConnectBlock(): FindUndoPos failed");
  1564. if (!UndoWriteToDisk(blockundo, pos, pindex->pprev->GetBlockHash()))
  1565. return state.Abort("Failed to write undo data");
  1566. // update nUndoPos in block index
  1567. pindex->nUndoPos = pos.nPos;
  1568. pindex->nStatus |= BLOCK_HAVE_UNDO;
  1569. }
  1570. pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
  1571. setDirtyBlockIndex.insert(pindex);
  1572. }
  1573. if (fTxIndex)
  1574. if (!pblocktree->WriteTxIndex(vPos))
  1575. return state.Abort("Failed to write transaction index");
  1576. // add this block to the view's block chain
  1577. view.SetBestBlock(pindex->GetBlockHash());
  1578. int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2;
  1579. LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
  1580. // Watch for changes to the previous coinbase transaction.
  1581. static uint256 hashPrevBestCoinBase;
  1582. GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase);
  1583. hashPrevBestCoinBase = block.vtx[0].GetHash();
  1584. int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3;
  1585. LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
  1586. return true;
  1587. }
  1588. enum FlushStateMode {
  1589. FLUSH_STATE_NONE,
  1590. FLUSH_STATE_IF_NEEDED,
  1591. FLUSH_STATE_PERIODIC,
  1592. FLUSH_STATE_ALWAYS
  1593. };
  1594. /**
  1595. * Update the on-disk chain state.
  1596. * The caches and indexes are flushed depending on the mode we're called with
  1597. * if they're too large, if it's been a while since the last write,
  1598. * or always and in all cases if we're in prune mode and are deleting files.
  1599. */
  1600. bool static FlushStateToDisk(CValidationState &state, FlushStateMode mode) {
  1601. LOCK2(cs_main, cs_LastBlockFile);
  1602. static int64_t nLastWrite = 0;
  1603. std::set<int> setFilesToPrune;
  1604. bool fFlushForPrune = false;
  1605. try {
  1606. if (fPruneMode && fCheckForPruning) {
  1607. FindFilesToPrune(setFilesToPrune);
  1608. if (!setFilesToPrune.empty()) {
  1609. fFlushForPrune = true;
  1610. if (!fHavePruned) {
  1611. pblocktree->WriteFlag("prunedblockfiles", true);
  1612. fHavePruned = true;
  1613. }
  1614. }
  1615. }
  1616. if ((mode == FLUSH_STATE_ALWAYS) ||
  1617. ((mode == FLUSH_STATE_PERIODIC || mode == FLUSH_STATE_IF_NEEDED) && pcoinsTip->GetCacheSize() > nCoinCacheSize) ||
  1618. (mode == FLUSH_STATE_PERIODIC && GetTimeMicros() > nLastWrite + DATABASE_WRITE_INTERVAL * 1000000) ||
  1619. fFlushForPrune) {
  1620. // Typical CCoins structures on disk are around 100 bytes in size.
  1621. // Pushing a new one to the database can cause it to be written
  1622. // twice (once in the log, and once in the tables). This is already
  1623. // an overestimation, as most will delete an existing entry or
  1624. // overwrite one. Still, use a conservative safety factor of 2.
  1625. if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
  1626. return state.Error("out of disk space");
  1627. // First make sure all block and undo data is flushed to disk.
  1628. FlushBlockFile();
  1629. // Then update all block file information (which may refer to block and undo files).
  1630. {
  1631. std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
  1632. vFiles.reserve(setDirtyFileInfo.size());
  1633. for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
  1634. vFiles.push_back(make_pair(*it, &vinfoBlockFile[*it]));
  1635. setDirtyFileInfo.erase(it++);
  1636. }
  1637. std::vector<const CBlockIndex*> vBlocks;
  1638. vBlocks.reserve(setDirtyBlockIndex.size());
  1639. for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
  1640. vBlocks.push_back(*it);
  1641. setDirtyBlockIndex.erase(it++);
  1642. }
  1643. if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
  1644. return state.Abort("Files to write to block index database");
  1645. }
  1646. }
  1647. // Flush the chainstate (which may refer to block index entries).
  1648. if (!pcoinsTip->Flush())
  1649. return state.Abort("Failed to write to coin database");
  1650. // Finally remove any pruned files
  1651. if (fFlushForPrune) {
  1652. UnlinkPrunedFiles(setFilesToPrune);
  1653. fCheckForPruning = false;
  1654. }
  1655. // Update best block in wallet (so we can detect restored wallets).
  1656. if (mode != FLUSH_STATE_IF_NEEDED) {
  1657. GetMainSignals().SetBestChain(chainActive.GetLocator());
  1658. }
  1659. nLastWrite = GetTimeMicros();
  1660. }
  1661. } catch (const std::runtime_error& e) {
  1662. return state.Abort(std::string("System error while flushing: ") + e.what());
  1663. }
  1664. return true;
  1665. }
  1666. void FlushStateToDisk() {
  1667. CValidationState state;
  1668. FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
  1669. }
  1670. void PruneAndFlush() {
  1671. CValidationState state;
  1672. fCheckForPruning = true;
  1673. FlushStateToDisk(state, FLUSH_STATE_NONE);
  1674. }
  1675. /** Update chainActive and related internal data structures. */
  1676. void static UpdateTip(CBlockIndex *pindexNew) {
  1677. chainActive.SetTip(pindexNew);
  1678. // New best block
  1679. nTimeBestReceived = GetTime();
  1680. mempool.AddTransactionsUpdated(1);
  1681. LogPrintf("%s: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%u\n", __func__,
  1682. chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
  1683. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
  1684. Checkpoints::GuessVerificationProgress(chainActive.Tip()), (unsigned int)pcoinsTip->GetCacheSize());
  1685. cvBlockChange.notify_all();
  1686. // Check the version of the last 100 blocks to see if we need to upgrade:
  1687. static bool fWarned = false;
  1688. if (!IsInitialBlockDownload() && !fWarned)
  1689. {
  1690. int nUpgraded = 0;
  1691. const CBlockIndex* pindex = chainActive.Tip();
  1692. for (int i = 0; i < 100 && pindex != NULL; i++)
  1693. {
  1694. if (pindex->nVersion > CBlock::CURRENT_VERSION)
  1695. ++nUpgraded;
  1696. pindex = pindex->pprev;
  1697. }
  1698. if (nUpgraded > 0)
  1699. LogPrintf("%s: %d of last 100 blocks above version %d\n", __func__, nUpgraded, (int)CBlock::CURRENT_VERSION);
  1700. if (nUpgraded > 100/2)
  1701. {
  1702. // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
  1703. strMiscWarning = _("Warning: This version is obsolete; upgrade required!");
  1704. CAlert::Notify(strMiscWarning, true);
  1705. fWarned = true;
  1706. }
  1707. }
  1708. }
  1709. /** Disconnect chainActive's tip. */
  1710. bool static DisconnectTip(CValidationState &state) {
  1711. CBlockIndex *pindexDelete = chainActive.Tip();
  1712. assert(pindexDelete);
  1713. mempool.check(pcoinsTip);
  1714. // Read block from disk.
  1715. CBlock block;
  1716. if (!ReadBlockFromDisk(block, pindexDelete))
  1717. return state.Abort("Failed to read block");
  1718. // Apply the block atomically to the chain state.
  1719. int64_t nStart = GetTimeMicros();
  1720. {
  1721. CCoinsViewCache view(pcoinsTip);
  1722. if (!DisconnectBlock(block, state, pindexDelete, view))
  1723. return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
  1724. assert(view.Flush());
  1725. }
  1726. LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
  1727. // Write the chain state to disk, if necessary.
  1728. if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
  1729. return false;
  1730. // Resurrect mempool transactions from the disconnected block.
  1731. BOOST_FOREACH(const CTransaction &tx, block.vtx) {
  1732. // ignore validation errors in resurrected transactions
  1733. list<CTransaction> removed;
  1734. CValidationState stateDummy;
  1735. if (tx.IsCoinBase() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
  1736. mempool.remove(tx, removed, true);
  1737. }
  1738. mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
  1739. mempool.check(pcoinsTip);
  1740. // Update chainActive and related variables.
  1741. UpdateTip(pindexDelete->pprev);
  1742. // Let wallets know transactions went from 1-confirmed to
  1743. // 0-confirmed or conflicted:
  1744. BOOST_FOREACH(const CTransaction &tx, block.vtx) {
  1745. SyncWithWallets(tx, NULL);
  1746. }
  1747. return true;
  1748. }
  1749. static int64_t nTimeReadFromDisk = 0;
  1750. static int64_t nTimeConnectTotal = 0;
  1751. static int64_t nTimeFlush = 0;
  1752. static int64_t nTimeChainState = 0;
  1753. static int64_t nTimePostConnect = 0;
  1754. /**
  1755. * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
  1756. * corresponding to pindexNew, to bypass loading it again from disk.
  1757. */
  1758. bool static ConnectTip(CValidationState &state, CBlockIndex *pindexNew, CBlock *pblock) {
  1759. assert(pindexNew->pprev == chainActive.Tip());
  1760. mempool.check(pcoinsTip);
  1761. // Read block from disk.
  1762. int64_t nTime1 = GetTimeMicros();
  1763. CBlock block;
  1764. if (!pblock) {
  1765. if (!ReadBlockFromDisk(block, pindexNew))
  1766. return state.Abort("Failed to read block");
  1767. pblock = &block;
  1768. }
  1769. // Apply the block atomically to the chain state.
  1770. int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
  1771. int64_t nTime3;
  1772. LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
  1773. {
  1774. CCoinsViewCache view(pcoinsTip);
  1775. CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
  1776. bool rv = ConnectBlock(*pblock, state, pindexNew, view);
  1777. GetMainSignals().BlockChecked(*pblock, state);
  1778. if (!rv) {
  1779. if (state.IsInvalid())
  1780. InvalidBlockFound(pindexNew, state);
  1781. return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
  1782. }
  1783. mapBlockSource.erase(inv.hash);
  1784. nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
  1785. LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
  1786. assert(view.Flush());
  1787. }
  1788. int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
  1789. LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
  1790. // Write the chain state to disk, if necessary.
  1791. if (!FlushStateToDisk(state, FLUSH_STATE_IF_NEEDED))
  1792. return false;
  1793. int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
  1794. LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
  1795. // Remove conflicting transactions from the mempool.
  1796. list<CTransaction> txConflicted;
  1797. mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted);
  1798. mempool.check(pcoinsTip);
  1799. // Update chainActive & related variables.
  1800. UpdateTip(pindexNew);
  1801. // Tell wallet about transactions that went from mempool
  1802. // to conflicted:
  1803. BOOST_FOREACH(const CTransaction &tx, txConflicted) {
  1804. SyncWithWallets(tx, NULL);
  1805. }
  1806. // ... and about transactions that got confirmed:
  1807. BOOST_FOREACH(const CTransaction &tx, pblock->vtx) {
  1808. SyncWithWallets(tx, pblock);
  1809. }
  1810. int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
  1811. LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
  1812. LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
  1813. return true;
  1814. }
  1815. /**
  1816. * Return the tip of the chain with the most work in it, that isn't
  1817. * known to be invalid (it's however far from certain to be valid).
  1818. */
  1819. static CBlockIndex* FindMostWorkChain() {
  1820. do {
  1821. CBlockIndex *pindexNew = NULL;
  1822. // Find the best candidate header.
  1823. {
  1824. std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
  1825. if (it == setBlockIndexCandidates.rend())
  1826. return NULL;
  1827. pindexNew = *it;
  1828. }
  1829. // Check whether all blocks on the path between the currently active chain and the candidate are valid.
  1830. // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
  1831. CBlockIndex *pindexTest = pindexNew;
  1832. bool fInvalidAncestor = false;
  1833. while (pindexTest && !chainActive.Contains(pindexTest)) {
  1834. assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
  1835. // Pruned nodes may have entries in setBlockIndexCandidates for
  1836. // which block files have been deleted. Remove those as candidates
  1837. // for the most work chain if we come across them; we can't switch
  1838. // to a chain unless we have all the non-active-chain parent blocks.
  1839. bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
  1840. bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
  1841. if (fFailedChain || fMissingData) {
  1842. // Candidate chain is not usable (either invalid or missing data)
  1843. if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
  1844. pindexBestInvalid = pindexNew;
  1845. CBlockIndex *pindexFailed = pindexNew;
  1846. // Remove the entire chain from the set.
  1847. while (pindexTest != pindexFailed) {
  1848. if (fFailedChain) {
  1849. pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
  1850. } else if (fMissingData) {
  1851. // If we're missing data, then add back to mapBlocksUnlinked,
  1852. // so that if the block arrives in the future we can try adding
  1853. // to setBlockIndexCandidates again.
  1854. mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
  1855. }
  1856. setBlockIndexCandidates.erase(pindexFailed);
  1857. pindexFailed = pindexFailed->pprev;
  1858. }
  1859. setBlockIndexCandidates.erase(pindexTest);
  1860. fInvalidAncestor = true;
  1861. break;
  1862. }
  1863. pindexTest = pindexTest->pprev;
  1864. }
  1865. if (!fInvalidAncestor)
  1866. return pindexNew;
  1867. } while(true);
  1868. }
  1869. /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
  1870. static void PruneBlockIndexCandidates() {
  1871. // Note that we can't delete the current block itself, as we may need to return to it later in case a
  1872. // reorganization to a better block fails.
  1873. std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
  1874. while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
  1875. setBlockIndexCandidates.erase(it++);
  1876. }
  1877. // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
  1878. assert(!setBlockIndexCandidates.empty());
  1879. }
  1880. /**
  1881. * Try to make some progress towards making pindexMostWork the active block.
  1882. * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
  1883. */
  1884. static bool ActivateBestChainStep(CValidationState &state, CBlockIndex *pindexMostWork, CBlock *pblock) {
  1885. AssertLockHeld(cs_main);
  1886. bool fInvalidFound = false;
  1887. const CBlockIndex *pindexOldTip = chainActive.Tip();
  1888. const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
  1889. // Disconnect active blocks which are no longer in the best chain.
  1890. while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
  1891. if (!DisconnectTip(state))
  1892. return false;
  1893. }
  1894. // Build list of new blocks to connect.
  1895. std::vector<CBlockIndex*> vpindexToConnect;
  1896. bool fContinue = true;
  1897. int nHeight = pindexFork ? pindexFork->nHeight : -1;
  1898. while (fContinue && nHeight != pindexMostWork->nHeight) {
  1899. // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
  1900. // a few blocks along the way.
  1901. int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
  1902. vpindexToConnect.clear();
  1903. vpindexToConnect.reserve(nTargetHeight - nHeight);
  1904. CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
  1905. while (pindexIter && pindexIter->nHeight != nHeight) {
  1906. vpindexToConnect.push_back(pindexIter);
  1907. pindexIter = pindexIter->pprev;
  1908. }
  1909. nHeight = nTargetHeight;
  1910. // Connect new blocks.
  1911. BOOST_REVERSE_FOREACH(CBlockIndex *pindexConnect, vpindexToConnect) {
  1912. if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL)) {
  1913. if (state.IsInvalid()) {
  1914. // The block violates a consensus rule.
  1915. if (!state.CorruptionPossible())
  1916. InvalidChainFound(vpindexToConnect.back());
  1917. state = CValidationState();
  1918. fInvalidFound = true;
  1919. fContinue = false;
  1920. break;
  1921. } else {
  1922. // A system error occurred (disk space, database error, ...).
  1923. return false;
  1924. }
  1925. } else {
  1926. PruneBlockIndexCandidates();
  1927. if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
  1928. // We're in a better position than we were. Return temporarily to release the lock.
  1929. fContinue = false;
  1930. break;
  1931. }
  1932. }
  1933. }
  1934. }
  1935. // Callbacks/notifications for a new best chain.
  1936. if (fInvalidFound)
  1937. CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
  1938. else
  1939. CheckForkWarningConditions();
  1940. return true;
  1941. }
  1942. /**
  1943. * Make the best chain active, in multiple steps. The result is either failure
  1944. * or an activated best chain. pblock is either NULL or a pointer to a block
  1945. * that is already loaded (to avoid loading it again from disk).
  1946. */
  1947. bool ActivateBestChain(CValidationState &state, CBlock *pblock) {
  1948. CBlockIndex *pindexNewTip = NULL;
  1949. CBlockIndex *pindexMostWork = NULL;
  1950. do {
  1951. boost::this_thread::interruption_point();
  1952. bool fInitialDownload;
  1953. {
  1954. LOCK(cs_main);
  1955. pindexMostWork = FindMostWorkChain();
  1956. // Whether we have anything to do at all.
  1957. if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
  1958. return true;
  1959. if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL))
  1960. return false;
  1961. pindexNewTip = chainActive.Tip();
  1962. fInitialDownload = IsInitialBlockDownload();
  1963. }
  1964. // When we reach this point, we switched to a new tip (stored in pindexNewTip).
  1965. // Notifications/callbacks that can run without cs_main
  1966. if (!fInitialDownload) {
  1967. uint256 hashNewTip = pindexNewTip->GetBlockHash();
  1968. // Relay inventory, but don't relay old inventory during initial block download.
  1969. int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
  1970. // Don't relay blocks if pruning -- could cause a peer to try to download, resulting
  1971. // in a stalled download if the block file is pruned before the request.
  1972. if (nLocalServices & NODE_NETWORK) {
  1973. LOCK(cs_vNodes);
  1974. BOOST_FOREACH(CNode* pnode, vNodes)
  1975. if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
  1976. pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
  1977. }
  1978. // Notify external listeners about the new tip.
  1979. uiInterface.NotifyBlockTip(hashNewTip);
  1980. }
  1981. } while(pindexMostWork != chainActive.Tip());
  1982. CheckBlockIndex();
  1983. // Write changes periodically to disk, after relay.
  1984. if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
  1985. return false;
  1986. }
  1987. return true;
  1988. }
  1989. bool InvalidateBlock(CValidationState& state, CBlockIndex *pindex) {
  1990. AssertLockHeld(cs_main);
  1991. // Mark the block itself as invalid.
  1992. pindex->nStatus |= BLOCK_FAILED_VALID;
  1993. setDirtyBlockIndex.insert(pindex);
  1994. setBlockIndexCandidates.erase(pindex);
  1995. while (chainActive.Contains(pindex)) {
  1996. CBlockIndex *pindexWalk = chainActive.Tip();
  1997. pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
  1998. setDirtyBlockIndex.insert(pindexWalk);
  1999. setBlockIndexCandidates.erase(pindexWalk);
  2000. // ActivateBestChain considers blocks already in chainActive
  2001. // unconditionally valid already, so force disconnect away from it.
  2002. if (!DisconnectTip(state)) {
  2003. return false;
  2004. }
  2005. }
  2006. // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
  2007. // add it again.
  2008. BlockMap::iterator it = mapBlockIndex.begin();
  2009. while (it != mapBlockIndex.end()) {
  2010. if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
  2011. setBlockIndexCandidates.insert(it->second);
  2012. }
  2013. it++;
  2014. }
  2015. InvalidChainFound(pindex);
  2016. return true;
  2017. }
  2018. bool ReconsiderBlock(CValidationState& state, CBlockIndex *pindex) {
  2019. AssertLockHeld(cs_main);
  2020. int nHeight = pindex->nHeight;
  2021. // Remove the invalidity flag from this block and all its descendants.
  2022. BlockMap::iterator it = mapBlockIndex.begin();
  2023. while (it != mapBlockIndex.end()) {
  2024. if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
  2025. it->second->nStatus &= ~BLOCK_FAILED_MASK;
  2026. setDirtyBlockIndex.insert(it->second);
  2027. if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
  2028. setBlockIndexCandidates.insert(it->second);
  2029. }
  2030. if (it->second == pindexBestInvalid) {
  2031. // Reset invalid block marker if it was pointing to one of those.
  2032. pindexBestInvalid = NULL;
  2033. }
  2034. }
  2035. it++;
  2036. }
  2037. // Remove the invalidity flag from all ancestors too.
  2038. while (pindex != NULL) {
  2039. if (pindex->nStatus & BLOCK_FAILED_MASK) {
  2040. pindex->nStatus &= ~BLOCK_FAILED_MASK;
  2041. setDirtyBlockIndex.insert(pindex);
  2042. }
  2043. pindex = pindex->pprev;
  2044. }
  2045. return true;
  2046. }
  2047. CBlockIndex* AddToBlockIndex(const CBlockHeader& block)
  2048. {
  2049. // Check for duplicate
  2050. uint256 hash = block.GetHash();
  2051. BlockMap::iterator it = mapBlockIndex.find(hash);
  2052. if (it != mapBlockIndex.end())
  2053. return it->second;
  2054. // Construct new block index object
  2055. CBlockIndex* pindexNew = new CBlockIndex(block);
  2056. assert(pindexNew);
  2057. // We assign the sequence id to blocks only when the full data is available,
  2058. // to avoid miners withholding blocks but broadcasting headers, to get a
  2059. // competitive advantage.
  2060. pindexNew->nSequenceId = 0;
  2061. BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  2062. pindexNew->phashBlock = &((*mi).first);
  2063. BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
  2064. if (miPrev != mapBlockIndex.end())
  2065. {
  2066. pindexNew->pprev = (*miPrev).second;
  2067. pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
  2068. pindexNew->BuildSkip();
  2069. }
  2070. pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
  2071. pindexNew->RaiseValidity(BLOCK_VALID_TREE);
  2072. if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
  2073. pindexBestHeader = pindexNew;
  2074. setDirtyBlockIndex.insert(pindexNew);
  2075. return pindexNew;
  2076. }
  2077. /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
  2078. bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos)
  2079. {
  2080. pindexNew->nTx = block.vtx.size();
  2081. pindexNew->nChainTx = 0;
  2082. pindexNew->nFile = pos.nFile;
  2083. pindexNew->nDataPos = pos.nPos;
  2084. pindexNew->nUndoPos = 0;
  2085. pindexNew->nStatus |= BLOCK_HAVE_DATA;
  2086. pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
  2087. setDirtyBlockIndex.insert(pindexNew);
  2088. if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
  2089. // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
  2090. deque<CBlockIndex*> queue;
  2091. queue.push_back(pindexNew);
  2092. // Recursively process any descendant blocks that now may be eligible to be connected.
  2093. while (!queue.empty()) {
  2094. CBlockIndex *pindex = queue.front();
  2095. queue.pop_front();
  2096. pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
  2097. {
  2098. LOCK(cs_nBlockSequenceId);
  2099. pindex->nSequenceId = nBlockSequenceId++;
  2100. }
  2101. if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
  2102. setBlockIndexCandidates.insert(pindex);
  2103. }
  2104. std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
  2105. while (range.first != range.second) {
  2106. std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
  2107. queue.push_back(it->second);
  2108. range.first++;
  2109. mapBlocksUnlinked.erase(it);
  2110. }
  2111. }
  2112. } else {
  2113. if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
  2114. mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
  2115. }
  2116. }
  2117. return true;
  2118. }
  2119. bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
  2120. {
  2121. LOCK(cs_LastBlockFile);
  2122. unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
  2123. if (vinfoBlockFile.size() <= nFile) {
  2124. vinfoBlockFile.resize(nFile + 1);
  2125. }
  2126. if (!fKnown) {
  2127. while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
  2128. LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
  2129. FlushBlockFile(true);
  2130. nFile++;
  2131. if (vinfoBlockFile.size() <= nFile) {
  2132. vinfoBlockFile.resize(nFile + 1);
  2133. }
  2134. }
  2135. pos.nFile = nFile;
  2136. pos.nPos = vinfoBlockFile[nFile].nSize;
  2137. }
  2138. nLastBlockFile = nFile;
  2139. vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
  2140. if (fKnown)
  2141. vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
  2142. else
  2143. vinfoBlockFile[nFile].nSize += nAddSize;
  2144. if (!fKnown) {
  2145. unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
  2146. unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
  2147. if (nNewChunks > nOldChunks) {
  2148. if (fPruneMode)
  2149. fCheckForPruning = true;
  2150. if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
  2151. FILE *file = OpenBlockFile(pos);
  2152. if (file) {
  2153. LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
  2154. AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
  2155. fclose(file);
  2156. }
  2157. }
  2158. else
  2159. return state.Error("out of disk space");
  2160. }
  2161. }
  2162. setDirtyFileInfo.insert(nFile);
  2163. return true;
  2164. }
  2165. bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
  2166. {
  2167. pos.nFile = nFile;
  2168. LOCK(cs_LastBlockFile);
  2169. unsigned int nNewSize;
  2170. pos.nPos = vinfoBlockFile[nFile].nUndoSize;
  2171. nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
  2172. setDirtyFileInfo.insert(nFile);
  2173. unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
  2174. unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
  2175. if (nNewChunks > nOldChunks) {
  2176. if (fPruneMode)
  2177. fCheckForPruning = true;
  2178. if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
  2179. FILE *file = OpenUndoFile(pos);
  2180. if (file) {
  2181. LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
  2182. AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
  2183. fclose(file);
  2184. }
  2185. }
  2186. else
  2187. return state.Error("out of disk space");
  2188. }
  2189. return true;
  2190. }
  2191. bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
  2192. {
  2193. // Check proof of work matches claimed amount
  2194. if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
  2195. return state.DoS(50, error("CheckBlockHeader(): proof of work failed"),
  2196. REJECT_INVALID, "high-hash");
  2197. // Check timestamp
  2198. if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
  2199. return state.Invalid(error("CheckBlockHeader(): block timestamp too far in the future"),
  2200. REJECT_INVALID, "time-too-new");
  2201. return true;
  2202. }
  2203. bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
  2204. {
  2205. // These are checks that are independent of context.
  2206. // Check that the header is valid (particularly PoW). This is mostly
  2207. // redundant with the call in AcceptBlockHeader.
  2208. if (!CheckBlockHeader(block, state, fCheckPOW))
  2209. return false;
  2210. // Check the merkle root.
  2211. if (fCheckMerkleRoot) {
  2212. bool mutated;
  2213. uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
  2214. if (block.hashMerkleRoot != hashMerkleRoot2)
  2215. return state.DoS(100, error("CheckBlock(): hashMerkleRoot mismatch"),
  2216. REJECT_INVALID, "bad-txnmrklroot", true);
  2217. // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
  2218. // of transactions in a block without affecting the merkle root of a block,
  2219. // while still invalidating it.
  2220. if (mutated)
  2221. return state.DoS(100, error("CheckBlock(): duplicate transaction"),
  2222. REJECT_INVALID, "bad-txns-duplicate", true);
  2223. }
  2224. // All potential-corruption validation must be done before we do any
  2225. // transaction validation, as otherwise we may mark the header as invalid
  2226. // because we receive the wrong transactions for it.
  2227. // Size limits
  2228. if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
  2229. return state.DoS(100, error("CheckBlock(): size limits failed"),
  2230. REJECT_INVALID, "bad-blk-length");
  2231. // First transaction must be coinbase, the rest must not be
  2232. if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
  2233. return state.DoS(100, error("CheckBlock(): first tx is not coinbase"),
  2234. REJECT_INVALID, "bad-cb-missing");
  2235. for (unsigned int i = 1; i < block.vtx.size(); i++)
  2236. if (block.vtx[i].IsCoinBase())
  2237. return state.DoS(100, error("CheckBlock(): more than one coinbase"),
  2238. REJECT_INVALID, "bad-cb-multiple");
  2239. // Check transactions
  2240. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  2241. if (!CheckTransaction(tx, state))
  2242. return error("CheckBlock(): CheckTransaction failed");
  2243. unsigned int nSigOps = 0;
  2244. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  2245. {
  2246. nSigOps += GetLegacySigOpCount(tx);
  2247. }
  2248. if (nSigOps > MAX_BLOCK_SIGOPS)
  2249. return state.DoS(100, error("CheckBlock(): out-of-bounds SigOpCount"),
  2250. REJECT_INVALID, "bad-blk-sigops", true);
  2251. return true;
  2252. }
  2253. bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex * const pindexPrev)
  2254. {
  2255. const Consensus::Params& consensusParams = Params().GetConsensus();
  2256. uint256 hash = block.GetHash();
  2257. if (hash == consensusParams.hashGenesisBlock)
  2258. return true;
  2259. assert(pindexPrev);
  2260. int nHeight = pindexPrev->nHeight+1;
  2261. // Check proof of work
  2262. if (block.nBits != GetNextWorkRequired(pindexPrev, &block, Params().GetConsensus()))
  2263. return state.DoS(100, error("%s: incorrect proof of work", __func__),
  2264. REJECT_INVALID, "bad-diffbits");
  2265. // Check timestamp against prev
  2266. if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
  2267. return state.Invalid(error("%s: block's timestamp is too early", __func__),
  2268. REJECT_INVALID, "time-too-old");
  2269. // Check that the block chain matches the known block chain up to a checkpoint
  2270. if (!Checkpoints::CheckBlock(nHeight, hash))
  2271. return state.DoS(100, error("%s: rejected by checkpoint lock-in at %d", __func__, nHeight),
  2272. REJECT_CHECKPOINT, "checkpoint mismatch");
  2273. // Don't accept any forks from the main chain prior to last checkpoint
  2274. CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint();
  2275. if (pcheckpoint && nHeight < pcheckpoint->nHeight)
  2276. return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight));
  2277. // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
  2278. if (block.nVersion < 2 && IsSuperMajority(2, pindexPrev, Params().RejectBlockOutdatedMajority()))
  2279. {
  2280. return state.Invalid(error("%s: rejected nVersion=1 block", __func__),
  2281. REJECT_OBSOLETE, "bad-version");
  2282. }
  2283. // Reject block.nVersion=2 blocks when 95% (75% on testnet) of the network has upgraded:
  2284. if (block.nVersion < 3 && IsSuperMajority(3, pindexPrev, Params().RejectBlockOutdatedMajority()))
  2285. {
  2286. return state.Invalid(error("%s : rejected nVersion=2 block", __func__),
  2287. REJECT_OBSOLETE, "bad-version");
  2288. }
  2289. return true;
  2290. }
  2291. bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex * const pindexPrev)
  2292. {
  2293. const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
  2294. // Check that all transactions are finalized
  2295. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  2296. if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) {
  2297. return state.DoS(10, error("%s: contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
  2298. }
  2299. // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
  2300. // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
  2301. if (block.nVersion >= 2 && IsSuperMajority(2, pindexPrev, Params().EnforceBlockUpgradeMajority()))
  2302. {
  2303. CScript expect = CScript() << nHeight;
  2304. if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
  2305. !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) {
  2306. return state.DoS(100, error("%s: block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height");
  2307. }
  2308. }
  2309. return true;
  2310. }
  2311. bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex)
  2312. {
  2313. const CChainParams& chainparams = Params();
  2314. AssertLockHeld(cs_main);
  2315. // Check for duplicate
  2316. uint256 hash = block.GetHash();
  2317. BlockMap::iterator miSelf = mapBlockIndex.find(hash);
  2318. CBlockIndex *pindex = NULL;
  2319. if (miSelf != mapBlockIndex.end()) {
  2320. // Block header is already known.
  2321. pindex = miSelf->second;
  2322. if (ppindex)
  2323. *ppindex = pindex;
  2324. if (pindex->nStatus & BLOCK_FAILED_MASK)
  2325. return state.Invalid(error("%s: block is marked invalid", __func__), 0, "duplicate");
  2326. return true;
  2327. }
  2328. if (!CheckBlockHeader(block, state))
  2329. return false;
  2330. // Get prev block index
  2331. CBlockIndex* pindexPrev = NULL;
  2332. if (hash != chainparams.GetConsensus().hashGenesisBlock) {
  2333. BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
  2334. if (mi == mapBlockIndex.end())
  2335. return state.DoS(10, error("%s: prev block not found", __func__), 0, "bad-prevblk");
  2336. pindexPrev = (*mi).second;
  2337. if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
  2338. return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
  2339. }
  2340. if (!ContextualCheckBlockHeader(block, state, pindexPrev))
  2341. return false;
  2342. if (pindex == NULL)
  2343. pindex = AddToBlockIndex(block);
  2344. if (ppindex)
  2345. *ppindex = pindex;
  2346. return true;
  2347. }
  2348. bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp)
  2349. {
  2350. AssertLockHeld(cs_main);
  2351. CBlockIndex *&pindex = *ppindex;
  2352. if (!AcceptBlockHeader(block, state, &pindex))
  2353. return false;
  2354. // If we're pruning, ensure that we don't allow a peer to dump a copy
  2355. // of old blocks. But we might need blocks that are not on the main chain
  2356. // to handle a reorg, even if we've processed once.
  2357. if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) {
  2358. // TODO: deal better with duplicate blocks.
  2359. // return state.DoS(20, error("AcceptBlock(): already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()), REJECT_DUPLICATE, "duplicate");
  2360. return true;
  2361. }
  2362. if ((!CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
  2363. if (state.IsInvalid() && !state.CorruptionPossible()) {
  2364. pindex->nStatus |= BLOCK_FAILED_VALID;
  2365. setDirtyBlockIndex.insert(pindex);
  2366. }
  2367. return false;
  2368. }
  2369. int nHeight = pindex->nHeight;
  2370. // Write block to history file
  2371. try {
  2372. unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
  2373. CDiskBlockPos blockPos;
  2374. if (dbp != NULL)
  2375. blockPos = *dbp;
  2376. if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != NULL))
  2377. return error("AcceptBlock(): FindBlockPos failed");
  2378. if (dbp == NULL)
  2379. if (!WriteBlockToDisk(block, blockPos))
  2380. return state.Abort("Failed to write block");
  2381. if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
  2382. return error("AcceptBlock(): ReceivedBlockTransactions failed");
  2383. } catch (const std::runtime_error& e) {
  2384. return state.Abort(std::string("System error: ") + e.what());
  2385. }
  2386. if (fCheckForPruning)
  2387. FlushStateToDisk(state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
  2388. return true;
  2389. }
  2390. static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired)
  2391. {
  2392. unsigned int nToCheck = Params().ToCheckBlockUpgradeMajority();
  2393. unsigned int nFound = 0;
  2394. for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
  2395. {
  2396. if (pstart->nVersion >= minVersion)
  2397. ++nFound;
  2398. pstart = pstart->pprev;
  2399. }
  2400. return (nFound >= nRequired);
  2401. }
  2402. bool ProcessNewBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
  2403. {
  2404. // Preliminary checks
  2405. bool checked = CheckBlock(*pblock, state);
  2406. {
  2407. LOCK(cs_main);
  2408. MarkBlockAsReceived(pblock->GetHash());
  2409. if (!checked) {
  2410. return error("%s: CheckBlock FAILED", __func__);
  2411. }
  2412. // Store to disk
  2413. CBlockIndex *pindex = NULL;
  2414. bool ret = AcceptBlock(*pblock, state, &pindex, dbp);
  2415. if (pindex && pfrom) {
  2416. mapBlockSource[pindex->GetBlockHash()] = pfrom->GetId();
  2417. }
  2418. CheckBlockIndex();
  2419. if (!ret)
  2420. return error("%s: AcceptBlock FAILED", __func__);
  2421. }
  2422. if (!ActivateBestChain(state, pblock))
  2423. return error("%s: ActivateBestChain failed", __func__);
  2424. return true;
  2425. }
  2426. bool TestBlockValidity(CValidationState &state, const CBlock& block, CBlockIndex * const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
  2427. {
  2428. AssertLockHeld(cs_main);
  2429. assert(pindexPrev == chainActive.Tip());
  2430. CCoinsViewCache viewNew(pcoinsTip);
  2431. CBlockIndex indexDummy(block);
  2432. indexDummy.pprev = pindexPrev;
  2433. indexDummy.nHeight = pindexPrev->nHeight + 1;
  2434. // NOTE: CheckBlockHeader is called by CheckBlock
  2435. if (!ContextualCheckBlockHeader(block, state, pindexPrev))
  2436. return false;
  2437. if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
  2438. return false;
  2439. if (!ContextualCheckBlock(block, state, pindexPrev))
  2440. return false;
  2441. if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
  2442. return false;
  2443. assert(state.IsValid());
  2444. return true;
  2445. }
  2446. bool AbortNode(const std::string &strMessage, const std::string &userMessage) {
  2447. strMiscWarning = strMessage;
  2448. LogPrintf("*** %s\n", strMessage);
  2449. uiInterface.ThreadSafeMessageBox(
  2450. userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
  2451. "", CClientUIInterface::MSG_ERROR);
  2452. StartShutdown();
  2453. return false;
  2454. }
  2455. /**
  2456. * BLOCK PRUNING CODE
  2457. */
  2458. /* Calculate the amount of disk space the block & undo files currently use */
  2459. uint64_t CalculateCurrentUsage()
  2460. {
  2461. uint64_t retval = 0;
  2462. BOOST_FOREACH(const CBlockFileInfo &file, vinfoBlockFile) {
  2463. retval += file.nSize + file.nUndoSize;
  2464. }
  2465. return retval;
  2466. }
  2467. /* Prune a block file (modify associated database entries)*/
  2468. void PruneOneBlockFile(const int fileNumber)
  2469. {
  2470. for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); ++it) {
  2471. CBlockIndex* pindex = it->second;
  2472. if (pindex->nFile == fileNumber) {
  2473. pindex->nStatus &= ~BLOCK_HAVE_DATA;
  2474. pindex->nStatus &= ~BLOCK_HAVE_UNDO;
  2475. pindex->nFile = 0;
  2476. pindex->nDataPos = 0;
  2477. pindex->nUndoPos = 0;
  2478. setDirtyBlockIndex.insert(pindex);
  2479. // Prune from mapBlocksUnlinked -- any block we prune would have
  2480. // to be downloaded again in order to consider its chain, at which
  2481. // point it would be considered as a candidate for
  2482. // mapBlocksUnlinked or setBlockIndexCandidates.
  2483. std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
  2484. while (range.first != range.second) {
  2485. std::multimap<CBlockIndex *, CBlockIndex *>::iterator it = range.first;
  2486. range.first++;
  2487. if (it->second == pindex) {
  2488. mapBlocksUnlinked.erase(it);
  2489. }
  2490. }
  2491. }
  2492. }
  2493. vinfoBlockFile[fileNumber].SetNull();
  2494. setDirtyFileInfo.insert(fileNumber);
  2495. }
  2496. void UnlinkPrunedFiles(std::set<int>& setFilesToPrune)
  2497. {
  2498. for (set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
  2499. CDiskBlockPos pos(*it, 0);
  2500. boost::filesystem::remove(GetBlockPosFilename(pos, "blk"));
  2501. boost::filesystem::remove(GetBlockPosFilename(pos, "rev"));
  2502. LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
  2503. }
  2504. }
  2505. /* Calculate the block/rev files that should be deleted to remain under target*/
  2506. void FindFilesToPrune(std::set<int>& setFilesToPrune)
  2507. {
  2508. LOCK2(cs_main, cs_LastBlockFile);
  2509. if (chainActive.Tip() == NULL || nPruneTarget == 0) {
  2510. return;
  2511. }
  2512. if (chainActive.Tip()->nHeight <= Params().PruneAfterHeight()) {
  2513. return;
  2514. }
  2515. unsigned int nLastBlockWeMustKeep = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
  2516. uint64_t nCurrentUsage = CalculateCurrentUsage();
  2517. // We don't check to prune until after we've allocated new space for files
  2518. // So we should leave a buffer under our target to account for another allocation
  2519. // before the next pruning.
  2520. uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
  2521. uint64_t nBytesToPrune;
  2522. int count=0;
  2523. if (nCurrentUsage + nBuffer >= nPruneTarget) {
  2524. for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
  2525. nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
  2526. if (vinfoBlockFile[fileNumber].nSize == 0)
  2527. continue;
  2528. if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
  2529. break;
  2530. // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip
  2531. if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeMustKeep)
  2532. break;
  2533. PruneOneBlockFile(fileNumber);
  2534. // Queue up the files for removal
  2535. setFilesToPrune.insert(fileNumber);
  2536. nCurrentUsage -= nBytesToPrune;
  2537. count++;
  2538. }
  2539. }
  2540. LogPrint("prune", "Prune: target=%dMiB actual=%dMiB diff=%dMiB min_must_keep=%d removed %d blk/rev pairs\n",
  2541. nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
  2542. ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
  2543. nLastBlockWeMustKeep, count);
  2544. }
  2545. bool CheckDiskSpace(uint64_t nAdditionalBytes)
  2546. {
  2547. uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
  2548. // Check for nMinDiskSpace bytes (currently 50MB)
  2549. if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
  2550. return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
  2551. return true;
  2552. }
  2553. FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
  2554. {
  2555. if (pos.IsNull())
  2556. return NULL;
  2557. boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
  2558. boost::filesystem::create_directories(path.parent_path());
  2559. FILE* file = fopen(path.string().c_str(), "rb+");
  2560. if (!file && !fReadOnly)
  2561. file = fopen(path.string().c_str(), "wb+");
  2562. if (!file) {
  2563. LogPrintf("Unable to open file %s\n", path.string());
  2564. return NULL;
  2565. }
  2566. if (pos.nPos) {
  2567. if (fseek(file, pos.nPos, SEEK_SET)) {
  2568. LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
  2569. fclose(file);
  2570. return NULL;
  2571. }
  2572. }
  2573. return file;
  2574. }
  2575. FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
  2576. return OpenDiskFile(pos, "blk", fReadOnly);
  2577. }
  2578. FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
  2579. return OpenDiskFile(pos, "rev", fReadOnly);
  2580. }
  2581. boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
  2582. {
  2583. return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
  2584. }
  2585. CBlockIndex * InsertBlockIndex(uint256 hash)
  2586. {
  2587. if (hash.IsNull())
  2588. return NULL;
  2589. // Return existing
  2590. BlockMap::iterator mi = mapBlockIndex.find(hash);
  2591. if (mi != mapBlockIndex.end())
  2592. return (*mi).second;
  2593. // Create new
  2594. CBlockIndex* pindexNew = new CBlockIndex();
  2595. if (!pindexNew)
  2596. throw runtime_error("LoadBlockIndex(): new CBlockIndex failed");
  2597. mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  2598. pindexNew->phashBlock = &((*mi).first);
  2599. return pindexNew;
  2600. }
  2601. bool static LoadBlockIndexDB()
  2602. {
  2603. if (!pblocktree->LoadBlockIndexGuts())
  2604. return false;
  2605. boost::this_thread::interruption_point();
  2606. // Calculate nChainWork
  2607. vector<pair<int, CBlockIndex*> > vSortedByHeight;
  2608. vSortedByHeight.reserve(mapBlockIndex.size());
  2609. BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
  2610. {
  2611. CBlockIndex* pindex = item.second;
  2612. vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
  2613. }
  2614. sort(vSortedByHeight.begin(), vSortedByHeight.end());
  2615. BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
  2616. {
  2617. CBlockIndex* pindex = item.second;
  2618. pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
  2619. // We can link the chain of blocks for which we've received transactions at some point.
  2620. // Pruned nodes may have deleted the block.
  2621. if (pindex->nTx > 0) {
  2622. if (pindex->pprev) {
  2623. if (pindex->pprev->nChainTx) {
  2624. pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
  2625. } else {
  2626. pindex->nChainTx = 0;
  2627. mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
  2628. }
  2629. } else {
  2630. pindex->nChainTx = pindex->nTx;
  2631. }
  2632. }
  2633. if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
  2634. setBlockIndexCandidates.insert(pindex);
  2635. if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
  2636. pindexBestInvalid = pindex;
  2637. if (pindex->pprev)
  2638. pindex->BuildSkip();
  2639. if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
  2640. pindexBestHeader = pindex;
  2641. }
  2642. // Load block file info
  2643. pblocktree->ReadLastBlockFile(nLastBlockFile);
  2644. vinfoBlockFile.resize(nLastBlockFile + 1);
  2645. LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
  2646. for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
  2647. pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
  2648. }
  2649. LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
  2650. for (int nFile = nLastBlockFile + 1; true; nFile++) {
  2651. CBlockFileInfo info;
  2652. if (pblocktree->ReadBlockFileInfo(nFile, info)) {
  2653. vinfoBlockFile.push_back(info);
  2654. } else {
  2655. break;
  2656. }
  2657. }
  2658. // Check presence of blk files
  2659. LogPrintf("Checking all blk files are present...\n");
  2660. set<int> setBlkDataFiles;
  2661. BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
  2662. {
  2663. CBlockIndex* pindex = item.second;
  2664. if (pindex->nStatus & BLOCK_HAVE_DATA) {
  2665. setBlkDataFiles.insert(pindex->nFile);
  2666. }
  2667. }
  2668. for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
  2669. {
  2670. CDiskBlockPos pos(*it, 0);
  2671. if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
  2672. return false;
  2673. }
  2674. }
  2675. // Check whether we have ever pruned block & undo files
  2676. pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
  2677. if (fHavePruned)
  2678. LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
  2679. // Check whether we need to continue reindexing
  2680. bool fReindexing = false;
  2681. pblocktree->ReadReindexing(fReindexing);
  2682. fReindex |= fReindexing;
  2683. // Check whether we have a transaction index
  2684. pblocktree->ReadFlag("txindex", fTxIndex);
  2685. LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
  2686. // Load pointer to end of best chain
  2687. BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
  2688. if (it == mapBlockIndex.end())
  2689. return true;
  2690. chainActive.SetTip(it->second);
  2691. PruneBlockIndexCandidates();
  2692. LogPrintf("%s: hashBestChain=%s height=%d date=%s progress=%f\n", __func__,
  2693. chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
  2694. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
  2695. Checkpoints::GuessVerificationProgress(chainActive.Tip()));
  2696. return true;
  2697. }
  2698. CVerifyDB::CVerifyDB()
  2699. {
  2700. uiInterface.ShowProgress(_("Verifying blocks..."), 0);
  2701. }
  2702. CVerifyDB::~CVerifyDB()
  2703. {
  2704. uiInterface.ShowProgress("", 100);
  2705. }
  2706. bool CVerifyDB::VerifyDB(CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
  2707. {
  2708. LOCK(cs_main);
  2709. if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
  2710. return true;
  2711. // Verify blocks in the best chain
  2712. if (nCheckDepth <= 0)
  2713. nCheckDepth = 1000000000; // suffices until the year 19000
  2714. if (nCheckDepth > chainActive.Height())
  2715. nCheckDepth = chainActive.Height();
  2716. nCheckLevel = std::max(0, std::min(4, nCheckLevel));
  2717. LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
  2718. CCoinsViewCache coins(coinsview);
  2719. CBlockIndex* pindexState = chainActive.Tip();
  2720. CBlockIndex* pindexFailure = NULL;
  2721. int nGoodTransactions = 0;
  2722. CValidationState state;
  2723. for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
  2724. {
  2725. boost::this_thread::interruption_point();
  2726. uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
  2727. if (pindex->nHeight < chainActive.Height()-nCheckDepth)
  2728. break;
  2729. CBlock block;
  2730. // check level 0: read from disk
  2731. if (!ReadBlockFromDisk(block, pindex))
  2732. return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  2733. // check level 1: verify block validity
  2734. if (nCheckLevel >= 1 && !CheckBlock(block, state))
  2735. return error("VerifyDB(): *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  2736. // check level 2: verify undo validity
  2737. if (nCheckLevel >= 2 && pindex) {
  2738. CBlockUndo undo;
  2739. CDiskBlockPos pos = pindex->GetUndoPos();
  2740. if (!pos.IsNull()) {
  2741. if (!UndoReadFromDisk(undo, pos, pindex->pprev->GetBlockHash()))
  2742. return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  2743. }
  2744. }
  2745. // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
  2746. if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= nCoinCacheSize) {
  2747. bool fClean = true;
  2748. if (!DisconnectBlock(block, state, pindex, coins, &fClean))
  2749. return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  2750. pindexState = pindex->pprev;
  2751. if (!fClean) {
  2752. nGoodTransactions = 0;
  2753. pindexFailure = pindex;
  2754. } else
  2755. nGoodTransactions += block.vtx.size();
  2756. }
  2757. if (ShutdownRequested())
  2758. return true;
  2759. }
  2760. if (pindexFailure)
  2761. return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
  2762. // check level 4: try reconnecting blocks
  2763. if (nCheckLevel >= 4) {
  2764. CBlockIndex *pindex = pindexState;
  2765. while (pindex != chainActive.Tip()) {
  2766. boost::this_thread::interruption_point();
  2767. uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
  2768. pindex = chainActive.Next(pindex);
  2769. CBlock block;
  2770. if (!ReadBlockFromDisk(block, pindex))
  2771. return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  2772. if (!ConnectBlock(block, state, pindex, coins))
  2773. return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  2774. }
  2775. }
  2776. LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
  2777. return true;
  2778. }
  2779. void UnloadBlockIndex()
  2780. {
  2781. LOCK(cs_main);
  2782. setBlockIndexCandidates.clear();
  2783. chainActive.SetTip(NULL);
  2784. pindexBestInvalid = NULL;
  2785. pindexBestHeader = NULL;
  2786. mempool.clear();
  2787. mapOrphanTransactions.clear();
  2788. mapOrphanTransactionsByPrev.clear();
  2789. nSyncStarted = 0;
  2790. mapBlocksUnlinked.clear();
  2791. vinfoBlockFile.clear();
  2792. nLastBlockFile = 0;
  2793. nBlockSequenceId = 1;
  2794. mapBlockSource.clear();
  2795. mapBlocksInFlight.clear();
  2796. nQueuedValidatedHeaders = 0;
  2797. nPreferredDownload = 0;
  2798. setDirtyBlockIndex.clear();
  2799. setDirtyFileInfo.clear();
  2800. mapNodeState.clear();
  2801. BOOST_FOREACH(BlockMap::value_type& entry, mapBlockIndex) {
  2802. delete entry.second;
  2803. }
  2804. mapBlockIndex.clear();
  2805. fHavePruned = false;
  2806. }
  2807. bool LoadBlockIndex()
  2808. {
  2809. // Load block index from databases
  2810. if (!fReindex && !LoadBlockIndexDB())
  2811. return false;
  2812. return true;
  2813. }
  2814. bool InitBlockIndex() {
  2815. LOCK(cs_main);
  2816. // Check whether we're already initialized
  2817. if (chainActive.Genesis() != NULL)
  2818. return true;
  2819. // Use the provided setting for -txindex in the new database
  2820. fTxIndex = GetBoolArg("-txindex", false);
  2821. pblocktree->WriteFlag("txindex", fTxIndex);
  2822. LogPrintf("Initializing databases...\n");
  2823. // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
  2824. if (!fReindex) {
  2825. try {
  2826. CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
  2827. // Start new block file
  2828. unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
  2829. CDiskBlockPos blockPos;
  2830. CValidationState state;
  2831. if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.GetBlockTime()))
  2832. return error("LoadBlockIndex(): FindBlockPos failed");
  2833. if (!WriteBlockToDisk(block, blockPos))
  2834. return error("LoadBlockIndex(): writing genesis block to disk failed");
  2835. CBlockIndex *pindex = AddToBlockIndex(block);
  2836. if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
  2837. return error("LoadBlockIndex(): genesis block not accepted");
  2838. if (!ActivateBestChain(state, &block))
  2839. return error("LoadBlockIndex(): genesis block cannot be activated");
  2840. // Force a chainstate write so that when we VerifyDB in a moment, it doesn't check stale data
  2841. return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
  2842. } catch (const std::runtime_error& e) {
  2843. return error("LoadBlockIndex(): failed to initialize block database: %s", e.what());
  2844. }
  2845. }
  2846. return true;
  2847. }
  2848. bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
  2849. {
  2850. const CChainParams& chainparams = Params();
  2851. // Map of disk positions for blocks with unknown parent (only used for reindex)
  2852. static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
  2853. int64_t nStart = GetTimeMillis();
  2854. int nLoaded = 0;
  2855. try {
  2856. // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
  2857. CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
  2858. uint64_t nRewind = blkdat.GetPos();
  2859. while (!blkdat.eof()) {
  2860. boost::this_thread::interruption_point();
  2861. blkdat.SetPos(nRewind);
  2862. nRewind++; // start one byte further next time, in case of failure
  2863. blkdat.SetLimit(); // remove former limit
  2864. unsigned int nSize = 0;
  2865. try {
  2866. // locate a header
  2867. unsigned char buf[MESSAGE_START_SIZE];
  2868. blkdat.FindByte(Params().MessageStart()[0]);
  2869. nRewind = blkdat.GetPos()+1;
  2870. blkdat >> FLATDATA(buf);
  2871. if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
  2872. continue;
  2873. // read size
  2874. blkdat >> nSize;
  2875. if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
  2876. continue;
  2877. } catch (const std::exception&) {
  2878. // no valid block header found; don't complain
  2879. break;
  2880. }
  2881. try {
  2882. // read block
  2883. uint64_t nBlockPos = blkdat.GetPos();
  2884. if (dbp)
  2885. dbp->nPos = nBlockPos;
  2886. blkdat.SetLimit(nBlockPos + nSize);
  2887. blkdat.SetPos(nBlockPos);
  2888. CBlock block;
  2889. blkdat >> block;
  2890. nRewind = blkdat.GetPos();
  2891. // detect out of order blocks, and store them for later
  2892. uint256 hash = block.GetHash();
  2893. if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
  2894. LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
  2895. block.hashPrevBlock.ToString());
  2896. if (dbp)
  2897. mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
  2898. continue;
  2899. }
  2900. // process in case the block isn't known yet
  2901. if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
  2902. CValidationState state;
  2903. if (ProcessNewBlock(state, NULL, &block, dbp))
  2904. nLoaded++;
  2905. if (state.IsError())
  2906. break;
  2907. } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
  2908. LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
  2909. }
  2910. // Recursively process earlier encountered successors of this block
  2911. deque<uint256> queue;
  2912. queue.push_back(hash);
  2913. while (!queue.empty()) {
  2914. uint256 head = queue.front();
  2915. queue.pop_front();
  2916. std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
  2917. while (range.first != range.second) {
  2918. std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
  2919. if (ReadBlockFromDisk(block, it->second))
  2920. {
  2921. LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
  2922. head.ToString());
  2923. CValidationState dummy;
  2924. if (ProcessNewBlock(dummy, NULL, &block, &it->second))
  2925. {
  2926. nLoaded++;
  2927. queue.push_back(block.GetHash());
  2928. }
  2929. }
  2930. range.first++;
  2931. mapBlocksUnknownParent.erase(it);
  2932. }
  2933. }
  2934. } catch (const std::exception& e) {
  2935. LogPrintf("%s: Deserialize or I/O error - %s", __func__, e.what());
  2936. }
  2937. }
  2938. } catch (const std::runtime_error& e) {
  2939. AbortNode(std::string("System error: ") + e.what());
  2940. }
  2941. if (nLoaded > 0)
  2942. LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
  2943. return nLoaded > 0;
  2944. }
  2945. void static CheckBlockIndex()
  2946. {
  2947. const Consensus::Params& consensusParams = Params().GetConsensus();
  2948. if (!fCheckBlockIndex) {
  2949. return;
  2950. }
  2951. LOCK(cs_main);
  2952. // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
  2953. // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
  2954. // iterating the block tree require that chainActive has been initialized.)
  2955. if (chainActive.Height() < 0) {
  2956. assert(mapBlockIndex.size() <= 1);
  2957. return;
  2958. }
  2959. // Build forward-pointing map of the entire block tree.
  2960. std::multimap<CBlockIndex*,CBlockIndex*> forward;
  2961. for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
  2962. forward.insert(std::make_pair(it->second->pprev, it->second));
  2963. }
  2964. assert(forward.size() == mapBlockIndex.size());
  2965. std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
  2966. CBlockIndex *pindex = rangeGenesis.first->second;
  2967. rangeGenesis.first++;
  2968. assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
  2969. // Iterate over the entire block tree, using depth-first search.
  2970. // Along the way, remember whether there are blocks on the path from genesis
  2971. // block being explored which are the first to have certain properties.
  2972. size_t nNodes = 0;
  2973. int nHeight = 0;
  2974. CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
  2975. CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
  2976. CBlockIndex* pindexFirstNeverProcessed = NULL; // Oldest ancestor of pindex for which nTx == 0.
  2977. CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
  2978. CBlockIndex* pindexFirstNotTransactionsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
  2979. CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
  2980. CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
  2981. while (pindex != NULL) {
  2982. nNodes++;
  2983. if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
  2984. if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
  2985. if (pindexFirstNeverProcessed == NULL && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
  2986. if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
  2987. if (pindex->pprev != NULL && pindexFirstNotTransactionsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
  2988. if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
  2989. if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
  2990. // Begin: actual consistency checks.
  2991. if (pindex->pprev == NULL) {
  2992. // Genesis block checks.
  2993. assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
  2994. assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
  2995. }
  2996. if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
  2997. // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
  2998. // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
  2999. if (!fHavePruned) {
  3000. // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
  3001. assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
  3002. assert(pindexFirstMissing == pindexFirstNeverProcessed);
  3003. } else {
  3004. // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
  3005. if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
  3006. }
  3007. if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
  3008. assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
  3009. // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
  3010. assert((pindexFirstNeverProcessed != NULL) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
  3011. assert((pindexFirstNotTransactionsValid != NULL) == (pindex->nChainTx == 0));
  3012. assert(pindex->nHeight == nHeight); // nHeight must be consistent.
  3013. 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.
  3014. assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
  3015. assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
  3016. if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
  3017. if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
  3018. if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
  3019. if (pindexFirstInvalid == NULL) {
  3020. // Checks for not-invalid blocks.
  3021. assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
  3022. }
  3023. if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == NULL) {
  3024. if (pindexFirstInvalid == NULL) {
  3025. // If this block sorts at least as good as the current tip and
  3026. // is valid and we have all data for its parents, it must be in
  3027. // setBlockIndexCandidates. chainActive.Tip() must also be there
  3028. // even if some data has been pruned.
  3029. if (pindexFirstMissing == NULL || pindex == chainActive.Tip()) {
  3030. assert(setBlockIndexCandidates.count(pindex));
  3031. }
  3032. // If some parent is missing, then it could be that this block was in
  3033. // setBlockIndexCandidates but had to be removed because of the missing data.
  3034. // In this case it must be in mapBlocksUnlinked -- see test below.
  3035. }
  3036. } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
  3037. assert(setBlockIndexCandidates.count(pindex) == 0);
  3038. }
  3039. // Check whether this block is in mapBlocksUnlinked.
  3040. std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
  3041. bool foundInUnlinked = false;
  3042. while (rangeUnlinked.first != rangeUnlinked.second) {
  3043. assert(rangeUnlinked.first->first == pindex->pprev);
  3044. if (rangeUnlinked.first->second == pindex) {
  3045. foundInUnlinked = true;
  3046. break;
  3047. }
  3048. rangeUnlinked.first++;
  3049. }
  3050. if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != NULL && pindexFirstInvalid == NULL) {
  3051. // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
  3052. assert(foundInUnlinked);
  3053. }
  3054. if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
  3055. if (pindexFirstMissing == NULL) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
  3056. if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == NULL && pindexFirstMissing != NULL) {
  3057. // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
  3058. assert(fHavePruned); // We must have pruned.
  3059. // This block may have entered mapBlocksUnlinked if:
  3060. // - it has a descendant that at some point had more work than the
  3061. // tip, and
  3062. // - we tried switching to that descendant but were missing
  3063. // data for some intermediate block between chainActive and the
  3064. // tip.
  3065. // So if this block is itself better than chainActive.Tip() and it wasn't in
  3066. // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
  3067. if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
  3068. if (pindexFirstInvalid == NULL) {
  3069. assert(foundInUnlinked);
  3070. }
  3071. }
  3072. }
  3073. // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
  3074. // End: actual consistency checks.
  3075. // Try descending into the first subnode.
  3076. std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
  3077. if (range.first != range.second) {
  3078. // A subnode was found.
  3079. pindex = range.first->second;
  3080. nHeight++;
  3081. continue;
  3082. }
  3083. // This is a leaf node.
  3084. // Move upwards until we reach a node of which we have not yet visited the last child.
  3085. while (pindex) {
  3086. // We are going to either move to a parent or a sibling of pindex.
  3087. // If pindex was the first with a certain property, unset the corresponding variable.
  3088. if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
  3089. if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
  3090. if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = NULL;
  3091. if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
  3092. if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = NULL;
  3093. if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
  3094. if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
  3095. // Find our parent.
  3096. CBlockIndex* pindexPar = pindex->pprev;
  3097. // Find which child we just visited.
  3098. std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
  3099. while (rangePar.first->second != pindex) {
  3100. assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
  3101. rangePar.first++;
  3102. }
  3103. // Proceed to the next one.
  3104. rangePar.first++;
  3105. if (rangePar.first != rangePar.second) {
  3106. // Move to the sibling.
  3107. pindex = rangePar.first->second;
  3108. break;
  3109. } else {
  3110. // Move up further.
  3111. pindex = pindexPar;
  3112. nHeight--;
  3113. continue;
  3114. }
  3115. }
  3116. }
  3117. // Check that we actually traversed the entire map.
  3118. assert(nNodes == forward.size());
  3119. }
  3120. //////////////////////////////////////////////////////////////////////////////
  3121. //
  3122. // CAlert
  3123. //
  3124. string GetWarnings(string strFor)
  3125. {
  3126. int nPriority = 0;
  3127. string strStatusBar;
  3128. string strRPC;
  3129. if (!CLIENT_VERSION_IS_RELEASE)
  3130. strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
  3131. if (GetBoolArg("-testsafemode", false))
  3132. strStatusBar = strRPC = "testsafemode enabled";
  3133. // Misc warnings like out of disk space and clock is wrong
  3134. if (strMiscWarning != "")
  3135. {
  3136. nPriority = 1000;
  3137. strStatusBar = strMiscWarning;
  3138. }
  3139. if (fLargeWorkForkFound)
  3140. {
  3141. nPriority = 2000;
  3142. strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
  3143. }
  3144. else if (fLargeWorkInvalidChainFound)
  3145. {
  3146. nPriority = 2000;
  3147. 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.");
  3148. }
  3149. // Alerts
  3150. {
  3151. LOCK(cs_mapAlerts);
  3152. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  3153. {
  3154. const CAlert& alert = item.second;
  3155. if (alert.AppliesToMe() && alert.nPriority > nPriority)
  3156. {
  3157. nPriority = alert.nPriority;
  3158. strStatusBar = alert.strStatusBar;
  3159. }
  3160. }
  3161. }
  3162. if (strFor == "statusbar")
  3163. return strStatusBar;
  3164. else if (strFor == "rpc")
  3165. return strRPC;
  3166. assert(!"GetWarnings(): invalid parameter");
  3167. return "error";
  3168. }
  3169. //////////////////////////////////////////////////////////////////////////////
  3170. //
  3171. // Messages
  3172. //
  3173. bool static AlreadyHave(const CInv& inv)
  3174. {
  3175. switch (inv.type)
  3176. {
  3177. case MSG_TX:
  3178. {
  3179. bool txInMap = false;
  3180. txInMap = mempool.exists(inv.hash);
  3181. return txInMap || mapOrphanTransactions.count(inv.hash) ||
  3182. pcoinsTip->HaveCoins(inv.hash);
  3183. }
  3184. case MSG_BLOCK:
  3185. return mapBlockIndex.count(inv.hash);
  3186. }
  3187. // Don't know what it is, just say we already got one
  3188. return true;
  3189. }
  3190. void static ProcessGetData(CNode* pfrom)
  3191. {
  3192. std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
  3193. vector<CInv> vNotFound;
  3194. LOCK(cs_main);
  3195. while (it != pfrom->vRecvGetData.end()) {
  3196. // Don't bother if send buffer is too full to respond anyway
  3197. if (pfrom->nSendSize >= SendBufferSize())
  3198. break;
  3199. const CInv &inv = *it;
  3200. {
  3201. boost::this_thread::interruption_point();
  3202. it++;
  3203. if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
  3204. {
  3205. bool send = false;
  3206. BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
  3207. if (mi != mapBlockIndex.end())
  3208. {
  3209. if (chainActive.Contains(mi->second)) {
  3210. send = true;
  3211. } else {
  3212. // To prevent fingerprinting attacks, only send blocks outside of the active
  3213. // chain if they are valid, and no more than a month older than the best header
  3214. // chain we know about.
  3215. send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
  3216. (mi->second->GetBlockTime() > pindexBestHeader->GetBlockTime() - 30 * 24 * 60 * 60);
  3217. if (!send) {
  3218. LogPrintf("%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId());
  3219. }
  3220. }
  3221. }
  3222. // Pruned nodes may have deleted the block, so check whether
  3223. // it's available before trying to send.
  3224. if (send && (mi->second->nStatus & BLOCK_HAVE_DATA))
  3225. {
  3226. // Send block from disk
  3227. CBlock block;
  3228. if (!ReadBlockFromDisk(block, (*mi).second))
  3229. assert(!"cannot load block from disk");
  3230. if (inv.type == MSG_BLOCK)
  3231. pfrom->PushMessage("block", block);
  3232. else // MSG_FILTERED_BLOCK)
  3233. {
  3234. LOCK(pfrom->cs_filter);
  3235. if (pfrom->pfilter)
  3236. {
  3237. CMerkleBlock merkleBlock(block, *pfrom->pfilter);
  3238. pfrom->PushMessage("merkleblock", merkleBlock);
  3239. // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
  3240. // This avoids hurting performance by pointlessly requiring a round-trip
  3241. // Note that there is currently no way for a node to request any single transactions we didn't send here -
  3242. // they must either disconnect and retry or request the full block.
  3243. // Thus, the protocol spec specified allows for us to provide duplicate txn here,
  3244. // however we MUST always provide at least what the remote peer needs
  3245. typedef std::pair<unsigned int, uint256> PairType;
  3246. BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
  3247. if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
  3248. pfrom->PushMessage("tx", block.vtx[pair.first]);
  3249. }
  3250. // else
  3251. // no response
  3252. }
  3253. // Trigger the peer node to send a getblocks request for the next batch of inventory
  3254. if (inv.hash == pfrom->hashContinue)
  3255. {
  3256. // Bypass PushInventory, this must send even if redundant,
  3257. // and we want it right after the last block so they don't
  3258. // wait for other stuff first.
  3259. vector<CInv> vInv;
  3260. vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
  3261. pfrom->PushMessage("inv", vInv);
  3262. pfrom->hashContinue.SetNull();
  3263. }
  3264. }
  3265. }
  3266. else if (inv.IsKnownType())
  3267. {
  3268. // Send stream from relay memory
  3269. bool pushed = false;
  3270. {
  3271. LOCK(cs_mapRelay);
  3272. map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
  3273. if (mi != mapRelay.end()) {
  3274. pfrom->PushMessage(inv.GetCommand(), (*mi).second);
  3275. pushed = true;
  3276. }
  3277. }
  3278. if (!pushed && inv.type == MSG_TX) {
  3279. CTransaction tx;
  3280. if (mempool.lookup(inv.hash, tx)) {
  3281. CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
  3282. ss.reserve(1000);
  3283. ss << tx;
  3284. pfrom->PushMessage("tx", ss);
  3285. pushed = true;
  3286. }
  3287. }
  3288. if (!pushed) {
  3289. vNotFound.push_back(inv);
  3290. }
  3291. }
  3292. // Track requests for our stuff.
  3293. GetMainSignals().Inventory(inv.hash);
  3294. if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
  3295. break;
  3296. }
  3297. }
  3298. pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
  3299. if (!vNotFound.empty()) {
  3300. // Let the peer know that we didn't find what it asked for, so it doesn't
  3301. // have to wait around forever. Currently only SPV clients actually care
  3302. // about this message: it's needed when they are recursively walking the
  3303. // dependencies of relevant unconfirmed transactions. SPV clients want to
  3304. // do that because they want to know about (and store and rebroadcast and
  3305. // risk analyze) the dependencies of transactions relevant to them, without
  3306. // having to download the entire memory pool.
  3307. pfrom->PushMessage("notfound", vNotFound);
  3308. }
  3309. }
  3310. bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
  3311. {
  3312. const CChainParams& chainparams = Params();
  3313. RandAddSeedPerfmon();
  3314. LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
  3315. if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
  3316. {
  3317. LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
  3318. return true;
  3319. }
  3320. if (strCommand == "version")
  3321. {
  3322. // Each connection can only send one version message
  3323. if (pfrom->nVersion != 0)
  3324. {
  3325. pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
  3326. Misbehaving(pfrom->GetId(), 1);
  3327. return false;
  3328. }
  3329. int64_t nTime;
  3330. CAddress addrMe;
  3331. CAddress addrFrom;
  3332. uint64_t nNonce = 1;
  3333. vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
  3334. if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
  3335. {
  3336. // disconnect from peers older than this proto version
  3337. LogPrintf("peer=%d using obsolete version %i; disconnecting\n", pfrom->id, pfrom->nVersion);
  3338. pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
  3339. strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
  3340. pfrom->fDisconnect = true;
  3341. return false;
  3342. }
  3343. if (pfrom->nVersion == 10300)
  3344. pfrom->nVersion = 300;
  3345. if (!vRecv.empty())
  3346. vRecv >> addrFrom >> nNonce;
  3347. if (!vRecv.empty()) {
  3348. vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
  3349. pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
  3350. }
  3351. if (!vRecv.empty())
  3352. vRecv >> pfrom->nStartingHeight;
  3353. if (!vRecv.empty())
  3354. vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
  3355. else
  3356. pfrom->fRelayTxes = true;
  3357. // Disconnect if we connected to ourself
  3358. if (nNonce == nLocalHostNonce && nNonce > 1)
  3359. {
  3360. LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
  3361. pfrom->fDisconnect = true;
  3362. return true;
  3363. }
  3364. pfrom->addrLocal = addrMe;
  3365. if (pfrom->fInbound && addrMe.IsRoutable())
  3366. {
  3367. SeenLocal(addrMe);
  3368. }
  3369. // Be shy and don't send version until we hear
  3370. if (pfrom->fInbound)
  3371. pfrom->PushVersion();
  3372. pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
  3373. // Potentially mark this peer as a preferred download peer.
  3374. UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
  3375. // Change version
  3376. pfrom->PushMessage("verack");
  3377. pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
  3378. if (!pfrom->fInbound)
  3379. {
  3380. // Advertise our address
  3381. if (fListen && !IsInitialBlockDownload())
  3382. {
  3383. CAddress addr = GetLocalAddress(&pfrom->addr);
  3384. if (addr.IsRoutable())
  3385. {
  3386. pfrom->PushAddress(addr);
  3387. } else if (IsPeerAddrLocalGood(pfrom)) {
  3388. addr.SetIP(pfrom->addrLocal);
  3389. pfrom->PushAddress(addr);
  3390. }
  3391. }
  3392. // Get recent addresses
  3393. if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
  3394. {
  3395. pfrom->PushMessage("getaddr");
  3396. pfrom->fGetAddr = true;
  3397. }
  3398. addrman.Good(pfrom->addr);
  3399. } else {
  3400. if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
  3401. {
  3402. addrman.Add(addrFrom, addrFrom);
  3403. addrman.Good(addrFrom);
  3404. }
  3405. }
  3406. // Relay alerts
  3407. {
  3408. LOCK(cs_mapAlerts);
  3409. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  3410. item.second.RelayTo(pfrom);
  3411. }
  3412. pfrom->fSuccessfullyConnected = true;
  3413. string remoteAddr;
  3414. if (fLogIPs)
  3415. remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
  3416. LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
  3417. pfrom->cleanSubVer, pfrom->nVersion,
  3418. pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
  3419. remoteAddr);
  3420. int64_t nTimeOffset = nTime - GetTime();
  3421. pfrom->nTimeOffset = nTimeOffset;
  3422. AddTimeData(pfrom->addr, nTimeOffset);
  3423. }
  3424. else if (pfrom->nVersion == 0)
  3425. {
  3426. // Must have a version message before anything else
  3427. Misbehaving(pfrom->GetId(), 1);
  3428. return false;
  3429. }
  3430. else if (strCommand == "verack")
  3431. {
  3432. pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
  3433. // Mark this node as currently connected, so we update its timestamp later.
  3434. if (pfrom->fNetworkNode) {
  3435. LOCK(cs_main);
  3436. State(pfrom->GetId())->fCurrentlyConnected = true;
  3437. }
  3438. }
  3439. else if (strCommand == "addr")
  3440. {
  3441. vector<CAddress> vAddr;
  3442. vRecv >> vAddr;
  3443. // Don't want addr from older versions unless seeding
  3444. if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
  3445. return true;
  3446. if (vAddr.size() > 1000)
  3447. {
  3448. Misbehaving(pfrom->GetId(), 20);
  3449. return error("message addr size() = %u", vAddr.size());
  3450. }
  3451. // Store the new addresses
  3452. vector<CAddress> vAddrOk;
  3453. int64_t nNow = GetAdjustedTime();
  3454. int64_t nSince = nNow - 10 * 60;
  3455. BOOST_FOREACH(CAddress& addr, vAddr)
  3456. {
  3457. boost::this_thread::interruption_point();
  3458. if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
  3459. addr.nTime = nNow - 5 * 24 * 60 * 60;
  3460. pfrom->AddAddressKnown(addr);
  3461. bool fReachable = IsReachable(addr);
  3462. if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
  3463. {
  3464. // Relay to a limited number of other nodes
  3465. {
  3466. LOCK(cs_vNodes);
  3467. // Use deterministic randomness to send to the same nodes for 24 hours
  3468. // at a time so the setAddrKnowns of the chosen nodes prevent repeats
  3469. static uint256 hashSalt;
  3470. if (hashSalt.IsNull())
  3471. hashSalt = GetRandHash();
  3472. uint64_t hashAddr = addr.GetHash();
  3473. uint256 hashRand = ArithToUint256(UintToArith256(hashSalt) ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)));
  3474. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  3475. multimap<uint256, CNode*> mapMix;
  3476. BOOST_FOREACH(CNode* pnode, vNodes)
  3477. {
  3478. if (pnode->nVersion < CADDR_TIME_VERSION)
  3479. continue;
  3480. unsigned int nPointer;
  3481. memcpy(&nPointer, &pnode, sizeof(nPointer));
  3482. uint256 hashKey = ArithToUint256(UintToArith256(hashRand) ^ nPointer);
  3483. hashKey = Hash(BEGIN(hashKey), END(hashKey));
  3484. mapMix.insert(make_pair(hashKey, pnode));
  3485. }
  3486. int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
  3487. for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
  3488. ((*mi).second)->PushAddress(addr);
  3489. }
  3490. }
  3491. // Do not store addresses outside our network
  3492. if (fReachable)
  3493. vAddrOk.push_back(addr);
  3494. }
  3495. addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
  3496. if (vAddr.size() < 1000)
  3497. pfrom->fGetAddr = false;
  3498. if (pfrom->fOneShot)
  3499. pfrom->fDisconnect = true;
  3500. }
  3501. else if (strCommand == "inv")
  3502. {
  3503. vector<CInv> vInv;
  3504. vRecv >> vInv;
  3505. if (vInv.size() > MAX_INV_SZ)
  3506. {
  3507. Misbehaving(pfrom->GetId(), 20);
  3508. return error("message inv size() = %u", vInv.size());
  3509. }
  3510. LOCK(cs_main);
  3511. std::vector<CInv> vToFetch;
  3512. for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
  3513. {
  3514. const CInv &inv = vInv[nInv];
  3515. boost::this_thread::interruption_point();
  3516. pfrom->AddInventoryKnown(inv);
  3517. bool fAlreadyHave = AlreadyHave(inv);
  3518. LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
  3519. if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
  3520. pfrom->AskFor(inv);
  3521. if (inv.type == MSG_BLOCK) {
  3522. UpdateBlockAvailability(pfrom->GetId(), inv.hash);
  3523. if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
  3524. // First request the headers preceding the announced block. In the normal fully-synced
  3525. // case where a new block is announced that succeeds the current tip (no reorganization),
  3526. // there are no such headers.
  3527. // Secondly, and only when we are close to being synced, we request the announced block directly,
  3528. // to avoid an extra round-trip. Note that we must *first* ask for the headers, so by the
  3529. // time the block arrives, the header chain leading up to it is already validated. Not
  3530. // doing this will result in the received block being rejected as an orphan in case it is
  3531. // not a direct successor.
  3532. pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexBestHeader), inv.hash);
  3533. CNodeState *nodestate = State(pfrom->GetId());
  3534. if (chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - chainparams.GetConsensus().nPowTargetSpacing * 20 &&
  3535. nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
  3536. vToFetch.push_back(inv);
  3537. // Mark block as in flight already, even though the actual "getdata" message only goes out
  3538. // later (within the same cs_main lock, though).
  3539. MarkBlockAsInFlight(pfrom->GetId(), inv.hash);
  3540. }
  3541. LogPrint("net", "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
  3542. }
  3543. }
  3544. // Track requests for our stuff
  3545. GetMainSignals().Inventory(inv.hash);
  3546. if (pfrom->nSendSize > (SendBufferSize() * 2)) {
  3547. Misbehaving(pfrom->GetId(), 50);
  3548. return error("send buffer size() = %u", pfrom->nSendSize);
  3549. }
  3550. }
  3551. if (!vToFetch.empty())
  3552. pfrom->PushMessage("getdata", vToFetch);
  3553. }
  3554. else if (strCommand == "getdata")
  3555. {
  3556. vector<CInv> vInv;
  3557. vRecv >> vInv;
  3558. if (vInv.size() > MAX_INV_SZ)
  3559. {
  3560. Misbehaving(pfrom->GetId(), 20);
  3561. return error("message getdata size() = %u", vInv.size());
  3562. }
  3563. if (fDebug || (vInv.size() != 1))
  3564. LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
  3565. if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
  3566. LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
  3567. pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
  3568. ProcessGetData(pfrom);
  3569. }
  3570. else if (strCommand == "getblocks")
  3571. {
  3572. CBlockLocator locator;
  3573. uint256 hashStop;
  3574. vRecv >> locator >> hashStop;
  3575. LOCK(cs_main);
  3576. // Find the last block the caller has in the main chain
  3577. CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
  3578. // Send the rest of the chain
  3579. if (pindex)
  3580. pindex = chainActive.Next(pindex);
  3581. int nLimit = 500;
  3582. LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->id);
  3583. for (; pindex; pindex = chainActive.Next(pindex))
  3584. {
  3585. if (pindex->GetBlockHash() == hashStop)
  3586. {
  3587. LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  3588. break;
  3589. }
  3590. pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
  3591. if (--nLimit <= 0)
  3592. {
  3593. // When this block is requested, we'll send an inv that'll
  3594. // trigger the peer to getblocks the next batch of inventory.
  3595. LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  3596. pfrom->hashContinue = pindex->GetBlockHash();
  3597. break;
  3598. }
  3599. }
  3600. }
  3601. else if (strCommand == "getheaders")
  3602. {
  3603. CBlockLocator locator;
  3604. uint256 hashStop;
  3605. vRecv >> locator >> hashStop;
  3606. LOCK(cs_main);
  3607. CBlockIndex* pindex = NULL;
  3608. if (locator.IsNull())
  3609. {
  3610. // If locator is null, return the hashStop block
  3611. BlockMap::iterator mi = mapBlockIndex.find(hashStop);
  3612. if (mi == mapBlockIndex.end())
  3613. return true;
  3614. pindex = (*mi).second;
  3615. }
  3616. else
  3617. {
  3618. // Find the last block the caller has in the main chain
  3619. pindex = FindForkInGlobalIndex(chainActive, locator);
  3620. if (pindex)
  3621. pindex = chainActive.Next(pindex);
  3622. }
  3623. // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
  3624. vector<CBlock> vHeaders;
  3625. int nLimit = MAX_HEADERS_RESULTS;
  3626. LogPrint("net", "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
  3627. for (; pindex; pindex = chainActive.Next(pindex))
  3628. {
  3629. vHeaders.push_back(pindex->GetBlockHeader());
  3630. if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
  3631. break;
  3632. }
  3633. pfrom->PushMessage("headers", vHeaders);
  3634. }
  3635. else if (strCommand == "tx")
  3636. {
  3637. vector<uint256> vWorkQueue;
  3638. vector<uint256> vEraseQueue;
  3639. CTransaction tx;
  3640. vRecv >> tx;
  3641. CInv inv(MSG_TX, tx.GetHash());
  3642. pfrom->AddInventoryKnown(inv);
  3643. LOCK(cs_main);
  3644. bool fMissingInputs = false;
  3645. CValidationState state;
  3646. mapAlreadyAskedFor.erase(inv);
  3647. if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
  3648. {
  3649. mempool.check(pcoinsTip);
  3650. RelayTransaction(tx);
  3651. vWorkQueue.push_back(inv.hash);
  3652. vEraseQueue.push_back(inv.hash);
  3653. LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s: accepted %s (poolsz %u)\n",
  3654. pfrom->id, pfrom->cleanSubVer,
  3655. tx.GetHash().ToString(),
  3656. mempool.mapTx.size());
  3657. // Recursively process any orphan transactions that depended on this one
  3658. set<NodeId> setMisbehaving;
  3659. for (unsigned int i = 0; i < vWorkQueue.size(); i++)
  3660. {
  3661. map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
  3662. if (itByPrev == mapOrphanTransactionsByPrev.end())
  3663. continue;
  3664. for (set<uint256>::iterator mi = itByPrev->second.begin();
  3665. mi != itByPrev->second.end();
  3666. ++mi)
  3667. {
  3668. const uint256& orphanHash = *mi;
  3669. const CTransaction& orphanTx = mapOrphanTransactions[orphanHash].tx;
  3670. NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
  3671. bool fMissingInputs2 = false;
  3672. // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
  3673. // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
  3674. // anyone relaying LegitTxX banned)
  3675. CValidationState stateDummy;
  3676. vEraseQueue.push_back(orphanHash);
  3677. if (setMisbehaving.count(fromPeer))
  3678. continue;
  3679. if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
  3680. {
  3681. LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
  3682. RelayTransaction(orphanTx);
  3683. vWorkQueue.push_back(orphanHash);
  3684. }
  3685. else if (!fMissingInputs2)
  3686. {
  3687. int nDos = 0;
  3688. if (stateDummy.IsInvalid(nDos) && nDos > 0)
  3689. {
  3690. // Punish peer that gave us an invalid orphan tx
  3691. Misbehaving(fromPeer, nDos);
  3692. setMisbehaving.insert(fromPeer);
  3693. LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
  3694. }
  3695. // too-little-fee orphan
  3696. LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
  3697. }
  3698. mempool.check(pcoinsTip);
  3699. }
  3700. }
  3701. BOOST_FOREACH(uint256 hash, vEraseQueue)
  3702. EraseOrphanTx(hash);
  3703. }
  3704. else if (fMissingInputs)
  3705. {
  3706. AddOrphanTx(tx, pfrom->GetId());
  3707. // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
  3708. unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
  3709. unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
  3710. if (nEvicted > 0)
  3711. LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
  3712. } else if (pfrom->fWhitelisted) {
  3713. // Always relay transactions received from whitelisted peers, even
  3714. // if they are already in the mempool (allowing the node to function
  3715. // as a gateway for nodes hidden behind it).
  3716. RelayTransaction(tx);
  3717. }
  3718. int nDoS = 0;
  3719. if (state.IsInvalid(nDoS))
  3720. {
  3721. LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
  3722. pfrom->id, pfrom->cleanSubVer,
  3723. state.GetRejectReason());
  3724. pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
  3725. state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
  3726. if (nDoS > 0)
  3727. Misbehaving(pfrom->GetId(), nDoS);
  3728. }
  3729. }
  3730. else if (strCommand == "headers" && !fImporting && !fReindex) // Ignore headers received while importing
  3731. {
  3732. std::vector<CBlockHeader> headers;
  3733. // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
  3734. unsigned int nCount = ReadCompactSize(vRecv);
  3735. if (nCount > MAX_HEADERS_RESULTS) {
  3736. Misbehaving(pfrom->GetId(), 20);
  3737. return error("headers message size = %u", nCount);
  3738. }
  3739. headers.resize(nCount);
  3740. for (unsigned int n = 0; n < nCount; n++) {
  3741. vRecv >> headers[n];
  3742. ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
  3743. }
  3744. LOCK(cs_main);
  3745. if (nCount == 0) {
  3746. // Nothing interesting. Stop asking this peers for more headers.
  3747. return true;
  3748. }
  3749. CBlockIndex *pindexLast = NULL;
  3750. BOOST_FOREACH(const CBlockHeader& header, headers) {
  3751. CValidationState state;
  3752. if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
  3753. Misbehaving(pfrom->GetId(), 20);
  3754. return error("non-continuous headers sequence");
  3755. }
  3756. if (!AcceptBlockHeader(header, state, &pindexLast)) {
  3757. int nDoS;
  3758. if (state.IsInvalid(nDoS)) {
  3759. if (nDoS > 0)
  3760. Misbehaving(pfrom->GetId(), nDoS);
  3761. return error("invalid header received");
  3762. }
  3763. }
  3764. }
  3765. if (pindexLast)
  3766. UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
  3767. if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
  3768. // Headers message had its maximum size; the peer may have more headers.
  3769. // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
  3770. // from there instead.
  3771. LogPrint("net", "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
  3772. pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256());
  3773. }
  3774. CheckBlockIndex();
  3775. }
  3776. else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
  3777. {
  3778. CBlock block;
  3779. vRecv >> block;
  3780. CInv inv(MSG_BLOCK, block.GetHash());
  3781. LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
  3782. pfrom->AddInventoryKnown(inv);
  3783. CValidationState state;
  3784. ProcessNewBlock(state, pfrom, &block);
  3785. int nDoS;
  3786. if (state.IsInvalid(nDoS)) {
  3787. pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
  3788. state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
  3789. if (nDoS > 0) {
  3790. LOCK(cs_main);
  3791. Misbehaving(pfrom->GetId(), nDoS);
  3792. }
  3793. }
  3794. }
  3795. // This asymmetric behavior for inbound and outbound connections was introduced
  3796. // to prevent a fingerprinting attack: an attacker can send specific fake addresses
  3797. // to users' AddrMan and later request them by sending getaddr messages.
  3798. // Making nodes which are behind NAT and can only make outgoing connections ignore
  3799. // the getaddr message mitigates the attack.
  3800. else if ((strCommand == "getaddr") && (pfrom->fInbound))
  3801. {
  3802. pfrom->vAddrToSend.clear();
  3803. vector<CAddress> vAddr = addrman.GetAddr();
  3804. BOOST_FOREACH(const CAddress &addr, vAddr)
  3805. pfrom->PushAddress(addr);
  3806. }
  3807. else if (strCommand == "mempool")
  3808. {
  3809. LOCK2(cs_main, pfrom->cs_filter);
  3810. std::vector<uint256> vtxid;
  3811. mempool.queryHashes(vtxid);
  3812. vector<CInv> vInv;
  3813. BOOST_FOREACH(uint256& hash, vtxid) {
  3814. CInv inv(MSG_TX, hash);
  3815. CTransaction tx;
  3816. bool fInMemPool = mempool.lookup(hash, tx);
  3817. if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
  3818. if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
  3819. (!pfrom->pfilter))
  3820. vInv.push_back(inv);
  3821. if (vInv.size() == MAX_INV_SZ) {
  3822. pfrom->PushMessage("inv", vInv);
  3823. vInv.clear();
  3824. }
  3825. }
  3826. if (vInv.size() > 0)
  3827. pfrom->PushMessage("inv", vInv);
  3828. }
  3829. else if (strCommand == "ping")
  3830. {
  3831. if (pfrom->nVersion > BIP0031_VERSION)
  3832. {
  3833. uint64_t nonce = 0;
  3834. vRecv >> nonce;
  3835. // Echo the message back with the nonce. This allows for two useful features:
  3836. //
  3837. // 1) A remote node can quickly check if the connection is operational
  3838. // 2) Remote nodes can measure the latency of the network thread. If this node
  3839. // is overloaded it won't respond to pings quickly and the remote node can
  3840. // avoid sending us more work, like chain download requests.
  3841. //
  3842. // The nonce stops the remote getting confused between different pings: without
  3843. // it, if the remote node sends a ping once per second and this node takes 5
  3844. // seconds to respond to each, the 5th ping the remote sends would appear to
  3845. // return very quickly.
  3846. pfrom->PushMessage("pong", nonce);
  3847. }
  3848. }
  3849. else if (strCommand == "pong")
  3850. {
  3851. int64_t pingUsecEnd = nTimeReceived;
  3852. uint64_t nonce = 0;
  3853. size_t nAvail = vRecv.in_avail();
  3854. bool bPingFinished = false;
  3855. std::string sProblem;
  3856. if (nAvail >= sizeof(nonce)) {
  3857. vRecv >> nonce;
  3858. // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
  3859. if (pfrom->nPingNonceSent != 0) {
  3860. if (nonce == pfrom->nPingNonceSent) {
  3861. // Matching pong received, this ping is no longer outstanding
  3862. bPingFinished = true;
  3863. int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
  3864. if (pingUsecTime > 0) {
  3865. // Successful ping time measurement, replace previous
  3866. pfrom->nPingUsecTime = pingUsecTime;
  3867. } else {
  3868. // This should never happen
  3869. sProblem = "Timing mishap";
  3870. }
  3871. } else {
  3872. // Nonce mismatches are normal when pings are overlapping
  3873. sProblem = "Nonce mismatch";
  3874. if (nonce == 0) {
  3875. // This is most likely a bug in another implementation somewhere; cancel this ping
  3876. bPingFinished = true;
  3877. sProblem = "Nonce zero";
  3878. }
  3879. }
  3880. } else {
  3881. sProblem = "Unsolicited pong without ping";
  3882. }
  3883. } else {
  3884. // This is most likely a bug in another implementation somewhere; cancel this ping
  3885. bPingFinished = true;
  3886. sProblem = "Short payload";
  3887. }
  3888. if (!(sProblem.empty())) {
  3889. LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
  3890. pfrom->id,
  3891. pfrom->cleanSubVer,
  3892. sProblem,
  3893. pfrom->nPingNonceSent,
  3894. nonce,
  3895. nAvail);
  3896. }
  3897. if (bPingFinished) {
  3898. pfrom->nPingNonceSent = 0;
  3899. }
  3900. }
  3901. else if (strCommand == "alert")
  3902. {
  3903. CAlert alert;
  3904. vRecv >> alert;
  3905. uint256 alertHash = alert.GetHash();
  3906. if (pfrom->setKnown.count(alertHash) == 0)
  3907. {
  3908. if (alert.ProcessAlert(Params().AlertKey()))
  3909. {
  3910. // Relay
  3911. pfrom->setKnown.insert(alertHash);
  3912. {
  3913. LOCK(cs_vNodes);
  3914. BOOST_FOREACH(CNode* pnode, vNodes)
  3915. alert.RelayTo(pnode);
  3916. }
  3917. }
  3918. else {
  3919. // Small DoS penalty so peers that send us lots of
  3920. // duplicate/expired/invalid-signature/whatever alerts
  3921. // eventually get banned.
  3922. // This isn't a Misbehaving(100) (immediate ban) because the
  3923. // peer might be an older or different implementation with
  3924. // a different signature key, etc.
  3925. Misbehaving(pfrom->GetId(), 10);
  3926. }
  3927. }
  3928. }
  3929. else if (strCommand == "filterload")
  3930. {
  3931. CBloomFilter filter;
  3932. vRecv >> filter;
  3933. if (!filter.IsWithinSizeConstraints())
  3934. // There is no excuse for sending a too-large filter
  3935. Misbehaving(pfrom->GetId(), 100);
  3936. else
  3937. {
  3938. LOCK(pfrom->cs_filter);
  3939. delete pfrom->pfilter;
  3940. pfrom->pfilter = new CBloomFilter(filter);
  3941. pfrom->pfilter->UpdateEmptyFull();
  3942. }
  3943. pfrom->fRelayTxes = true;
  3944. }
  3945. else if (strCommand == "filteradd")
  3946. {
  3947. vector<unsigned char> vData;
  3948. vRecv >> vData;
  3949. // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
  3950. // and thus, the maximum size any matched object can have) in a filteradd message
  3951. if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
  3952. {
  3953. Misbehaving(pfrom->GetId(), 100);
  3954. } else {
  3955. LOCK(pfrom->cs_filter);
  3956. if (pfrom->pfilter)
  3957. pfrom->pfilter->insert(vData);
  3958. else
  3959. Misbehaving(pfrom->GetId(), 100);
  3960. }
  3961. }
  3962. else if (strCommand == "filterclear")
  3963. {
  3964. LOCK(pfrom->cs_filter);
  3965. delete pfrom->pfilter;
  3966. pfrom->pfilter = new CBloomFilter();
  3967. pfrom->fRelayTxes = true;
  3968. }
  3969. else if (strCommand == "reject")
  3970. {
  3971. if (fDebug) {
  3972. try {
  3973. string strMsg; unsigned char ccode; string strReason;
  3974. vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
  3975. ostringstream ss;
  3976. ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
  3977. if (strMsg == "block" || strMsg == "tx")
  3978. {
  3979. uint256 hash;
  3980. vRecv >> hash;
  3981. ss << ": hash " << hash.ToString();
  3982. }
  3983. LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
  3984. } catch (const std::ios_base::failure&) {
  3985. // Avoid feedback loops by preventing reject messages from triggering a new reject message.
  3986. LogPrint("net", "Unparseable reject message received\n");
  3987. }
  3988. }
  3989. }
  3990. else
  3991. {
  3992. // Ignore unknown commands for extensibility
  3993. LogPrint("net", "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->id);
  3994. }
  3995. return true;
  3996. }
  3997. // requires LOCK(cs_vRecvMsg)
  3998. bool ProcessMessages(CNode* pfrom)
  3999. {
  4000. //if (fDebug)
  4001. // LogPrintf("%s(%u messages)\n", __func__, pfrom->vRecvMsg.size());
  4002. //
  4003. // Message format
  4004. // (4) message start
  4005. // (12) command
  4006. // (4) size
  4007. // (4) checksum
  4008. // (x) data
  4009. //
  4010. bool fOk = true;
  4011. if (!pfrom->vRecvGetData.empty())
  4012. ProcessGetData(pfrom);
  4013. // this maintains the order of responses
  4014. if (!pfrom->vRecvGetData.empty()) return fOk;
  4015. std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
  4016. while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
  4017. // Don't bother if send buffer is too full to respond anyway
  4018. if (pfrom->nSendSize >= SendBufferSize())
  4019. break;
  4020. // get next message
  4021. CNetMessage& msg = *it;
  4022. //if (fDebug)
  4023. // LogPrintf("%s(message %u msgsz, %u bytes, complete:%s)\n", __func__,
  4024. // msg.hdr.nMessageSize, msg.vRecv.size(),
  4025. // msg.complete() ? "Y" : "N");
  4026. // end, if an incomplete message is found
  4027. if (!msg.complete())
  4028. break;
  4029. // at this point, any failure means we can delete the current message
  4030. it++;
  4031. // Scan for message start
  4032. if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
  4033. LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
  4034. fOk = false;
  4035. break;
  4036. }
  4037. // Read header
  4038. CMessageHeader& hdr = msg.hdr;
  4039. if (!hdr.IsValid(Params().MessageStart()))
  4040. {
  4041. LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
  4042. continue;
  4043. }
  4044. string strCommand = hdr.GetCommand();
  4045. // Message size
  4046. unsigned int nMessageSize = hdr.nMessageSize;
  4047. // Checksum
  4048. CDataStream& vRecv = msg.vRecv;
  4049. uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
  4050. unsigned int nChecksum = ReadLE32((unsigned char*)&hash);
  4051. if (nChecksum != hdr.nChecksum)
  4052. {
  4053. LogPrintf("%s(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", __func__,
  4054. SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
  4055. continue;
  4056. }
  4057. // Process message
  4058. bool fRet = false;
  4059. try
  4060. {
  4061. fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
  4062. boost::this_thread::interruption_point();
  4063. }
  4064. catch (const std::ios_base::failure& e)
  4065. {
  4066. pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
  4067. if (strstr(e.what(), "end of data"))
  4068. {
  4069. // Allow exceptions from under-length message on vRecv
  4070. 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());
  4071. }
  4072. else if (strstr(e.what(), "size too large"))
  4073. {
  4074. // Allow exceptions from over-long size
  4075. LogPrintf("%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what());
  4076. }
  4077. else
  4078. {
  4079. PrintExceptionContinue(&e, "ProcessMessages()");
  4080. }
  4081. }
  4082. catch (const boost::thread_interrupted&) {
  4083. throw;
  4084. }
  4085. catch (const std::exception& e) {
  4086. PrintExceptionContinue(&e, "ProcessMessages()");
  4087. } catch (...) {
  4088. PrintExceptionContinue(NULL, "ProcessMessages()");
  4089. }
  4090. if (!fRet)
  4091. LogPrintf("%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->id);
  4092. break;
  4093. }
  4094. // In case the connection got shut down, its receive buffer was wiped
  4095. if (!pfrom->fDisconnect)
  4096. pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
  4097. return fOk;
  4098. }
  4099. bool SendMessages(CNode* pto, bool fSendTrickle)
  4100. {
  4101. const Consensus::Params& consensusParams = Params().GetConsensus();
  4102. {
  4103. // Don't send anything until we get its version message
  4104. if (pto->nVersion == 0)
  4105. return true;
  4106. //
  4107. // Message: ping
  4108. //
  4109. bool pingSend = false;
  4110. if (pto->fPingQueued) {
  4111. // RPC ping request by user
  4112. pingSend = true;
  4113. }
  4114. if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
  4115. // Ping automatically sent as a latency probe & keepalive.
  4116. pingSend = true;
  4117. }
  4118. if (pingSend) {
  4119. uint64_t nonce = 0;
  4120. while (nonce == 0) {
  4121. GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
  4122. }
  4123. pto->fPingQueued = false;
  4124. pto->nPingUsecStart = GetTimeMicros();
  4125. if (pto->nVersion > BIP0031_VERSION) {
  4126. pto->nPingNonceSent = nonce;
  4127. pto->PushMessage("ping", nonce);
  4128. } else {
  4129. // Peer is too old to support ping command with nonce, pong will never arrive.
  4130. pto->nPingNonceSent = 0;
  4131. pto->PushMessage("ping");
  4132. }
  4133. }
  4134. TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
  4135. if (!lockMain)
  4136. return true;
  4137. // Address refresh broadcast
  4138. static int64_t nLastRebroadcast;
  4139. if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
  4140. {
  4141. LOCK(cs_vNodes);
  4142. BOOST_FOREACH(CNode* pnode, vNodes)
  4143. {
  4144. // Periodically clear setAddrKnown to allow refresh broadcasts
  4145. if (nLastRebroadcast)
  4146. pnode->setAddrKnown.clear();
  4147. // Rebroadcast our address
  4148. AdvertizeLocal(pnode);
  4149. }
  4150. if (!vNodes.empty())
  4151. nLastRebroadcast = GetTime();
  4152. }
  4153. //
  4154. // Message: addr
  4155. //
  4156. if (fSendTrickle)
  4157. {
  4158. vector<CAddress> vAddr;
  4159. vAddr.reserve(pto->vAddrToSend.size());
  4160. BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
  4161. {
  4162. // returns true if wasn't already contained in the set
  4163. if (pto->setAddrKnown.insert(addr).second)
  4164. {
  4165. vAddr.push_back(addr);
  4166. // receiver rejects addr messages larger than 1000
  4167. if (vAddr.size() >= 1000)
  4168. {
  4169. pto->PushMessage("addr", vAddr);
  4170. vAddr.clear();
  4171. }
  4172. }
  4173. }
  4174. pto->vAddrToSend.clear();
  4175. if (!vAddr.empty())
  4176. pto->PushMessage("addr", vAddr);
  4177. }
  4178. CNodeState &state = *State(pto->GetId());
  4179. if (state.fShouldBan) {
  4180. if (pto->fWhitelisted)
  4181. LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
  4182. else {
  4183. pto->fDisconnect = true;
  4184. if (pto->addr.IsLocal())
  4185. LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
  4186. else
  4187. {
  4188. CNode::Ban(pto->addr);
  4189. }
  4190. }
  4191. state.fShouldBan = false;
  4192. }
  4193. BOOST_FOREACH(const CBlockReject& reject, state.rejects)
  4194. pto->PushMessage("reject", (string)"block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
  4195. state.rejects.clear();
  4196. // Start block sync
  4197. if (pindexBestHeader == NULL)
  4198. pindexBestHeader = chainActive.Tip();
  4199. 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.
  4200. if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex) {
  4201. // Only actively request headers from a single peer, unless we're close to today.
  4202. if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 24 * 60 * 60) {
  4203. state.fSyncStarted = true;
  4204. nSyncStarted++;
  4205. CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
  4206. LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
  4207. pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256());
  4208. }
  4209. }
  4210. // Resend wallet transactions that haven't gotten in a block yet
  4211. // Except during reindex, importing and IBD, when old wallet
  4212. // transactions become unconfirmed and spams other nodes.
  4213. if (!fReindex && !fImporting && !IsInitialBlockDownload())
  4214. {
  4215. GetMainSignals().Broadcast(nTimeBestReceived);
  4216. }
  4217. //
  4218. // Message: inventory
  4219. //
  4220. vector<CInv> vInv;
  4221. vector<CInv> vInvWait;
  4222. {
  4223. LOCK(pto->cs_inventory);
  4224. vInv.reserve(pto->vInventoryToSend.size());
  4225. vInvWait.reserve(pto->vInventoryToSend.size());
  4226. BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
  4227. {
  4228. if (pto->setInventoryKnown.count(inv))
  4229. continue;
  4230. // trickle out tx inv to protect privacy
  4231. if (inv.type == MSG_TX && !fSendTrickle)
  4232. {
  4233. // 1/4 of tx invs blast to all immediately
  4234. static uint256 hashSalt;
  4235. if (hashSalt.IsNull())
  4236. hashSalt = GetRandHash();
  4237. uint256 hashRand = ArithToUint256(UintToArith256(inv.hash) ^ UintToArith256(hashSalt));
  4238. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  4239. bool fTrickleWait = ((UintToArith256(hashRand) & 3) != 0);
  4240. if (fTrickleWait)
  4241. {
  4242. vInvWait.push_back(inv);
  4243. continue;
  4244. }
  4245. }
  4246. // returns true if wasn't already contained in the set
  4247. if (pto->setInventoryKnown.insert(inv).second)
  4248. {
  4249. vInv.push_back(inv);
  4250. if (vInv.size() >= 1000)
  4251. {
  4252. pto->PushMessage("inv", vInv);
  4253. vInv.clear();
  4254. }
  4255. }
  4256. }
  4257. pto->vInventoryToSend = vInvWait;
  4258. }
  4259. if (!vInv.empty())
  4260. pto->PushMessage("inv", vInv);
  4261. // Detect whether we're stalling
  4262. int64_t nNow = GetTimeMicros();
  4263. if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
  4264. // Stalling only triggers when the block download window cannot move. During normal steady state,
  4265. // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
  4266. // should only happen during initial block download.
  4267. LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
  4268. pto->fDisconnect = true;
  4269. }
  4270. // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
  4271. // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
  4272. // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
  4273. // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes
  4274. // to unreasonably increase our timeout.
  4275. if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0 && state.vBlocksInFlight.front().nTime < nNow - 500000 * consensusParams.nPowTargetSpacing * (4 + state.vBlocksInFlight.front().nValidatedQueuedBefore)) {
  4276. LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", state.vBlocksInFlight.front().hash.ToString(), pto->id);
  4277. pto->fDisconnect = true;
  4278. }
  4279. //
  4280. // Message: getdata (blocks)
  4281. //
  4282. vector<CInv> vGetData;
  4283. if (!pto->fDisconnect && !pto->fClient && (fFetch || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
  4284. vector<CBlockIndex*> vToDownload;
  4285. NodeId staller = -1;
  4286. FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
  4287. BOOST_FOREACH(CBlockIndex *pindex, vToDownload) {
  4288. vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
  4289. MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
  4290. LogPrint("net", "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
  4291. pindex->nHeight, pto->id);
  4292. }
  4293. if (state.nBlocksInFlight == 0 && staller != -1) {
  4294. if (State(staller)->nStallingSince == 0) {
  4295. State(staller)->nStallingSince = nNow;
  4296. LogPrint("net", "Stall started peer=%d\n", staller);
  4297. }
  4298. }
  4299. }
  4300. //
  4301. // Message: getdata (non-blocks)
  4302. //
  4303. while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
  4304. {
  4305. const CInv& inv = (*pto->mapAskFor.begin()).second;
  4306. if (!AlreadyHave(inv))
  4307. {
  4308. if (fDebug)
  4309. LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
  4310. vGetData.push_back(inv);
  4311. if (vGetData.size() >= 1000)
  4312. {
  4313. pto->PushMessage("getdata", vGetData);
  4314. vGetData.clear();
  4315. }
  4316. }
  4317. pto->mapAskFor.erase(pto->mapAskFor.begin());
  4318. }
  4319. if (!vGetData.empty())
  4320. pto->PushMessage("getdata", vGetData);
  4321. }
  4322. return true;
  4323. }
  4324. std::string CBlockFileInfo::ToString() const {
  4325. 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));
  4326. }
  4327. class CMainCleanup
  4328. {
  4329. public:
  4330. CMainCleanup() {}
  4331. ~CMainCleanup() {
  4332. // block headers
  4333. BlockMap::iterator it1 = mapBlockIndex.begin();
  4334. for (; it1 != mapBlockIndex.end(); it1++)
  4335. delete (*it1).second;
  4336. mapBlockIndex.clear();
  4337. // orphan transactions
  4338. mapOrphanTransactions.clear();
  4339. mapOrphanTransactionsByPrev.clear();
  4340. }
  4341. } instance_of_cmaincleanup;