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.

validation.cpp 209KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2017 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 <validation.h>
  6. #include <arith_uint256.h>
  7. #include <chain.h>
  8. #include <chainparams.h>
  9. #include <checkpoints.h>
  10. #include <checkqueue.h>
  11. #include <consensus/consensus.h>
  12. #include <consensus/merkle.h>
  13. #include <consensus/tx_verify.h>
  14. #include <consensus/validation.h>
  15. #include <cuckoocache.h>
  16. #include <hash.h>
  17. #include <init.h>
  18. #include <policy/fees.h>
  19. #include <policy/policy.h>
  20. #include <policy/rbf.h>
  21. #include <pow.h>
  22. #include <primitives/block.h>
  23. #include <primitives/transaction.h>
  24. #include <random.h>
  25. #include <reverse_iterator.h>
  26. #include <script/script.h>
  27. #include <script/sigcache.h>
  28. #include <script/standard.h>
  29. #include <timedata.h>
  30. #include <tinyformat.h>
  31. #include <txdb.h>
  32. #include <txmempool.h>
  33. #include <ui_interface.h>
  34. #include <undo.h>
  35. #include <util.h>
  36. #include <utilmoneystr.h>
  37. #include <utilstrencodings.h>
  38. #include <validationinterface.h>
  39. #include <warnings.h>
  40. #include <future>
  41. #include <sstream>
  42. #include <boost/algorithm/string/replace.hpp>
  43. #include <boost/algorithm/string/join.hpp>
  44. #include <boost/thread.hpp>
  45. #if defined(NDEBUG)
  46. # error "Bitcoin cannot be compiled without assertions."
  47. #endif
  48. #define MICRO 0.000001
  49. #define MILLI 0.001
  50. /**
  51. * Global state
  52. */
  53. namespace {
  54. struct CBlockIndexWorkComparator
  55. {
  56. bool operator()(const CBlockIndex *pa, const CBlockIndex *pb) const {
  57. // First sort by most total work, ...
  58. if (pa->nChainWork > pb->nChainWork) return false;
  59. if (pa->nChainWork < pb->nChainWork) return true;
  60. // ... then by earliest time received, ...
  61. if (pa->nSequenceId < pb->nSequenceId) return false;
  62. if (pa->nSequenceId > pb->nSequenceId) return true;
  63. // Use pointer address as tie breaker (should only happen with blocks
  64. // loaded from disk, as those all have id 0).
  65. if (pa < pb) return false;
  66. if (pa > pb) return true;
  67. // Identical blocks.
  68. return false;
  69. }
  70. };
  71. } // anon namespace
  72. enum DisconnectResult
  73. {
  74. DISCONNECT_OK, // All good.
  75. DISCONNECT_UNCLEAN, // Rolled back, but UTXO set was inconsistent with block.
  76. DISCONNECT_FAILED // Something else went wrong.
  77. };
  78. class ConnectTrace;
  79. /**
  80. * CChainState stores and provides an API to update our local knowledge of the
  81. * current best chain and header tree.
  82. *
  83. * It generally provides access to the current block tree, as well as functions
  84. * to provide new data, which it will appropriately validate and incorporate in
  85. * its state as necessary.
  86. *
  87. * Eventually, the API here is targeted at being exposed externally as a
  88. * consumable libconsensus library, so any functions added must only call
  89. * other class member functions, pure functions in other parts of the consensus
  90. * library, callbacks via the validation interface, or read/write-to-disk
  91. * functions (eventually this will also be via callbacks).
  92. */
  93. class CChainState {
  94. private:
  95. /**
  96. * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
  97. * as good as our current tip or better. Entries may be failed, though, and pruning nodes may be
  98. * missing the data for the block.
  99. */
  100. std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
  101. /**
  102. * Every received block is assigned a unique and increasing identifier, so we
  103. * know which one to give priority in case of a fork.
  104. */
  105. CCriticalSection cs_nBlockSequenceId;
  106. /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
  107. int32_t nBlockSequenceId = 1;
  108. /** Decreasing counter (used by subsequent preciousblock calls). */
  109. int32_t nBlockReverseSequenceId = -1;
  110. /** chainwork for the last block that preciousblock has been applied to. */
  111. arith_uint256 nLastPreciousChainwork = 0;
  112. /** In order to efficiently track invalidity of headers, we keep the set of
  113. * blocks which we tried to connect and found to be invalid here (ie which
  114. * were set to BLOCK_FAILED_VALID since the last restart). We can then
  115. * walk this set and check if a new header is a descendant of something in
  116. * this set, preventing us from having to walk mapBlockIndex when we try
  117. * to connect a bad block and fail.
  118. *
  119. * While this is more complicated than marking everything which descends
  120. * from an invalid block as invalid at the time we discover it to be
  121. * invalid, doing so would require walking all of mapBlockIndex to find all
  122. * descendants. Since this case should be very rare, keeping track of all
  123. * BLOCK_FAILED_VALID blocks in a set should be just fine and work just as
  124. * well.
  125. *
  126. * Because we already walk mapBlockIndex in height-order at startup, we go
  127. * ahead and mark descendants of invalid blocks as FAILED_CHILD at that time,
  128. * instead of putting things in this set.
  129. */
  130. std::set<CBlockIndex*> g_failed_blocks;
  131. /**
  132. * the ChainState CriticalSection
  133. * A lock that must be held when modifying this ChainState - held in ActivateBestChain()
  134. */
  135. CCriticalSection m_cs_chainstate;
  136. public:
  137. CChain chainActive;
  138. BlockMap mapBlockIndex;
  139. std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
  140. CBlockIndex *pindexBestInvalid = nullptr;
  141. bool LoadBlockIndex(const Consensus::Params& consensus_params, CBlockTreeDB& blocktree);
  142. bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock);
  143. bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex);
  144. bool AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock);
  145. // Block (dis)connection on a given view:
  146. DisconnectResult DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view);
  147. bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
  148. CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck = false);
  149. // Block disconnection on our pcoinsTip:
  150. bool DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool);
  151. // Manual block validity manipulation:
  152. bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex);
  153. bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex);
  154. bool ResetBlockFailureFlags(CBlockIndex *pindex);
  155. bool ReplayBlocks(const CChainParams& params, CCoinsView* view);
  156. bool RewindBlockIndex(const CChainParams& params);
  157. bool LoadGenesisBlock(const CChainParams& chainparams);
  158. void PruneBlockIndexCandidates();
  159. void UnloadBlockIndex();
  160. private:
  161. bool ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace);
  162. bool ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool);
  163. CBlockIndex* AddToBlockIndex(const CBlockHeader& block);
  164. /** Create a new block index entry for a given block hash */
  165. CBlockIndex * InsertBlockIndex(const uint256& hash);
  166. void CheckBlockIndex(const Consensus::Params& consensusParams);
  167. void InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state);
  168. CBlockIndex* FindMostWorkChain();
  169. bool ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams);
  170. bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params);
  171. } g_chainstate;
  172. CCriticalSection cs_main;
  173. BlockMap& mapBlockIndex = g_chainstate.mapBlockIndex;
  174. CChain& chainActive = g_chainstate.chainActive;
  175. CBlockIndex *pindexBestHeader = nullptr;
  176. CWaitableCriticalSection csBestBlock;
  177. CConditionVariable cvBlockChange;
  178. int nScriptCheckThreads = 0;
  179. std::atomic_bool fImporting(false);
  180. std::atomic_bool fReindex(false);
  181. bool fTxIndex = false;
  182. bool fHavePruned = false;
  183. bool fPruneMode = false;
  184. bool fIsBareMultisigStd = DEFAULT_PERMIT_BAREMULTISIG;
  185. bool fRequireStandard = true;
  186. bool fCheckBlockIndex = false;
  187. bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED;
  188. size_t nCoinCacheUsage = 5000 * 300;
  189. uint64_t nPruneTarget = 0;
  190. int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE;
  191. bool fEnableReplacement = DEFAULT_ENABLE_REPLACEMENT;
  192. uint256 hashAssumeValid;
  193. arith_uint256 nMinimumChainWork;
  194. CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE);
  195. CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
  196. CBlockPolicyEstimator feeEstimator;
  197. CTxMemPool mempool(&feeEstimator);
  198. /** Constant stuff for coinbase transactions we create: */
  199. CScript COINBASE_FLAGS;
  200. const std::string strMessageMagic = "Bitcoin Signed Message:\n";
  201. // Internal stuff
  202. namespace {
  203. CBlockIndex *&pindexBestInvalid = g_chainstate.pindexBestInvalid;
  204. /** All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
  205. * Pruned nodes may have entries where B is missing data.
  206. */
  207. std::multimap<CBlockIndex*, CBlockIndex*>& mapBlocksUnlinked = g_chainstate.mapBlocksUnlinked;
  208. CCriticalSection cs_LastBlockFile;
  209. std::vector<CBlockFileInfo> vinfoBlockFile;
  210. int nLastBlockFile = 0;
  211. /** Global flag to indicate we should check to see if there are
  212. * block/undo files that should be deleted. Set on startup
  213. * or if we allocate more file space when we're in prune mode
  214. */
  215. bool fCheckForPruning = false;
  216. /** Dirty block index entries. */
  217. std::set<CBlockIndex*> setDirtyBlockIndex;
  218. /** Dirty block file entries. */
  219. std::set<int> setDirtyFileInfo;
  220. } // anon namespace
  221. CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
  222. {
  223. // Find the first block the caller has in the main chain
  224. for (const uint256& hash : locator.vHave) {
  225. BlockMap::iterator mi = mapBlockIndex.find(hash);
  226. if (mi != mapBlockIndex.end())
  227. {
  228. CBlockIndex* pindex = (*mi).second;
  229. if (chain.Contains(pindex))
  230. return pindex;
  231. if (pindex->GetAncestor(chain.Height()) == chain.Tip()) {
  232. return chain.Tip();
  233. }
  234. }
  235. }
  236. return chain.Genesis();
  237. }
  238. std::unique_ptr<CCoinsViewDB> pcoinsdbview;
  239. std::unique_ptr<CCoinsViewCache> pcoinsTip;
  240. std::unique_ptr<CBlockTreeDB> pblocktree;
  241. enum FlushStateMode {
  242. FLUSH_STATE_NONE,
  243. FLUSH_STATE_IF_NEEDED,
  244. FLUSH_STATE_PERIODIC,
  245. FLUSH_STATE_ALWAYS
  246. };
  247. // See definition for documentation
  248. static bool FlushStateToDisk(const CChainParams& chainParams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight=0);
  249. static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight);
  250. static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight);
  251. bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks = nullptr);
  252. static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  253. bool CheckFinalTx(const CTransaction &tx, int flags)
  254. {
  255. AssertLockHeld(cs_main);
  256. // By convention a negative value for flags indicates that the
  257. // current network-enforced consensus rules should be used. In
  258. // a future soft-fork scenario that would mean checking which
  259. // rules would be enforced for the next block and setting the
  260. // appropriate flags. At the present time no soft-forks are
  261. // scheduled, so no flags are set.
  262. flags = std::max(flags, 0);
  263. // CheckFinalTx() uses chainActive.Height()+1 to evaluate
  264. // nLockTime because when IsFinalTx() is called within
  265. // CBlock::AcceptBlock(), the height of the block *being*
  266. // evaluated is what is used. Thus if we want to know if a
  267. // transaction can be part of the *next* block, we need to call
  268. // IsFinalTx() with one more than chainActive.Height().
  269. const int nBlockHeight = chainActive.Height() + 1;
  270. // BIP113 requires that time-locked transactions have nLockTime set to
  271. // less than the median time of the previous block they're contained in.
  272. // When the next block is created its previous block will be the current
  273. // chain tip, so we use that to calculate the median time passed to
  274. // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
  275. const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST)
  276. ? chainActive.Tip()->GetMedianTimePast()
  277. : GetAdjustedTime();
  278. return IsFinalTx(tx, nBlockHeight, nBlockTime);
  279. }
  280. bool TestLockPointValidity(const LockPoints* lp)
  281. {
  282. AssertLockHeld(cs_main);
  283. assert(lp);
  284. // If there are relative lock times then the maxInputBlock will be set
  285. // If there are no relative lock times, the LockPoints don't depend on the chain
  286. if (lp->maxInputBlock) {
  287. // Check whether chainActive is an extension of the block at which the LockPoints
  288. // calculation was valid. If not LockPoints are no longer valid
  289. if (!chainActive.Contains(lp->maxInputBlock)) {
  290. return false;
  291. }
  292. }
  293. // LockPoints still valid
  294. return true;
  295. }
  296. bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
  297. {
  298. AssertLockHeld(cs_main);
  299. AssertLockHeld(mempool.cs);
  300. CBlockIndex* tip = chainActive.Tip();
  301. assert(tip != nullptr);
  302. CBlockIndex index;
  303. index.pprev = tip;
  304. // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
  305. // height based locks because when SequenceLocks() is called within
  306. // ConnectBlock(), the height of the block *being*
  307. // evaluated is what is used.
  308. // Thus if we want to know if a transaction can be part of the
  309. // *next* block, we need to use one more than chainActive.Height()
  310. index.nHeight = tip->nHeight + 1;
  311. std::pair<int, int64_t> lockPair;
  312. if (useExistingLockPoints) {
  313. assert(lp);
  314. lockPair.first = lp->height;
  315. lockPair.second = lp->time;
  316. }
  317. else {
  318. // pcoinsTip contains the UTXO set for chainActive.Tip()
  319. CCoinsViewMemPool viewMemPool(pcoinsTip.get(), mempool);
  320. std::vector<int> prevheights;
  321. prevheights.resize(tx.vin.size());
  322. for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
  323. const CTxIn& txin = tx.vin[txinIndex];
  324. Coin coin;
  325. if (!viewMemPool.GetCoin(txin.prevout, coin)) {
  326. return error("%s: Missing input", __func__);
  327. }
  328. if (coin.nHeight == MEMPOOL_HEIGHT) {
  329. // Assume all mempool transaction confirm in the next block
  330. prevheights[txinIndex] = tip->nHeight + 1;
  331. } else {
  332. prevheights[txinIndex] = coin.nHeight;
  333. }
  334. }
  335. lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
  336. if (lp) {
  337. lp->height = lockPair.first;
  338. lp->time = lockPair.second;
  339. // Also store the hash of the block with the highest height of
  340. // all the blocks which have sequence locked prevouts.
  341. // This hash needs to still be on the chain
  342. // for these LockPoint calculations to be valid
  343. // Note: It is impossible to correctly calculate a maxInputBlock
  344. // if any of the sequence locked inputs depend on unconfirmed txs,
  345. // except in the special case where the relative lock time/height
  346. // is 0, which is equivalent to no sequence lock. Since we assume
  347. // input height of tip+1 for mempool txs and test the resulting
  348. // lockPair from CalculateSequenceLocks against tip+1. We know
  349. // EvaluateSequenceLocks will fail if there was a non-zero sequence
  350. // lock on a mempool input, so we can use the return value of
  351. // CheckSequenceLocks to indicate the LockPoints validity
  352. int maxInputHeight = 0;
  353. for (int height : prevheights) {
  354. // Can ignore mempool inputs since we'll fail if they had non-zero locks
  355. if (height != tip->nHeight+1) {
  356. maxInputHeight = std::max(maxInputHeight, height);
  357. }
  358. }
  359. lp->maxInputBlock = tip->GetAncestor(maxInputHeight);
  360. }
  361. }
  362. return EvaluateSequenceLocks(index, lockPair);
  363. }
  364. // Returns the script flags which should be checked for a given block
  365. static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams);
  366. static void LimitMempoolSize(CTxMemPool& pool, size_t limit, unsigned long age) {
  367. int expired = pool.Expire(GetTime() - age);
  368. if (expired != 0) {
  369. LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired);
  370. }
  371. std::vector<COutPoint> vNoSpendsRemaining;
  372. pool.TrimToSize(limit, &vNoSpendsRemaining);
  373. for (const COutPoint& removed : vNoSpendsRemaining)
  374. pcoinsTip->Uncache(removed);
  375. }
  376. /** Convert CValidationState to a human-readable message for logging */
  377. std::string FormatStateMessage(const CValidationState &state)
  378. {
  379. return strprintf("%s%s (code %i)",
  380. state.GetRejectReason(),
  381. state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage(),
  382. state.GetRejectCode());
  383. }
  384. static bool IsCurrentForFeeEstimation()
  385. {
  386. AssertLockHeld(cs_main);
  387. if (IsInitialBlockDownload())
  388. return false;
  389. if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE))
  390. return false;
  391. if (chainActive.Height() < pindexBestHeader->nHeight - 1)
  392. return false;
  393. return true;
  394. }
  395. /* Make mempool consistent after a reorg, by re-adding or recursively erasing
  396. * disconnected block transactions from the mempool, and also removing any
  397. * other transactions from the mempool that are no longer valid given the new
  398. * tip/height.
  399. *
  400. * Note: we assume that disconnectpool only contains transactions that are NOT
  401. * confirmed in the current chain nor already in the mempool (otherwise,
  402. * in-mempool descendants of such transactions would be removed).
  403. *
  404. * Passing fAddToMempool=false will skip trying to add the transactions back,
  405. * and instead just erase from the mempool as needed.
  406. */
  407. void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, bool fAddToMempool)
  408. {
  409. AssertLockHeld(cs_main);
  410. std::vector<uint256> vHashUpdate;
  411. // disconnectpool's insertion_order index sorts the entries from
  412. // oldest to newest, but the oldest entry will be the last tx from the
  413. // latest mined block that was disconnected.
  414. // Iterate disconnectpool in reverse, so that we add transactions
  415. // back to the mempool starting with the earliest transaction that had
  416. // been previously seen in a block.
  417. auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin();
  418. while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) {
  419. // ignore validation errors in resurrected transactions
  420. CValidationState stateDummy;
  421. if (!fAddToMempool || (*it)->IsCoinBase() ||
  422. !AcceptToMemoryPool(mempool, stateDummy, *it, nullptr /* pfMissingInputs */,
  423. nullptr /* plTxnReplaced */, true /* bypass_limits */, 0 /* nAbsurdFee */)) {
  424. // If the transaction doesn't make it in to the mempool, remove any
  425. // transactions that depend on it (which would now be orphans).
  426. mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
  427. } else if (mempool.exists((*it)->GetHash())) {
  428. vHashUpdate.push_back((*it)->GetHash());
  429. }
  430. ++it;
  431. }
  432. disconnectpool.queuedTx.clear();
  433. // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have
  434. // no in-mempool children, which is generally not true when adding
  435. // previously-confirmed transactions back to the mempool.
  436. // UpdateTransactionsFromBlock finds descendants of any transactions in
  437. // the disconnectpool that were added back and cleans up the mempool state.
  438. mempool.UpdateTransactionsFromBlock(vHashUpdate);
  439. // We also need to remove any now-immature transactions
  440. mempool.removeForReorg(pcoinsTip.get(), chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS);
  441. // Re-limit mempool size, in case we added any transactions
  442. LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
  443. }
  444. // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool
  445. // were somehow broken and returning the wrong scriptPubKeys
  446. static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &view, CTxMemPool& pool,
  447. unsigned int flags, bool cacheSigStore, PrecomputedTransactionData& txdata) {
  448. AssertLockHeld(cs_main);
  449. // pool.cs should be locked already, but go ahead and re-take the lock here
  450. // to enforce that mempool doesn't change between when we check the view
  451. // and when we actually call through to CheckInputs
  452. LOCK(pool.cs);
  453. assert(!tx.IsCoinBase());
  454. for (const CTxIn& txin : tx.vin) {
  455. const Coin& coin = view.AccessCoin(txin.prevout);
  456. // At this point we haven't actually checked if the coins are all
  457. // available (or shouldn't assume we have, since CheckInputs does).
  458. // So we just return failure if the inputs are not available here,
  459. // and then only have to check equivalence for available inputs.
  460. if (coin.IsSpent()) return false;
  461. const CTransactionRef& txFrom = pool.get(txin.prevout.hash);
  462. if (txFrom) {
  463. assert(txFrom->GetHash() == txin.prevout.hash);
  464. assert(txFrom->vout.size() > txin.prevout.n);
  465. assert(txFrom->vout[txin.prevout.n] == coin.out);
  466. } else {
  467. const Coin& coinFromDisk = pcoinsTip->AccessCoin(txin.prevout);
  468. assert(!coinFromDisk.IsSpent());
  469. assert(coinFromDisk.out == coin.out);
  470. }
  471. }
  472. return CheckInputs(tx, state, view, true, flags, cacheSigStore, true, txdata);
  473. }
  474. static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx,
  475. bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
  476. bool bypass_limits, const CAmount& nAbsurdFee, std::vector<COutPoint>& coins_to_uncache)
  477. {
  478. const CTransaction& tx = *ptx;
  479. const uint256 hash = tx.GetHash();
  480. AssertLockHeld(cs_main);
  481. LOCK(pool.cs); // mempool "read lock" (held through GetMainSignals().TransactionAddedToMempool())
  482. if (pfMissingInputs) {
  483. *pfMissingInputs = false;
  484. }
  485. if (!CheckTransaction(tx, state))
  486. return false; // state filled in by CheckTransaction
  487. // Coinbase is only valid in a block, not as a loose transaction
  488. if (tx.IsCoinBase())
  489. return state.DoS(100, false, REJECT_INVALID, "coinbase");
  490. // Reject transactions with witness before segregated witness activates (override with -prematurewitness)
  491. bool witnessEnabled = IsWitnessEnabled(chainActive.Tip(), chainparams.GetConsensus());
  492. if (!gArgs.GetBoolArg("-prematurewitness", false) && tx.HasWitness() && !witnessEnabled) {
  493. return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
  494. }
  495. // Rather not work on nonstandard transactions (unless -testnet/-regtest)
  496. std::string reason;
  497. if (fRequireStandard && !IsStandardTx(tx, reason, witnessEnabled))
  498. return state.DoS(0, false, REJECT_NONSTANDARD, reason);
  499. // Only accept nLockTime-using transactions that can be mined in the next
  500. // block; we don't want our mempool filled up with transactions that can't
  501. // be mined yet.
  502. if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS))
  503. return state.DoS(0, false, REJECT_NONSTANDARD, "non-final");
  504. // is it already in the memory pool?
  505. if (pool.exists(hash)) {
  506. return state.Invalid(false, REJECT_DUPLICATE, "txn-already-in-mempool");
  507. }
  508. // Check for conflicts with in-memory transactions
  509. std::set<uint256> setConflicts;
  510. for (const CTxIn &txin : tx.vin)
  511. {
  512. auto itConflicting = pool.mapNextTx.find(txin.prevout);
  513. if (itConflicting != pool.mapNextTx.end())
  514. {
  515. const CTransaction *ptxConflicting = itConflicting->second;
  516. if (!setConflicts.count(ptxConflicting->GetHash()))
  517. {
  518. // Allow opt-out of transaction replacement by setting
  519. // nSequence > MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs.
  520. //
  521. // SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by
  522. // non-replaceable transactions. All inputs rather than just one
  523. // is for the sake of multi-party protocols, where we don't
  524. // want a single party to be able to disable replacement.
  525. //
  526. // The opt-out ignores descendants as anyone relying on
  527. // first-seen mempool behavior should be checking all
  528. // unconfirmed ancestors anyway; doing otherwise is hopelessly
  529. // insecure.
  530. bool fReplacementOptOut = true;
  531. if (fEnableReplacement)
  532. {
  533. for (const CTxIn &_txin : ptxConflicting->vin)
  534. {
  535. if (_txin.nSequence <= MAX_BIP125_RBF_SEQUENCE)
  536. {
  537. fReplacementOptOut = false;
  538. break;
  539. }
  540. }
  541. }
  542. if (fReplacementOptOut) {
  543. return state.Invalid(false, REJECT_DUPLICATE, "txn-mempool-conflict");
  544. }
  545. setConflicts.insert(ptxConflicting->GetHash());
  546. }
  547. }
  548. }
  549. {
  550. CCoinsView dummy;
  551. CCoinsViewCache view(&dummy);
  552. LockPoints lp;
  553. CCoinsViewMemPool viewMemPool(pcoinsTip.get(), pool);
  554. view.SetBackend(viewMemPool);
  555. // do all inputs exist?
  556. for (const CTxIn txin : tx.vin) {
  557. if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
  558. coins_to_uncache.push_back(txin.prevout);
  559. }
  560. if (!view.HaveCoin(txin.prevout)) {
  561. // Are inputs missing because we already have the tx?
  562. for (size_t out = 0; out < tx.vout.size(); out++) {
  563. // Optimistically just do efficient check of cache for outputs
  564. if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
  565. return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
  566. }
  567. }
  568. // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
  569. if (pfMissingInputs) {
  570. *pfMissingInputs = true;
  571. }
  572. return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
  573. }
  574. }
  575. // Bring the best block into scope
  576. view.GetBestBlock();
  577. // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
  578. view.SetBackend(dummy);
  579. // Only accept BIP68 sequence locked transactions that can be mined in the next
  580. // block; we don't want our mempool filled up with transactions that can't
  581. // be mined yet.
  582. // Must keep pool.cs for this unless we change CheckSequenceLocks to take a
  583. // CoinsViewCache instead of create its own
  584. if (!CheckSequenceLocks(tx, STANDARD_LOCKTIME_VERIFY_FLAGS, &lp))
  585. return state.DoS(0, false, REJECT_NONSTANDARD, "non-BIP68-final");
  586. CAmount nFees = 0;
  587. if (!Consensus::CheckTxInputs(tx, state, view, GetSpendHeight(view), nFees)) {
  588. return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
  589. }
  590. // Check for non-standard pay-to-script-hash in inputs
  591. if (fRequireStandard && !AreInputsStandard(tx, view))
  592. return state.Invalid(false, REJECT_NONSTANDARD, "bad-txns-nonstandard-inputs");
  593. // Check for non-standard witness in P2WSH
  594. if (tx.HasWitness() && fRequireStandard && !IsWitnessStandard(tx, view))
  595. return state.DoS(0, false, REJECT_NONSTANDARD, "bad-witness-nonstandard", true);
  596. int64_t nSigOpsCost = GetTransactionSigOpCost(tx, view, STANDARD_SCRIPT_VERIFY_FLAGS);
  597. // nModifiedFees includes any fee deltas from PrioritiseTransaction
  598. CAmount nModifiedFees = nFees;
  599. pool.ApplyDelta(hash, nModifiedFees);
  600. // Keep track of transactions that spend a coinbase, which we re-scan
  601. // during reorgs to ensure COINBASE_MATURITY is still met.
  602. bool fSpendsCoinbase = false;
  603. for (const CTxIn &txin : tx.vin) {
  604. const Coin &coin = view.AccessCoin(txin.prevout);
  605. if (coin.IsCoinBase()) {
  606. fSpendsCoinbase = true;
  607. break;
  608. }
  609. }
  610. CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(),
  611. fSpendsCoinbase, nSigOpsCost, lp);
  612. unsigned int nSize = entry.GetTxSize();
  613. // Check that the transaction doesn't have an excessive number of
  614. // sigops, making it impossible to mine. Since the coinbase transaction
  615. // itself can contain sigops MAX_STANDARD_TX_SIGOPS is less than
  616. // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
  617. // merely non-standard transaction.
  618. if (nSigOpsCost > MAX_STANDARD_TX_SIGOPS_COST)
  619. return state.DoS(0, false, REJECT_NONSTANDARD, "bad-txns-too-many-sigops", false,
  620. strprintf("%d", nSigOpsCost));
  621. CAmount mempoolRejectFee = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000).GetFee(nSize);
  622. if (!bypass_limits && mempoolRejectFee > 0 && nModifiedFees < mempoolRejectFee) {
  623. return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool min fee not met", false, strprintf("%d < %d", nFees, mempoolRejectFee));
  624. }
  625. // No transactions are allowed below minRelayTxFee except from disconnected blocks
  626. if (!bypass_limits && nModifiedFees < ::minRelayTxFee.GetFee(nSize)) {
  627. return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "min relay fee not met");
  628. }
  629. if (nAbsurdFee && nFees > nAbsurdFee)
  630. return state.Invalid(false,
  631. REJECT_HIGHFEE, "absurdly-high-fee",
  632. strprintf("%d > %d", nFees, nAbsurdFee));
  633. // Calculate in-mempool ancestors, up to a limit.
  634. CTxMemPool::setEntries setAncestors;
  635. size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
  636. size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
  637. size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
  638. size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
  639. std::string errString;
  640. if (!pool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
  641. return state.DoS(0, false, REJECT_NONSTANDARD, "too-long-mempool-chain", false, errString);
  642. }
  643. // A transaction that spends outputs that would be replaced by it is invalid. Now
  644. // that we have the set of all ancestors we can detect this
  645. // pathological case by making sure setConflicts and setAncestors don't
  646. // intersect.
  647. for (CTxMemPool::txiter ancestorIt : setAncestors)
  648. {
  649. const uint256 &hashAncestor = ancestorIt->GetTx().GetHash();
  650. if (setConflicts.count(hashAncestor))
  651. {
  652. return state.DoS(10, false,
  653. REJECT_INVALID, "bad-txns-spends-conflicting-tx", false,
  654. strprintf("%s spends conflicting transaction %s",
  655. hash.ToString(),
  656. hashAncestor.ToString()));
  657. }
  658. }
  659. // Check if it's economically rational to mine this transaction rather
  660. // than the ones it replaces.
  661. CAmount nConflictingFees = 0;
  662. size_t nConflictingSize = 0;
  663. uint64_t nConflictingCount = 0;
  664. CTxMemPool::setEntries allConflicting;
  665. // If we don't hold the lock allConflicting might be incomplete; the
  666. // subsequent RemoveStaged() and addUnchecked() calls don't guarantee
  667. // mempool consistency for us.
  668. const bool fReplacementTransaction = setConflicts.size();
  669. if (fReplacementTransaction)
  670. {
  671. CFeeRate newFeeRate(nModifiedFees, nSize);
  672. std::set<uint256> setConflictsParents;
  673. const int maxDescendantsToVisit = 100;
  674. CTxMemPool::setEntries setIterConflicting;
  675. for (const uint256 &hashConflicting : setConflicts)
  676. {
  677. CTxMemPool::txiter mi = pool.mapTx.find(hashConflicting);
  678. if (mi == pool.mapTx.end())
  679. continue;
  680. // Save these to avoid repeated lookups
  681. setIterConflicting.insert(mi);
  682. // Don't allow the replacement to reduce the feerate of the
  683. // mempool.
  684. //
  685. // We usually don't want to accept replacements with lower
  686. // feerates than what they replaced as that would lower the
  687. // feerate of the next block. Requiring that the feerate always
  688. // be increased is also an easy-to-reason about way to prevent
  689. // DoS attacks via replacements.
  690. //
  691. // The mining code doesn't (currently) take children into
  692. // account (CPFP) so we only consider the feerates of
  693. // transactions being directly replaced, not their indirect
  694. // descendants. While that does mean high feerate children are
  695. // ignored when deciding whether or not to replace, we do
  696. // require the replacement to pay more overall fees too,
  697. // mitigating most cases.
  698. CFeeRate oldFeeRate(mi->GetModifiedFee(), mi->GetTxSize());
  699. if (newFeeRate <= oldFeeRate)
  700. {
  701. return state.DoS(0, false,
  702. REJECT_INSUFFICIENTFEE, "insufficient fee", false,
  703. strprintf("rejecting replacement %s; new feerate %s <= old feerate %s",
  704. hash.ToString(),
  705. newFeeRate.ToString(),
  706. oldFeeRate.ToString()));
  707. }
  708. for (const CTxIn &txin : mi->GetTx().vin)
  709. {
  710. setConflictsParents.insert(txin.prevout.hash);
  711. }
  712. nConflictingCount += mi->GetCountWithDescendants();
  713. }
  714. // This potentially overestimates the number of actual descendants
  715. // but we just want to be conservative to avoid doing too much
  716. // work.
  717. if (nConflictingCount <= maxDescendantsToVisit) {
  718. // If not too many to replace, then calculate the set of
  719. // transactions that would have to be evicted
  720. for (CTxMemPool::txiter it : setIterConflicting) {
  721. pool.CalculateDescendants(it, allConflicting);
  722. }
  723. for (CTxMemPool::txiter it : allConflicting) {
  724. nConflictingFees += it->GetModifiedFee();
  725. nConflictingSize += it->GetTxSize();
  726. }
  727. } else {
  728. return state.DoS(0, false,
  729. REJECT_NONSTANDARD, "too many potential replacements", false,
  730. strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n",
  731. hash.ToString(),
  732. nConflictingCount,
  733. maxDescendantsToVisit));
  734. }
  735. for (unsigned int j = 0; j < tx.vin.size(); j++)
  736. {
  737. // We don't want to accept replacements that require low
  738. // feerate junk to be mined first. Ideally we'd keep track of
  739. // the ancestor feerates and make the decision based on that,
  740. // but for now requiring all new inputs to be confirmed works.
  741. if (!setConflictsParents.count(tx.vin[j].prevout.hash))
  742. {
  743. // Rather than check the UTXO set - potentially expensive -
  744. // it's cheaper to just check if the new input refers to a
  745. // tx that's in the mempool.
  746. if (pool.mapTx.find(tx.vin[j].prevout.hash) != pool.mapTx.end())
  747. return state.DoS(0, false,
  748. REJECT_NONSTANDARD, "replacement-adds-unconfirmed", false,
  749. strprintf("replacement %s adds unconfirmed input, idx %d",
  750. hash.ToString(), j));
  751. }
  752. }
  753. // The replacement must pay greater fees than the transactions it
  754. // replaces - if we did the bandwidth used by those conflicting
  755. // transactions would not be paid for.
  756. if (nModifiedFees < nConflictingFees)
  757. {
  758. return state.DoS(0, false,
  759. REJECT_INSUFFICIENTFEE, "insufficient fee", false,
  760. strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s",
  761. hash.ToString(), FormatMoney(nModifiedFees), FormatMoney(nConflictingFees)));
  762. }
  763. // Finally in addition to paying more fees than the conflicts the
  764. // new transaction must pay for its own bandwidth.
  765. CAmount nDeltaFees = nModifiedFees - nConflictingFees;
  766. if (nDeltaFees < ::incrementalRelayFee.GetFee(nSize))
  767. {
  768. return state.DoS(0, false,
  769. REJECT_INSUFFICIENTFEE, "insufficient fee", false,
  770. strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s",
  771. hash.ToString(),
  772. FormatMoney(nDeltaFees),
  773. FormatMoney(::incrementalRelayFee.GetFee(nSize))));
  774. }
  775. }
  776. unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
  777. if (!chainparams.RequireStandard()) {
  778. scriptVerifyFlags = gArgs.GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
  779. }
  780. // Check against previous transactions
  781. // This is done last to help prevent CPU exhaustion denial-of-service attacks.
  782. PrecomputedTransactionData txdata(tx);
  783. if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, txdata)) {
  784. // SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
  785. // need to turn both off, and compare against just turning off CLEANSTACK
  786. // to see if the failure is specifically due to witness validation.
  787. CValidationState stateDummy; // Want reported failures to be from first CheckInputs
  788. if (!tx.HasWitness() && CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true, false, txdata) &&
  789. !CheckInputs(tx, stateDummy, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true, false, txdata)) {
  790. // Only the witness is missing, so the transaction itself may be fine.
  791. state.SetCorruptionPossible();
  792. }
  793. return false; // state filled in by CheckInputs
  794. }
  795. // Check again against the current block tip's script verification
  796. // flags to cache our script execution flags. This is, of course,
  797. // useless if the next block has different script flags from the
  798. // previous one, but because the cache tracks script flags for us it
  799. // will auto-invalidate and we'll just have a few blocks of extra
  800. // misses on soft-fork activation.
  801. //
  802. // This is also useful in case of bugs in the standard flags that cause
  803. // transactions to pass as valid when they're actually invalid. For
  804. // instance the STRICTENC flag was incorrectly allowing certain
  805. // CHECKSIG NOT scripts to pass, even though they were invalid.
  806. //
  807. // There is a similar check in CreateNewBlock() to prevent creating
  808. // invalid blocks (using TestBlockValidity), however allowing such
  809. // transactions into the mempool can be exploited as a DoS attack.
  810. unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), Params().GetConsensus());
  811. if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata))
  812. {
  813. // If we're using promiscuousmempoolflags, we may hit this normally
  814. // Check if current block has some flags that scriptVerifyFlags
  815. // does not before printing an ominous warning
  816. if (!(~scriptVerifyFlags & currentBlockScriptVerifyFlags)) {
  817. return error("%s: BUG! PLEASE REPORT THIS! ConnectInputs failed against latest-block but not STANDARD flags %s, %s",
  818. __func__, hash.ToString(), FormatStateMessage(state));
  819. } else {
  820. if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true, false, txdata)) {
  821. return error("%s: ConnectInputs failed against MANDATORY but not STANDARD flags due to promiscuous mempool %s, %s",
  822. __func__, hash.ToString(), FormatStateMessage(state));
  823. } else {
  824. LogPrintf("Warning: -promiscuousmempool flags set to not include currently enforced soft forks, this may break mining or otherwise cause instability!\n");
  825. }
  826. }
  827. }
  828. // Remove conflicting transactions from the mempool
  829. for (const CTxMemPool::txiter it : allConflicting)
  830. {
  831. LogPrint(BCLog::MEMPOOL, "replacing tx %s with %s for %s BTC additional fees, %d delta bytes\n",
  832. it->GetTx().GetHash().ToString(),
  833. hash.ToString(),
  834. FormatMoney(nModifiedFees - nConflictingFees),
  835. (int)nSize - (int)nConflictingSize);
  836. if (plTxnReplaced)
  837. plTxnReplaced->push_back(it->GetSharedTx());
  838. }
  839. pool.RemoveStaged(allConflicting, false, MemPoolRemovalReason::REPLACED);
  840. // This transaction should only count for fee estimation if:
  841. // - it isn't a BIP 125 replacement transaction (may not be widely supported)
  842. // - it's not being readded during a reorg which bypasses typical mempool fee limits
  843. // - the node is not behind
  844. // - the transaction is not dependent on any other transactions in the mempool
  845. bool validForFeeEstimation = !fReplacementTransaction && !bypass_limits && IsCurrentForFeeEstimation() && pool.HasNoInputsOf(tx);
  846. // Store transaction in memory
  847. pool.addUnchecked(hash, entry, setAncestors, validForFeeEstimation);
  848. // trim mempool and check if tx was trimmed
  849. if (!bypass_limits) {
  850. LimitMempoolSize(pool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60);
  851. if (!pool.exists(hash))
  852. return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "mempool full");
  853. }
  854. }
  855. GetMainSignals().TransactionAddedToMempool(ptx);
  856. return true;
  857. }
  858. /** (try to) add transaction to memory pool with a specified acceptance time **/
  859. static bool AcceptToMemoryPoolWithTime(const CChainParams& chainparams, CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
  860. bool* pfMissingInputs, int64_t nAcceptTime, std::list<CTransactionRef>* plTxnReplaced,
  861. bool bypass_limits, const CAmount nAbsurdFee)
  862. {
  863. std::vector<COutPoint> coins_to_uncache;
  864. bool res = AcceptToMemoryPoolWorker(chainparams, pool, state, tx, pfMissingInputs, nAcceptTime, plTxnReplaced, bypass_limits, nAbsurdFee, coins_to_uncache);
  865. if (!res) {
  866. for (const COutPoint& hashTx : coins_to_uncache)
  867. pcoinsTip->Uncache(hashTx);
  868. }
  869. // After we've (potentially) uncached entries, ensure our coins cache is still within its size limits
  870. CValidationState stateDummy;
  871. FlushStateToDisk(chainparams, stateDummy, FLUSH_STATE_PERIODIC);
  872. return res;
  873. }
  874. bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx,
  875. bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced,
  876. bool bypass_limits, const CAmount nAbsurdFee)
  877. {
  878. const CChainParams& chainparams = Params();
  879. return AcceptToMemoryPoolWithTime(chainparams, pool, state, tx, pfMissingInputs, GetTime(), plTxnReplaced, bypass_limits, nAbsurdFee);
  880. }
  881. /**
  882. * Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock.
  883. * If blockIndex is provided, the transaction is fetched from the corresponding block.
  884. */
  885. bool GetTransaction(const uint256& hash, CTransactionRef& txOut, const Consensus::Params& consensusParams, uint256& hashBlock, bool fAllowSlow, CBlockIndex* blockIndex)
  886. {
  887. CBlockIndex* pindexSlow = blockIndex;
  888. LOCK(cs_main);
  889. if (!blockIndex) {
  890. CTransactionRef ptx = mempool.get(hash);
  891. if (ptx) {
  892. txOut = ptx;
  893. return true;
  894. }
  895. if (fTxIndex) {
  896. CDiskTxPos postx;
  897. if (pblocktree->ReadTxIndex(hash, postx)) {
  898. CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
  899. if (file.IsNull())
  900. return error("%s: OpenBlockFile failed", __func__);
  901. CBlockHeader header;
  902. try {
  903. file >> header;
  904. fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
  905. file >> txOut;
  906. } catch (const std::exception& e) {
  907. return error("%s: Deserialize or I/O error - %s", __func__, e.what());
  908. }
  909. hashBlock = header.GetHash();
  910. if (txOut->GetHash() != hash)
  911. return error("%s: txid mismatch", __func__);
  912. return true;
  913. }
  914. // transaction not found in index, nothing more can be done
  915. return false;
  916. }
  917. if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
  918. const Coin& coin = AccessByTxid(*pcoinsTip, hash);
  919. if (!coin.IsSpent()) pindexSlow = chainActive[coin.nHeight];
  920. }
  921. }
  922. if (pindexSlow) {
  923. CBlock block;
  924. if (ReadBlockFromDisk(block, pindexSlow, consensusParams)) {
  925. for (const auto& tx : block.vtx) {
  926. if (tx->GetHash() == hash) {
  927. txOut = tx;
  928. hashBlock = pindexSlow->GetBlockHash();
  929. return true;
  930. }
  931. }
  932. }
  933. }
  934. return false;
  935. }
  936. //////////////////////////////////////////////////////////////////////////////
  937. //
  938. // CBlock and CBlockIndex
  939. //
  940. static bool WriteBlockToDisk(const CBlock& block, CDiskBlockPos& pos, const CMessageHeader::MessageStartChars& messageStart)
  941. {
  942. // Open history file to append
  943. CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
  944. if (fileout.IsNull())
  945. return error("WriteBlockToDisk: OpenBlockFile failed");
  946. // Write index header
  947. unsigned int nSize = GetSerializeSize(fileout, block);
  948. fileout << FLATDATA(messageStart) << nSize;
  949. // Write block
  950. long fileOutPos = ftell(fileout.Get());
  951. if (fileOutPos < 0)
  952. return error("WriteBlockToDisk: ftell failed");
  953. pos.nPos = (unsigned int)fileOutPos;
  954. fileout << block;
  955. return true;
  956. }
  957. bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
  958. {
  959. block.SetNull();
  960. // Open history file to read
  961. CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
  962. if (filein.IsNull())
  963. return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
  964. // Read block
  965. try {
  966. filein >> block;
  967. }
  968. catch (const std::exception& e) {
  969. return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
  970. }
  971. // Check the header
  972. if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
  973. return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
  974. return true;
  975. }
  976. bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
  977. {
  978. CDiskBlockPos blockPos;
  979. {
  980. LOCK(cs_main);
  981. blockPos = pindex->GetBlockPos();
  982. }
  983. if (!ReadBlockFromDisk(block, blockPos, consensusParams))
  984. return false;
  985. if (block.GetHash() != pindex->GetBlockHash())
  986. return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
  987. pindex->ToString(), pindex->GetBlockPos().ToString());
  988. return true;
  989. }
  990. CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
  991. {
  992. int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
  993. // Force block reward to zero when right shift is undefined.
  994. if (halvings >= 64)
  995. return 0;
  996. CAmount nSubsidy = 50 * COIN;
  997. // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
  998. nSubsidy >>= halvings;
  999. return nSubsidy;
  1000. }
  1001. bool IsInitialBlockDownload()
  1002. {
  1003. // Once this function has returned false, it must remain false.
  1004. static std::atomic<bool> latchToFalse{false};
  1005. // Optimization: pre-test latch before taking the lock.
  1006. if (latchToFalse.load(std::memory_order_relaxed))
  1007. return false;
  1008. LOCK(cs_main);
  1009. if (latchToFalse.load(std::memory_order_relaxed))
  1010. return false;
  1011. if (fImporting || fReindex)
  1012. return true;
  1013. if (chainActive.Tip() == nullptr)
  1014. return true;
  1015. if (chainActive.Tip()->nChainWork < nMinimumChainWork)
  1016. return true;
  1017. if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge))
  1018. return true;
  1019. LogPrintf("Leaving InitialBlockDownload (latching to false)\n");
  1020. latchToFalse.store(true, std::memory_order_relaxed);
  1021. return false;
  1022. }
  1023. CBlockIndex *pindexBestForkTip = nullptr, *pindexBestForkBase = nullptr;
  1024. static void AlertNotify(const std::string& strMessage)
  1025. {
  1026. uiInterface.NotifyAlertChanged();
  1027. std::string strCmd = gArgs.GetArg("-alertnotify", "");
  1028. if (strCmd.empty()) return;
  1029. // Alert text should be plain ascii coming from a trusted source, but to
  1030. // be safe we first strip anything not in safeChars, then add single quotes around
  1031. // the whole string before passing it to the shell:
  1032. std::string singleQuote("'");
  1033. std::string safeStatus = SanitizeString(strMessage);
  1034. safeStatus = singleQuote+safeStatus+singleQuote;
  1035. boost::replace_all(strCmd, "%s", safeStatus);
  1036. boost::thread t(runCommand, strCmd); // thread runs free
  1037. }
  1038. static void CheckForkWarningConditions()
  1039. {
  1040. AssertLockHeld(cs_main);
  1041. // Before we get past initial download, we cannot reliably alert about forks
  1042. // (we assume we don't get stuck on a fork before finishing our initial sync)
  1043. if (IsInitialBlockDownload())
  1044. return;
  1045. // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
  1046. // of our head, drop it
  1047. if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
  1048. pindexBestForkTip = nullptr;
  1049. if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6)))
  1050. {
  1051. if (!GetfLargeWorkForkFound() && pindexBestForkBase)
  1052. {
  1053. std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
  1054. pindexBestForkBase->phashBlock->ToString() + std::string("'");
  1055. AlertNotify(warning);
  1056. }
  1057. if (pindexBestForkTip && pindexBestForkBase)
  1058. {
  1059. 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__,
  1060. pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
  1061. pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
  1062. SetfLargeWorkForkFound(true);
  1063. }
  1064. else
  1065. {
  1066. LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__);
  1067. SetfLargeWorkInvalidChainFound(true);
  1068. }
  1069. }
  1070. else
  1071. {
  1072. SetfLargeWorkForkFound(false);
  1073. SetfLargeWorkInvalidChainFound(false);
  1074. }
  1075. }
  1076. static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
  1077. {
  1078. AssertLockHeld(cs_main);
  1079. // If we are on a fork that is sufficiently large, set a warning flag
  1080. CBlockIndex* pfork = pindexNewForkTip;
  1081. CBlockIndex* plonger = chainActive.Tip();
  1082. while (pfork && pfork != plonger)
  1083. {
  1084. while (plonger && plonger->nHeight > pfork->nHeight)
  1085. plonger = plonger->pprev;
  1086. if (pfork == plonger)
  1087. break;
  1088. pfork = pfork->pprev;
  1089. }
  1090. // We define a condition where we should warn the user about as a fork of at least 7 blocks
  1091. // with a tip within 72 blocks (+/- 12 hours if no one mines it) of ours
  1092. // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
  1093. // hash rate operating on the fork.
  1094. // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
  1095. // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
  1096. // the 7-block condition and from this always have the most-likely-to-cause-warning fork
  1097. if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) &&
  1098. pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
  1099. chainActive.Height() - pindexNewForkTip->nHeight < 72)
  1100. {
  1101. pindexBestForkTip = pindexNewForkTip;
  1102. pindexBestForkBase = pfork;
  1103. }
  1104. CheckForkWarningConditions();
  1105. }
  1106. void static InvalidChainFound(CBlockIndex* pindexNew)
  1107. {
  1108. if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
  1109. pindexBestInvalid = pindexNew;
  1110. LogPrintf("%s: invalid block=%s height=%d log2_work=%.8g date=%s\n", __func__,
  1111. pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
  1112. log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
  1113. pindexNew->GetBlockTime()));
  1114. CBlockIndex *tip = chainActive.Tip();
  1115. assert (tip);
  1116. LogPrintf("%s: current best=%s height=%d log2_work=%.8g date=%s\n", __func__,
  1117. tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0),
  1118. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", tip->GetBlockTime()));
  1119. CheckForkWarningConditions();
  1120. }
  1121. void CChainState::InvalidBlockFound(CBlockIndex *pindex, const CValidationState &state) {
  1122. if (!state.CorruptionPossible()) {
  1123. pindex->nStatus |= BLOCK_FAILED_VALID;
  1124. g_failed_blocks.insert(pindex);
  1125. setDirtyBlockIndex.insert(pindex);
  1126. setBlockIndexCandidates.erase(pindex);
  1127. InvalidChainFound(pindex);
  1128. }
  1129. }
  1130. void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight)
  1131. {
  1132. // mark inputs spent
  1133. if (!tx.IsCoinBase()) {
  1134. txundo.vprevout.reserve(tx.vin.size());
  1135. for (const CTxIn &txin : tx.vin) {
  1136. txundo.vprevout.emplace_back();
  1137. bool is_spent = inputs.SpendCoin(txin.prevout, &txundo.vprevout.back());
  1138. assert(is_spent);
  1139. }
  1140. }
  1141. // add outputs
  1142. AddCoins(inputs, tx, nHeight);
  1143. }
  1144. void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight)
  1145. {
  1146. CTxUndo txundo;
  1147. UpdateCoins(tx, inputs, txundo, nHeight);
  1148. }
  1149. bool CScriptCheck::operator()() {
  1150. const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
  1151. const CScriptWitness *witness = &ptxTo->vin[nIn].scriptWitness;
  1152. return VerifyScript(scriptSig, m_tx_out.scriptPubKey, witness, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, m_tx_out.nValue, cacheStore, *txdata), &error);
  1153. }
  1154. int GetSpendHeight(const CCoinsViewCache& inputs)
  1155. {
  1156. LOCK(cs_main);
  1157. CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
  1158. return pindexPrev->nHeight + 1;
  1159. }
  1160. static CuckooCache::cache<uint256, SignatureCacheHasher> scriptExecutionCache;
  1161. static uint256 scriptExecutionCacheNonce(GetRandHash());
  1162. void InitScriptExecutionCache() {
  1163. // nMaxCacheSize is unsigned. If -maxsigcachesize is set to zero,
  1164. // setup_bytes creates the minimum possible cache (2 elements).
  1165. size_t nMaxCacheSize = std::min(std::max((int64_t)0, gArgs.GetArg("-maxsigcachesize", DEFAULT_MAX_SIG_CACHE_SIZE) / 2), MAX_MAX_SIG_CACHE_SIZE) * ((size_t) 1 << 20);
  1166. size_t nElems = scriptExecutionCache.setup_bytes(nMaxCacheSize);
  1167. LogPrintf("Using %zu MiB out of %zu/2 requested for script execution cache, able to store %zu elements\n",
  1168. (nElems*sizeof(uint256)) >>20, (nMaxCacheSize*2)>>20, nElems);
  1169. }
  1170. /**
  1171. * Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
  1172. * This does not modify the UTXO set.
  1173. *
  1174. * If pvChecks is not nullptr, script checks are pushed onto it instead of being performed inline. Any
  1175. * script checks which are not necessary (eg due to script execution cache hits) are, obviously,
  1176. * not pushed onto pvChecks/run.
  1177. *
  1178. * Setting cacheSigStore/cacheFullScriptStore to false will remove elements from the corresponding cache
  1179. * which are matched. This is useful for checking blocks where we will likely never need the cache
  1180. * entry again.
  1181. *
  1182. * Non-static (and re-declared) in src/test/txvalidationcache_tests.cpp
  1183. */
  1184. bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
  1185. {
  1186. if (!tx.IsCoinBase())
  1187. {
  1188. if (pvChecks)
  1189. pvChecks->reserve(tx.vin.size());
  1190. // The first loop above does all the inexpensive checks.
  1191. // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
  1192. // Helps prevent CPU exhaustion attacks.
  1193. // Skip script verification when connecting blocks under the
  1194. // assumevalid block. Assuming the assumevalid block is valid this
  1195. // is safe because block merkle hashes are still computed and checked,
  1196. // Of course, if an assumed valid block is invalid due to false scriptSigs
  1197. // this optimization would allow an invalid chain to be accepted.
  1198. if (fScriptChecks) {
  1199. // First check if script executions have been cached with the same
  1200. // flags. Note that this assumes that the inputs provided are
  1201. // correct (ie that the transaction hash which is in tx's prevouts
  1202. // properly commits to the scriptPubKey in the inputs view of that
  1203. // transaction).
  1204. uint256 hashCacheEntry;
  1205. // We only use the first 19 bytes of nonce to avoid a second SHA
  1206. // round - giving us 19 + 32 + 4 = 55 bytes (+ 8 + 1 = 64)
  1207. static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
  1208. CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
  1209. AssertLockHeld(cs_main); //TODO: Remove this requirement by making CuckooCache not require external locks
  1210. if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
  1211. return true;
  1212. }
  1213. for (unsigned int i = 0; i < tx.vin.size(); i++) {
  1214. const COutPoint &prevout = tx.vin[i].prevout;
  1215. const Coin& coin = inputs.AccessCoin(prevout);
  1216. assert(!coin.IsSpent());
  1217. // We very carefully only pass in things to CScriptCheck which
  1218. // are clearly committed to by tx' witness hash. This provides
  1219. // a sanity check that our caching is not introducing consensus
  1220. // failures through additional data in, eg, the coins being
  1221. // spent being checked as a part of CScriptCheck.
  1222. // Verify signature
  1223. CScriptCheck check(coin.out, tx, i, flags, cacheSigStore, &txdata);
  1224. if (pvChecks) {
  1225. pvChecks->push_back(CScriptCheck());
  1226. check.swap(pvChecks->back());
  1227. } else if (!check()) {
  1228. if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
  1229. // Check whether the failure was caused by a
  1230. // non-mandatory script verification check, such as
  1231. // non-standard DER encodings or non-null dummy
  1232. // arguments; if so, don't trigger DoS protection to
  1233. // avoid splitting the network between upgraded and
  1234. // non-upgraded nodes.
  1235. CScriptCheck check2(coin.out, tx, i,
  1236. flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
  1237. if (check2())
  1238. return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
  1239. }
  1240. // Failures of other flags indicate a transaction that is
  1241. // invalid in new blocks, e.g. an invalid P2SH. We DoS ban
  1242. // such nodes as they are not following the protocol. That
  1243. // said during an upgrade careful thought should be taken
  1244. // as to the correct behavior - we may want to continue
  1245. // peering with non-upgraded nodes even after soft-fork
  1246. // super-majority signaling has occurred.
  1247. return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
  1248. }
  1249. }
  1250. if (cacheFullScriptStore && !pvChecks) {
  1251. // We executed all of the provided scripts, and were told to
  1252. // cache the result. Do so now.
  1253. scriptExecutionCache.insert(hashCacheEntry);
  1254. }
  1255. }
  1256. }
  1257. return true;
  1258. }
  1259. namespace {
  1260. bool UndoWriteToDisk(const CBlockUndo& blockundo, CDiskBlockPos& pos, const uint256& hashBlock, const CMessageHeader::MessageStartChars& messageStart)
  1261. {
  1262. // Open history file to append
  1263. CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
  1264. if (fileout.IsNull())
  1265. return error("%s: OpenUndoFile failed", __func__);
  1266. // Write index header
  1267. unsigned int nSize = GetSerializeSize(fileout, blockundo);
  1268. fileout << FLATDATA(messageStart) << nSize;
  1269. // Write undo data
  1270. long fileOutPos = ftell(fileout.Get());
  1271. if (fileOutPos < 0)
  1272. return error("%s: ftell failed", __func__);
  1273. pos.nPos = (unsigned int)fileOutPos;
  1274. fileout << blockundo;
  1275. // calculate & write checksum
  1276. CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
  1277. hasher << hashBlock;
  1278. hasher << blockundo;
  1279. fileout << hasher.GetHash();
  1280. return true;
  1281. }
  1282. static bool UndoReadFromDisk(CBlockUndo& blockundo, const CBlockIndex *pindex)
  1283. {
  1284. CDiskBlockPos pos = pindex->GetUndoPos();
  1285. if (pos.IsNull()) {
  1286. return error("%s: no undo data available", __func__);
  1287. }
  1288. // Open history file to read
  1289. CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
  1290. if (filein.IsNull())
  1291. return error("%s: OpenUndoFile failed", __func__);
  1292. // Read block
  1293. uint256 hashChecksum;
  1294. CHashVerifier<CAutoFile> verifier(&filein); // We need a CHashVerifier as reserializing may lose data
  1295. try {
  1296. verifier << pindex->pprev->GetBlockHash();
  1297. verifier >> blockundo;
  1298. filein >> hashChecksum;
  1299. }
  1300. catch (const std::exception& e) {
  1301. return error("%s: Deserialize or I/O error - %s", __func__, e.what());
  1302. }
  1303. // Verify checksum
  1304. if (hashChecksum != verifier.GetHash())
  1305. return error("%s: Checksum mismatch", __func__);
  1306. return true;
  1307. }
  1308. /** Abort with a message */
  1309. bool AbortNode(const std::string& strMessage, const std::string& userMessage="")
  1310. {
  1311. SetMiscWarning(strMessage);
  1312. LogPrintf("*** %s\n", strMessage);
  1313. uiInterface.ThreadSafeMessageBox(
  1314. userMessage.empty() ? _("Error: A fatal internal error occurred, see debug.log for details") : userMessage,
  1315. "", CClientUIInterface::MSG_ERROR);
  1316. StartShutdown();
  1317. return false;
  1318. }
  1319. bool AbortNode(CValidationState& state, const std::string& strMessage, const std::string& userMessage="")
  1320. {
  1321. AbortNode(strMessage, userMessage);
  1322. return state.Error(strMessage);
  1323. }
  1324. } // namespace
  1325. /**
  1326. * Restore the UTXO in a Coin at a given COutPoint
  1327. * @param undo The Coin to be restored.
  1328. * @param view The coins view to which to apply the changes.
  1329. * @param out The out point that corresponds to the tx input.
  1330. * @return A DisconnectResult as an int
  1331. */
  1332. int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out)
  1333. {
  1334. bool fClean = true;
  1335. if (view.HaveCoin(out)) fClean = false; // overwriting transaction output
  1336. if (undo.nHeight == 0) {
  1337. // Missing undo metadata (height and coinbase). Older versions included this
  1338. // information only in undo records for the last spend of a transactions'
  1339. // outputs. This implies that it must be present for some other output of the same tx.
  1340. const Coin& alternate = AccessByTxid(view, out.hash);
  1341. if (!alternate.IsSpent()) {
  1342. undo.nHeight = alternate.nHeight;
  1343. undo.fCoinBase = alternate.fCoinBase;
  1344. } else {
  1345. return DISCONNECT_FAILED; // adding output for transaction without known metadata
  1346. }
  1347. }
  1348. // The potential_overwrite parameter to AddCoin is only allowed to be false if we know for
  1349. // sure that the coin did not already exist in the cache. As we have queried for that above
  1350. // using HaveCoin, we don't need to guess. When fClean is false, a coin already existed and
  1351. // it is an overwrite.
  1352. view.AddCoin(out, std::move(undo), !fClean);
  1353. return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
  1354. }
  1355. /** Undo the effects of this block (with given index) on the UTXO set represented by coins.
  1356. * When FAILED is returned, view is left in an indeterminate state. */
  1357. DisconnectResult CChainState::DisconnectBlock(const CBlock& block, const CBlockIndex* pindex, CCoinsViewCache& view)
  1358. {
  1359. bool fClean = true;
  1360. CBlockUndo blockUndo;
  1361. if (!UndoReadFromDisk(blockUndo, pindex)) {
  1362. error("DisconnectBlock(): failure reading undo data");
  1363. return DISCONNECT_FAILED;
  1364. }
  1365. if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) {
  1366. error("DisconnectBlock(): block and undo data inconsistent");
  1367. return DISCONNECT_FAILED;
  1368. }
  1369. // undo transactions in reverse order
  1370. for (int i = block.vtx.size() - 1; i >= 0; i--) {
  1371. const CTransaction &tx = *(block.vtx[i]);
  1372. uint256 hash = tx.GetHash();
  1373. bool is_coinbase = tx.IsCoinBase();
  1374. // Check that all outputs are available and match the outputs in the block itself
  1375. // exactly.
  1376. for (size_t o = 0; o < tx.vout.size(); o++) {
  1377. if (!tx.vout[o].scriptPubKey.IsUnspendable()) {
  1378. COutPoint out(hash, o);
  1379. Coin coin;
  1380. bool is_spent = view.SpendCoin(out, &coin);
  1381. if (!is_spent || tx.vout[o] != coin.out || pindex->nHeight != coin.nHeight || is_coinbase != coin.fCoinBase) {
  1382. fClean = false; // transaction output mismatch
  1383. }
  1384. }
  1385. }
  1386. // restore inputs
  1387. if (i > 0) { // not coinbases
  1388. CTxUndo &txundo = blockUndo.vtxundo[i-1];
  1389. if (txundo.vprevout.size() != tx.vin.size()) {
  1390. error("DisconnectBlock(): transaction and undo data inconsistent");
  1391. return DISCONNECT_FAILED;
  1392. }
  1393. for (unsigned int j = tx.vin.size(); j-- > 0;) {
  1394. const COutPoint &out = tx.vin[j].prevout;
  1395. int res = ApplyTxInUndo(std::move(txundo.vprevout[j]), view, out);
  1396. if (res == DISCONNECT_FAILED) return DISCONNECT_FAILED;
  1397. fClean = fClean && res != DISCONNECT_UNCLEAN;
  1398. }
  1399. // At this point, all of txundo.vprevout should have been moved out.
  1400. }
  1401. }
  1402. // move best block pointer to prevout block
  1403. view.SetBestBlock(pindex->pprev->GetBlockHash());
  1404. return fClean ? DISCONNECT_OK : DISCONNECT_UNCLEAN;
  1405. }
  1406. void static FlushBlockFile(bool fFinalize = false)
  1407. {
  1408. LOCK(cs_LastBlockFile);
  1409. CDiskBlockPos posOld(nLastBlockFile, 0);
  1410. FILE *fileOld = OpenBlockFile(posOld);
  1411. if (fileOld) {
  1412. if (fFinalize)
  1413. TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
  1414. FileCommit(fileOld);
  1415. fclose(fileOld);
  1416. }
  1417. fileOld = OpenUndoFile(posOld);
  1418. if (fileOld) {
  1419. if (fFinalize)
  1420. TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
  1421. FileCommit(fileOld);
  1422. fclose(fileOld);
  1423. }
  1424. }
  1425. static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
  1426. static bool WriteUndoDataForBlock(const CBlockUndo& blockundo, CValidationState& state, CBlockIndex* pindex, const CChainParams& chainparams)
  1427. {
  1428. // Write undo information to disk
  1429. if (pindex->GetUndoPos().IsNull()) {
  1430. CDiskBlockPos _pos;
  1431. if (!FindUndoPos(state, pindex->nFile, _pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
  1432. return error("ConnectBlock(): FindUndoPos failed");
  1433. if (!UndoWriteToDisk(blockundo, _pos, pindex->pprev->GetBlockHash(), chainparams.MessageStart()))
  1434. return AbortNode(state, "Failed to write undo data");
  1435. // update nUndoPos in block index
  1436. pindex->nUndoPos = _pos.nPos;
  1437. pindex->nStatus |= BLOCK_HAVE_UNDO;
  1438. setDirtyBlockIndex.insert(pindex);
  1439. }
  1440. return true;
  1441. }
  1442. static bool WriteTxIndexDataForBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex)
  1443. {
  1444. if (!fTxIndex) return true;
  1445. CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
  1446. std::vector<std::pair<uint256, CDiskTxPos> > vPos;
  1447. vPos.reserve(block.vtx.size());
  1448. for (const CTransactionRef& tx : block.vtx)
  1449. {
  1450. vPos.push_back(std::make_pair(tx->GetHash(), pos));
  1451. pos.nTxOffset += ::GetSerializeSize(*tx, SER_DISK, CLIENT_VERSION);
  1452. }
  1453. if (!pblocktree->WriteTxIndex(vPos)) {
  1454. return AbortNode(state, "Failed to write transaction index");
  1455. }
  1456. return true;
  1457. }
  1458. static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
  1459. void ThreadScriptCheck() {
  1460. RenameThread("bitcoin-scriptch");
  1461. scriptcheckqueue.Thread();
  1462. }
  1463. // Protected by cs_main
  1464. VersionBitsCache versionbitscache;
  1465. int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params)
  1466. {
  1467. LOCK(cs_main);
  1468. int32_t nVersion = VERSIONBITS_TOP_BITS;
  1469. for (int i = 0; i < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++) {
  1470. ThresholdState state = VersionBitsState(pindexPrev, params, (Consensus::DeploymentPos)i, versionbitscache);
  1471. if (state == THRESHOLD_LOCKED_IN || state == THRESHOLD_STARTED) {
  1472. nVersion |= VersionBitsMask(params, (Consensus::DeploymentPos)i);
  1473. }
  1474. }
  1475. return nVersion;
  1476. }
  1477. /**
  1478. * Threshold condition checker that triggers when unknown versionbits are seen on the network.
  1479. */
  1480. class WarningBitsConditionChecker : public AbstractThresholdConditionChecker
  1481. {
  1482. private:
  1483. int bit;
  1484. public:
  1485. explicit WarningBitsConditionChecker(int bitIn) : bit(bitIn) {}
  1486. int64_t BeginTime(const Consensus::Params& params) const override { return 0; }
  1487. int64_t EndTime(const Consensus::Params& params) const override { return std::numeric_limits<int64_t>::max(); }
  1488. int Period(const Consensus::Params& params) const override { return params.nMinerConfirmationWindow; }
  1489. int Threshold(const Consensus::Params& params) const override { return params.nRuleChangeActivationThreshold; }
  1490. bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const override
  1491. {
  1492. return ((pindex->nVersion & VERSIONBITS_TOP_MASK) == VERSIONBITS_TOP_BITS) &&
  1493. ((pindex->nVersion >> bit) & 1) != 0 &&
  1494. ((ComputeBlockVersion(pindex->pprev, params) >> bit) & 1) == 0;
  1495. }
  1496. };
  1497. // Protected by cs_main
  1498. static ThresholdConditionCache warningcache[VERSIONBITS_NUM_BITS];
  1499. static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& consensusparams) {
  1500. AssertLockHeld(cs_main);
  1501. unsigned int flags = SCRIPT_VERIFY_NONE;
  1502. // Start enforcing P2SH (BIP16)
  1503. if (pindex->nHeight >= consensusparams.BIP16Height) {
  1504. flags |= SCRIPT_VERIFY_P2SH;
  1505. }
  1506. // Start enforcing the DERSIG (BIP66) rule
  1507. if (pindex->nHeight >= consensusparams.BIP66Height) {
  1508. flags |= SCRIPT_VERIFY_DERSIG;
  1509. }
  1510. // Start enforcing CHECKLOCKTIMEVERIFY (BIP65) rule
  1511. if (pindex->nHeight >= consensusparams.BIP65Height) {
  1512. flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
  1513. }
  1514. // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
  1515. if (VersionBitsState(pindex->pprev, consensusparams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
  1516. flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
  1517. }
  1518. // Start enforcing WITNESS rules using versionbits logic.
  1519. if (IsWitnessEnabled(pindex->pprev, consensusparams)) {
  1520. flags |= SCRIPT_VERIFY_WITNESS;
  1521. flags |= SCRIPT_VERIFY_NULLDUMMY;
  1522. }
  1523. return flags;
  1524. }
  1525. static int64_t nTimeCheck = 0;
  1526. static int64_t nTimeForks = 0;
  1527. static int64_t nTimeVerify = 0;
  1528. static int64_t nTimeConnect = 0;
  1529. static int64_t nTimeIndex = 0;
  1530. static int64_t nTimeCallbacks = 0;
  1531. static int64_t nTimeTotal = 0;
  1532. static int64_t nBlocksTotal = 0;
  1533. /** Apply the effects of this block (with given index) on the UTXO set represented by coins.
  1534. * Validity checks that depend on the UTXO set are also done; ConnectBlock()
  1535. * can fail if those validity checks fail (among other reasons). */
  1536. bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex,
  1537. CCoinsViewCache& view, const CChainParams& chainparams, bool fJustCheck)
  1538. {
  1539. AssertLockHeld(cs_main);
  1540. assert(pindex);
  1541. // pindex->phashBlock can be null if called by CreateNewBlock/TestBlockValidity
  1542. assert((pindex->phashBlock == nullptr) ||
  1543. (*pindex->phashBlock == block.GetHash()));
  1544. int64_t nTimeStart = GetTimeMicros();
  1545. // Check it again in case a previous version let a bad block in
  1546. // NOTE: We don't currently (re-)invoke ContextualCheckBlock() or
  1547. // ContextualCheckBlockHeader() here. This means that if we add a new
  1548. // consensus rule that is enforced in one of those two functions, then we
  1549. // may have let in a block that violates the rule prior to updating the
  1550. // software, and we would NOT be enforcing the rule here. Fully solving
  1551. // upgrade from one software version to the next after a consensus rule
  1552. // change is potentially tricky and issue-specific (see RewindBlockIndex()
  1553. // for one general approach that was used for BIP 141 deployment).
  1554. // Also, currently the rule against blocks more than 2 hours in the future
  1555. // is enforced in ContextualCheckBlockHeader(); we wouldn't want to
  1556. // re-enforce that rule here (at least until we make it impossible for
  1557. // GetAdjustedTime() to go backward).
  1558. if (!CheckBlock(block, state, chainparams.GetConsensus(), !fJustCheck, !fJustCheck))
  1559. return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
  1560. // verify that the view's current state corresponds to the previous block
  1561. uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();
  1562. assert(hashPrevBlock == view.GetBestBlock());
  1563. // Special case for the genesis block, skipping connection of its transactions
  1564. // (its coinbase is unspendable)
  1565. if (block.GetHash() == chainparams.GetConsensus().hashGenesisBlock) {
  1566. if (!fJustCheck)
  1567. view.SetBestBlock(pindex->GetBlockHash());
  1568. return true;
  1569. }
  1570. nBlocksTotal++;
  1571. bool fScriptChecks = true;
  1572. if (!hashAssumeValid.IsNull()) {
  1573. // We've been configured with the hash of a block which has been externally verified to have a valid history.
  1574. // A suitable default value is included with the software and updated from time to time. Because validity
  1575. // relative to a piece of software is an objective fact these defaults can be easily reviewed.
  1576. // This setting doesn't force the selection of any particular chain but makes validating some faster by
  1577. // effectively caching the result of part of the verification.
  1578. BlockMap::const_iterator it = mapBlockIndex.find(hashAssumeValid);
  1579. if (it != mapBlockIndex.end()) {
  1580. if (it->second->GetAncestor(pindex->nHeight) == pindex &&
  1581. pindexBestHeader->GetAncestor(pindex->nHeight) == pindex &&
  1582. pindexBestHeader->nChainWork >= nMinimumChainWork) {
  1583. // This block is a member of the assumed verified chain and an ancestor of the best header.
  1584. // The equivalent time check discourages hash power from extorting the network via DOS attack
  1585. // into accepting an invalid block through telling users they must manually set assumevalid.
  1586. // Requiring a software change or burying the invalid block, regardless of the setting, makes
  1587. // it hard to hide the implication of the demand. This also avoids having release candidates
  1588. // that are hardly doing any signature verification at all in testing without having to
  1589. // artificially set the default assumed verified block further back.
  1590. // The test against nMinimumChainWork prevents the skipping when denied access to any chain at
  1591. // least as good as the expected chain.
  1592. fScriptChecks = (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, chainparams.GetConsensus()) <= 60 * 60 * 24 * 7 * 2);
  1593. }
  1594. }
  1595. }
  1596. int64_t nTime1 = GetTimeMicros(); nTimeCheck += nTime1 - nTimeStart;
  1597. LogPrint(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime1 - nTimeStart), nTimeCheck * MICRO, nTimeCheck * MILLI / nBlocksTotal);
  1598. // Do not allow blocks that contain transactions which 'overwrite' older transactions,
  1599. // unless those are already completely spent.
  1600. // If such overwrites are allowed, coinbases and transactions depending upon those
  1601. // can be duplicated to remove the ability to spend the first instance -- even after
  1602. // being sent to another address.
  1603. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
  1604. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
  1605. // already refuses previously-known transaction ids entirely.
  1606. // This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.
  1607. // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
  1608. // two in the chain that violate it. This prevents exploiting the issue against nodes during their
  1609. // initial block download.
  1610. bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
  1611. !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256S("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
  1612. (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256S("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
  1613. // Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting
  1614. // with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the
  1615. // time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first
  1616. // before the first had been spent. Since those coinbases are sufficiently buried its no longer possible to create further
  1617. // duplicate transactions descending from the known pairs either.
  1618. // If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.
  1619. assert(pindex->pprev);
  1620. CBlockIndex *pindexBIP34height = pindex->pprev->GetAncestor(chainparams.GetConsensus().BIP34Height);
  1621. //Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.
  1622. fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == chainparams.GetConsensus().BIP34Hash));
  1623. if (fEnforceBIP30) {
  1624. for (const auto& tx : block.vtx) {
  1625. for (size_t o = 0; o < tx->vout.size(); o++) {
  1626. if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {
  1627. return state.DoS(100, error("ConnectBlock(): tried to overwrite transaction"),
  1628. REJECT_INVALID, "bad-txns-BIP30");
  1629. }
  1630. }
  1631. }
  1632. }
  1633. // Start enforcing BIP68 (sequence locks) and BIP112 (CHECKSEQUENCEVERIFY) using versionbits logic.
  1634. int nLockTimeFlags = 0;
  1635. if (VersionBitsState(pindex->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
  1636. nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;
  1637. }
  1638. // Get the script flags for this block
  1639. unsigned int flags = GetBlockScriptFlags(pindex, chainparams.GetConsensus());
  1640. int64_t nTime2 = GetTimeMicros(); nTimeForks += nTime2 - nTime1;
  1641. LogPrint(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime2 - nTime1), nTimeForks * MICRO, nTimeForks * MILLI / nBlocksTotal);
  1642. CBlockUndo blockundo;
  1643. CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr);
  1644. std::vector<int> prevheights;
  1645. CAmount nFees = 0;
  1646. int nInputs = 0;
  1647. int64_t nSigOpsCost = 0;
  1648. blockundo.vtxundo.reserve(block.vtx.size() - 1);
  1649. std::vector<PrecomputedTransactionData> txdata;
  1650. txdata.reserve(block.vtx.size()); // Required so that pointers to individual PrecomputedTransactionData don't get invalidated
  1651. for (unsigned int i = 0; i < block.vtx.size(); i++)
  1652. {
  1653. const CTransaction &tx = *(block.vtx[i]);
  1654. nInputs += tx.vin.size();
  1655. if (!tx.IsCoinBase())
  1656. {
  1657. CAmount txfee = 0;
  1658. if (!Consensus::CheckTxInputs(tx, state, view, pindex->nHeight, txfee)) {
  1659. return error("%s: Consensus::CheckTxInputs: %s, %s", __func__, tx.GetHash().ToString(), FormatStateMessage(state));
  1660. }
  1661. nFees += txfee;
  1662. if (!MoneyRange(nFees)) {
  1663. return state.DoS(100, error("%s: accumulated fee in the block out of range.", __func__),
  1664. REJECT_INVALID, "bad-txns-accumulated-fee-outofrange");
  1665. }
  1666. // Check that transaction is BIP68 final
  1667. // BIP68 lock checks (as opposed to nLockTime checks) must
  1668. // be in ConnectBlock because they require the UTXO set
  1669. prevheights.resize(tx.vin.size());
  1670. for (size_t j = 0; j < tx.vin.size(); j++) {
  1671. prevheights[j] = view.AccessCoin(tx.vin[j].prevout).nHeight;
  1672. }
  1673. if (!SequenceLocks(tx, nLockTimeFlags, &prevheights, *pindex)) {
  1674. return state.DoS(100, error("%s: contains a non-BIP68-final transaction", __func__),
  1675. REJECT_INVALID, "bad-txns-nonfinal");
  1676. }
  1677. }
  1678. // GetTransactionSigOpCost counts 3 types of sigops:
  1679. // * legacy (always)
  1680. // * p2sh (when P2SH enabled in flags and excludes coinbase)
  1681. // * witness (when witness enabled in flags and excludes coinbase)
  1682. nSigOpsCost += GetTransactionSigOpCost(tx, view, flags);
  1683. if (nSigOpsCost > MAX_BLOCK_SIGOPS_COST)
  1684. return state.DoS(100, error("ConnectBlock(): too many sigops"),
  1685. REJECT_INVALID, "bad-blk-sigops");
  1686. txdata.emplace_back(tx);
  1687. if (!tx.IsCoinBase())
  1688. {
  1689. std::vector<CScriptCheck> vChecks;
  1690. bool fCacheResults = fJustCheck; /* Don't cache results if we're actually connecting blocks (still consult the cache, though) */
  1691. if (!CheckInputs(tx, state, view, fScriptChecks, flags, fCacheResults, fCacheResults, txdata[i], nScriptCheckThreads ? &vChecks : nullptr))
  1692. return error("ConnectBlock(): CheckInputs on %s failed with %s",
  1693. tx.GetHash().ToString(), FormatStateMessage(state));
  1694. control.Add(vChecks);
  1695. }
  1696. CTxUndo undoDummy;
  1697. if (i > 0) {
  1698. blockundo.vtxundo.push_back(CTxUndo());
  1699. }
  1700. UpdateCoins(tx, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
  1701. }
  1702. int64_t nTime3 = GetTimeMicros(); nTimeConnect += nTime3 - nTime2;
  1703. LogPrint(BCLog::BENCH, " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs (%.2fms/blk)]\n", (unsigned)block.vtx.size(), MILLI * (nTime3 - nTime2), MILLI * (nTime3 - nTime2) / block.vtx.size(), nInputs <= 1 ? 0 : MILLI * (nTime3 - nTime2) / (nInputs-1), nTimeConnect * MICRO, nTimeConnect * MILLI / nBlocksTotal);
  1704. CAmount blockReward = nFees + GetBlockSubsidy(pindex->nHeight, chainparams.GetConsensus());
  1705. if (block.vtx[0]->GetValueOut() > blockReward)
  1706. return state.DoS(100,
  1707. error("ConnectBlock(): coinbase pays too much (actual=%d vs limit=%d)",
  1708. block.vtx[0]->GetValueOut(), blockReward),
  1709. REJECT_INVALID, "bad-cb-amount");
  1710. if (!control.Wait())
  1711. return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed");
  1712. int64_t nTime4 = GetTimeMicros(); nTimeVerify += nTime4 - nTime2;
  1713. LogPrint(BCLog::BENCH, " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs (%.2fms/blk)]\n", nInputs - 1, MILLI * (nTime4 - nTime2), nInputs <= 1 ? 0 : MILLI * (nTime4 - nTime2) / (nInputs-1), nTimeVerify * MICRO, nTimeVerify * MILLI / nBlocksTotal);
  1714. if (fJustCheck)
  1715. return true;
  1716. if (!WriteUndoDataForBlock(blockundo, state, pindex, chainparams))
  1717. return false;
  1718. if (!pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
  1719. pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
  1720. setDirtyBlockIndex.insert(pindex);
  1721. }
  1722. if (!WriteTxIndexDataForBlock(block, state, pindex))
  1723. return false;
  1724. assert(pindex->phashBlock);
  1725. // add this block to the view's block chain
  1726. view.SetBestBlock(pindex->GetBlockHash());
  1727. int64_t nTime5 = GetTimeMicros(); nTimeIndex += nTime5 - nTime4;
  1728. LogPrint(BCLog::BENCH, " - Index writing: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime5 - nTime4), nTimeIndex * MICRO, nTimeIndex * MILLI / nBlocksTotal);
  1729. int64_t nTime6 = GetTimeMicros(); nTimeCallbacks += nTime6 - nTime5;
  1730. LogPrint(BCLog::BENCH, " - Callbacks: %.2fms [%.2fs (%.2fms/blk)]\n", MILLI * (nTime6 - nTime5), nTimeCallbacks * MICRO, nTimeCallbacks * MILLI / nBlocksTotal);
  1731. return true;
  1732. }
  1733. /**
  1734. * Update the on-disk chain state.
  1735. * The caches and indexes are flushed depending on the mode we're called with
  1736. * if they're too large, if it's been a while since the last write,
  1737. * or always and in all cases if we're in prune mode and are deleting files.
  1738. */
  1739. bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState &state, FlushStateMode mode, int nManualPruneHeight) {
  1740. int64_t nMempoolUsage = mempool.DynamicMemoryUsage();
  1741. LOCK(cs_main);
  1742. static int64_t nLastWrite = 0;
  1743. static int64_t nLastFlush = 0;
  1744. static int64_t nLastSetChain = 0;
  1745. std::set<int> setFilesToPrune;
  1746. bool fFlushForPrune = false;
  1747. bool fDoFullFlush = false;
  1748. int64_t nNow = 0;
  1749. try {
  1750. {
  1751. LOCK(cs_LastBlockFile);
  1752. if (fPruneMode && (fCheckForPruning || nManualPruneHeight > 0) && !fReindex) {
  1753. if (nManualPruneHeight > 0) {
  1754. FindFilesToPruneManual(setFilesToPrune, nManualPruneHeight);
  1755. } else {
  1756. FindFilesToPrune(setFilesToPrune, chainparams.PruneAfterHeight());
  1757. fCheckForPruning = false;
  1758. }
  1759. if (!setFilesToPrune.empty()) {
  1760. fFlushForPrune = true;
  1761. if (!fHavePruned) {
  1762. pblocktree->WriteFlag("prunedblockfiles", true);
  1763. fHavePruned = true;
  1764. }
  1765. }
  1766. }
  1767. nNow = GetTimeMicros();
  1768. // Avoid writing/flushing immediately after startup.
  1769. if (nLastWrite == 0) {
  1770. nLastWrite = nNow;
  1771. }
  1772. if (nLastFlush == 0) {
  1773. nLastFlush = nNow;
  1774. }
  1775. if (nLastSetChain == 0) {
  1776. nLastSetChain = nNow;
  1777. }
  1778. int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
  1779. int64_t cacheSize = pcoinsTip->DynamicMemoryUsage();
  1780. int64_t nTotalSpace = nCoinCacheUsage + std::max<int64_t>(nMempoolSizeMax - nMempoolUsage, 0);
  1781. // The cache is large and we're within 10% and 10 MiB of the limit, but we have time now (not in the middle of a block processing).
  1782. bool fCacheLarge = mode == FLUSH_STATE_PERIODIC && cacheSize > std::max((9 * nTotalSpace) / 10, nTotalSpace - MAX_BLOCK_COINSDB_USAGE * 1024 * 1024);
  1783. // The cache is over the limit, we have to write now.
  1784. bool fCacheCritical = mode == FLUSH_STATE_IF_NEEDED && cacheSize > nTotalSpace;
  1785. // It's been a while since we wrote the block index to disk. Do this frequently, so we don't need to redownload after a crash.
  1786. bool fPeriodicWrite = mode == FLUSH_STATE_PERIODIC && nNow > nLastWrite + (int64_t)DATABASE_WRITE_INTERVAL * 1000000;
  1787. // It's been very long since we flushed the cache. Do this infrequently, to optimize cache usage.
  1788. bool fPeriodicFlush = mode == FLUSH_STATE_PERIODIC && nNow > nLastFlush + (int64_t)DATABASE_FLUSH_INTERVAL * 1000000;
  1789. // Combine all conditions that result in a full cache flush.
  1790. fDoFullFlush = (mode == FLUSH_STATE_ALWAYS) || fCacheLarge || fCacheCritical || fPeriodicFlush || fFlushForPrune;
  1791. // Write blocks and block index to disk.
  1792. if (fDoFullFlush || fPeriodicWrite) {
  1793. // Depend on nMinDiskSpace to ensure we can write block index
  1794. if (!CheckDiskSpace(0))
  1795. return state.Error("out of disk space");
  1796. // First make sure all block and undo data is flushed to disk.
  1797. FlushBlockFile();
  1798. // Then update all block file information (which may refer to block and undo files).
  1799. {
  1800. std::vector<std::pair<int, const CBlockFileInfo*> > vFiles;
  1801. vFiles.reserve(setDirtyFileInfo.size());
  1802. for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) {
  1803. vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it]));
  1804. setDirtyFileInfo.erase(it++);
  1805. }
  1806. std::vector<const CBlockIndex*> vBlocks;
  1807. vBlocks.reserve(setDirtyBlockIndex.size());
  1808. for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) {
  1809. vBlocks.push_back(*it);
  1810. setDirtyBlockIndex.erase(it++);
  1811. }
  1812. if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) {
  1813. return AbortNode(state, "Failed to write to block index database");
  1814. }
  1815. }
  1816. // Finally remove any pruned files
  1817. if (fFlushForPrune)
  1818. UnlinkPrunedFiles(setFilesToPrune);
  1819. nLastWrite = nNow;
  1820. }
  1821. // Flush best chain related state. This can only be done if the blocks / block index write was also done.
  1822. if (fDoFullFlush && !pcoinsTip->GetBestBlock().IsNull()) {
  1823. // Typical Coin structures on disk are around 48 bytes in size.
  1824. // Pushing a new one to the database can cause it to be written
  1825. // twice (once in the log, and once in the tables). This is already
  1826. // an overestimation, as most will delete an existing entry or
  1827. // overwrite one. Still, use a conservative safety factor of 2.
  1828. if (!CheckDiskSpace(48 * 2 * 2 * pcoinsTip->GetCacheSize()))
  1829. return state.Error("out of disk space");
  1830. // Flush the chainstate (which may refer to block index entries).
  1831. if (!pcoinsTip->Flush())
  1832. return AbortNode(state, "Failed to write to coin database");
  1833. nLastFlush = nNow;
  1834. }
  1835. }
  1836. if (fDoFullFlush || ((mode == FLUSH_STATE_ALWAYS || mode == FLUSH_STATE_PERIODIC) && nNow > nLastSetChain + (int64_t)DATABASE_WRITE_INTERVAL * 1000000)) {
  1837. // Update best block in wallet (so we can detect restored wallets).
  1838. GetMainSignals().SetBestChain(chainActive.GetLocator());
  1839. nLastSetChain = nNow;
  1840. }
  1841. } catch (const std::runtime_error& e) {
  1842. return AbortNode(state, std::string("System error while flushing: ") + e.what());
  1843. }
  1844. return true;
  1845. }
  1846. void FlushStateToDisk() {
  1847. CValidationState state;
  1848. const CChainParams& chainparams = Params();
  1849. FlushStateToDisk(chainparams, state, FLUSH_STATE_ALWAYS);
  1850. }
  1851. void PruneAndFlush() {
  1852. CValidationState state;
  1853. fCheckForPruning = true;
  1854. const CChainParams& chainparams = Params();
  1855. FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE);
  1856. }
  1857. static void DoWarning(const std::string& strWarning)
  1858. {
  1859. static bool fWarned = false;
  1860. SetMiscWarning(strWarning);
  1861. if (!fWarned) {
  1862. AlertNotify(strWarning);
  1863. fWarned = true;
  1864. }
  1865. }
  1866. /** Check warning conditions and do some notifications on new chain tip set. */
  1867. void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainParams) {
  1868. // New best block
  1869. mempool.AddTransactionsUpdated(1);
  1870. cvBlockChange.notify_all();
  1871. std::vector<std::string> warningMessages;
  1872. if (!IsInitialBlockDownload())
  1873. {
  1874. int nUpgraded = 0;
  1875. const CBlockIndex* pindex = pindexNew;
  1876. for (int bit = 0; bit < VERSIONBITS_NUM_BITS; bit++) {
  1877. WarningBitsConditionChecker checker(bit);
  1878. ThresholdState state = checker.GetStateFor(pindex, chainParams.GetConsensus(), warningcache[bit]);
  1879. if (state == THRESHOLD_ACTIVE || state == THRESHOLD_LOCKED_IN) {
  1880. const std::string strWarning = strprintf(_("Warning: unknown new rules activated (versionbit %i)"), bit);
  1881. if (state == THRESHOLD_ACTIVE) {
  1882. DoWarning(strWarning);
  1883. } else {
  1884. warningMessages.push_back(strWarning);
  1885. }
  1886. }
  1887. }
  1888. // Check the version of the last 100 blocks to see if we need to upgrade:
  1889. for (int i = 0; i < 100 && pindex != nullptr; i++)
  1890. {
  1891. int32_t nExpectedVersion = ComputeBlockVersion(pindex->pprev, chainParams.GetConsensus());
  1892. if (pindex->nVersion > VERSIONBITS_LAST_OLD_BLOCK_VERSION && (pindex->nVersion & ~nExpectedVersion) != 0)
  1893. ++nUpgraded;
  1894. pindex = pindex->pprev;
  1895. }
  1896. if (nUpgraded > 0)
  1897. warningMessages.push_back(strprintf(_("%d of last 100 blocks have unexpected version"), nUpgraded));
  1898. if (nUpgraded > 100/2)
  1899. {
  1900. std::string strWarning = _("Warning: Unknown block versions being mined! It's possible unknown rules are in effect");
  1901. // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
  1902. DoWarning(strWarning);
  1903. }
  1904. }
  1905. LogPrintf("%s: new best=%s height=%d version=0x%08x log2_work=%.8g tx=%lu date='%s' progress=%f cache=%.1fMiB(%utxo)", __func__,
  1906. pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, pindexNew->nVersion,
  1907. log(pindexNew->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
  1908. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime()),
  1909. GuessVerificationProgress(chainParams.TxData(), pindexNew), pcoinsTip->DynamicMemoryUsage() * (1.0 / (1<<20)), pcoinsTip->GetCacheSize());
  1910. if (!warningMessages.empty())
  1911. LogPrintf(" warning='%s'", boost::algorithm::join(warningMessages, ", "));
  1912. LogPrintf("\n");
  1913. }
  1914. /** Disconnect chainActive's tip.
  1915. * After calling, the mempool will be in an inconsistent state, with
  1916. * transactions from disconnected blocks being added to disconnectpool. You
  1917. * should make the mempool consistent again by calling UpdateMempoolForReorg.
  1918. * with cs_main held.
  1919. *
  1920. * If disconnectpool is nullptr, then no disconnected transactions are added to
  1921. * disconnectpool (note that the caller is responsible for mempool consistency
  1922. * in any case).
  1923. */
  1924. bool CChainState::DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
  1925. {
  1926. CBlockIndex *pindexDelete = chainActive.Tip();
  1927. assert(pindexDelete);
  1928. // Read block from disk.
  1929. std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
  1930. CBlock& block = *pblock;
  1931. if (!ReadBlockFromDisk(block, pindexDelete, chainparams.GetConsensus()))
  1932. return AbortNode(state, "Failed to read block");
  1933. // Apply the block atomically to the chain state.
  1934. int64_t nStart = GetTimeMicros();
  1935. {
  1936. CCoinsViewCache view(pcoinsTip.get());
  1937. assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
  1938. if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
  1939. return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
  1940. bool flushed = view.Flush();
  1941. assert(flushed);
  1942. }
  1943. LogPrint(BCLog::BENCH, "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * MILLI);
  1944. // Write the chain state to disk, if necessary.
  1945. if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
  1946. return false;
  1947. if (disconnectpool) {
  1948. // Save transactions to re-add to mempool at end of reorg
  1949. for (auto it = block.vtx.rbegin(); it != block.vtx.rend(); ++it) {
  1950. disconnectpool->addTransaction(*it);
  1951. }
  1952. while (disconnectpool->DynamicMemoryUsage() > MAX_DISCONNECTED_TX_POOL_SIZE * 1000) {
  1953. // Drop the earliest entry, and remove its children from the mempool.
  1954. auto it = disconnectpool->queuedTx.get<insertion_order>().begin();
  1955. mempool.removeRecursive(**it, MemPoolRemovalReason::REORG);
  1956. disconnectpool->removeEntry(it);
  1957. }
  1958. }
  1959. chainActive.SetTip(pindexDelete->pprev);
  1960. UpdateTip(pindexDelete->pprev, chainparams);
  1961. // Let wallets know transactions went from 1-confirmed to
  1962. // 0-confirmed or conflicted:
  1963. GetMainSignals().BlockDisconnected(pblock);
  1964. return true;
  1965. }
  1966. static int64_t nTimeReadFromDisk = 0;
  1967. static int64_t nTimeConnectTotal = 0;
  1968. static int64_t nTimeFlush = 0;
  1969. static int64_t nTimeChainState = 0;
  1970. static int64_t nTimePostConnect = 0;
  1971. struct PerBlockConnectTrace {
  1972. CBlockIndex* pindex = nullptr;
  1973. std::shared_ptr<const CBlock> pblock;
  1974. std::shared_ptr<std::vector<CTransactionRef>> conflictedTxs;
  1975. PerBlockConnectTrace() : conflictedTxs(std::make_shared<std::vector<CTransactionRef>>()) {}
  1976. };
  1977. /**
  1978. * Used to track blocks whose transactions were applied to the UTXO state as a
  1979. * part of a single ActivateBestChainStep call.
  1980. *
  1981. * This class also tracks transactions that are removed from the mempool as
  1982. * conflicts (per block) and can be used to pass all those transactions
  1983. * through SyncTransaction.
  1984. *
  1985. * This class assumes (and asserts) that the conflicted transactions for a given
  1986. * block are added via mempool callbacks prior to the BlockConnected() associated
  1987. * with those transactions. If any transactions are marked conflicted, it is
  1988. * assumed that an associated block will always be added.
  1989. *
  1990. * This class is single-use, once you call GetBlocksConnected() you have to throw
  1991. * it away and make a new one.
  1992. */
  1993. class ConnectTrace {
  1994. private:
  1995. std::vector<PerBlockConnectTrace> blocksConnected;
  1996. CTxMemPool &pool;
  1997. public:
  1998. explicit ConnectTrace(CTxMemPool &_pool) : blocksConnected(1), pool(_pool) {
  1999. pool.NotifyEntryRemoved.connect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
  2000. }
  2001. ~ConnectTrace() {
  2002. pool.NotifyEntryRemoved.disconnect(boost::bind(&ConnectTrace::NotifyEntryRemoved, this, _1, _2));
  2003. }
  2004. void BlockConnected(CBlockIndex* pindex, std::shared_ptr<const CBlock> pblock) {
  2005. assert(!blocksConnected.back().pindex);
  2006. assert(pindex);
  2007. assert(pblock);
  2008. blocksConnected.back().pindex = pindex;
  2009. blocksConnected.back().pblock = std::move(pblock);
  2010. blocksConnected.emplace_back();
  2011. }
  2012. std::vector<PerBlockConnectTrace>& GetBlocksConnected() {
  2013. // We always keep one extra block at the end of our list because
  2014. // blocks are added after all the conflicted transactions have
  2015. // been filled in. Thus, the last entry should always be an empty
  2016. // one waiting for the transactions from the next block. We pop
  2017. // the last entry here to make sure the list we return is sane.
  2018. assert(!blocksConnected.back().pindex);
  2019. assert(blocksConnected.back().conflictedTxs->empty());
  2020. blocksConnected.pop_back();
  2021. return blocksConnected;
  2022. }
  2023. void NotifyEntryRemoved(CTransactionRef txRemoved, MemPoolRemovalReason reason) {
  2024. assert(!blocksConnected.back().pindex);
  2025. if (reason == MemPoolRemovalReason::CONFLICT) {
  2026. blocksConnected.back().conflictedTxs->emplace_back(std::move(txRemoved));
  2027. }
  2028. }
  2029. };
  2030. /**
  2031. * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock
  2032. * corresponding to pindexNew, to bypass loading it again from disk.
  2033. *
  2034. * The block is added to connectTrace if connection succeeds.
  2035. */
  2036. bool CChainState::ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr<const CBlock>& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
  2037. {
  2038. assert(pindexNew->pprev == chainActive.Tip());
  2039. // Read block from disk.
  2040. int64_t nTime1 = GetTimeMicros();
  2041. std::shared_ptr<const CBlock> pthisBlock;
  2042. if (!pblock) {
  2043. std::shared_ptr<CBlock> pblockNew = std::make_shared<CBlock>();
  2044. if (!ReadBlockFromDisk(*pblockNew, pindexNew, chainparams.GetConsensus()))
  2045. return AbortNode(state, "Failed to read block");
  2046. pthisBlock = pblockNew;
  2047. } else {
  2048. pthisBlock = pblock;
  2049. }
  2050. const CBlock& blockConnecting = *pthisBlock;
  2051. // Apply the block atomically to the chain state.
  2052. int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1;
  2053. int64_t nTime3;
  2054. LogPrint(BCLog::BENCH, " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * MILLI, nTimeReadFromDisk * MICRO);
  2055. {
  2056. CCoinsViewCache view(pcoinsTip.get());
  2057. bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
  2058. GetMainSignals().BlockChecked(blockConnecting, state);
  2059. if (!rv) {
  2060. if (state.IsInvalid())
  2061. InvalidBlockFound(pindexNew, state);
  2062. return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
  2063. }
  2064. nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2;
  2065. LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
  2066. bool flushed = view.Flush();
  2067. assert(flushed);
  2068. }
  2069. int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3;
  2070. LogPrint(BCLog::BENCH, " - Flush: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime4 - nTime3) * MILLI, nTimeFlush * MICRO, nTimeFlush * MILLI / nBlocksTotal);
  2071. // Write the chain state to disk, if necessary.
  2072. if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_IF_NEEDED))
  2073. return false;
  2074. int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4;
  2075. LogPrint(BCLog::BENCH, " - Writing chainstate: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime5 - nTime4) * MILLI, nTimeChainState * MICRO, nTimeChainState * MILLI / nBlocksTotal);
  2076. // Remove conflicting transactions from the mempool.;
  2077. mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight);
  2078. disconnectpool.removeForBlock(blockConnecting.vtx);
  2079. // Update chainActive & related variables.
  2080. chainActive.SetTip(pindexNew);
  2081. UpdateTip(pindexNew, chainparams);
  2082. int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1;
  2083. LogPrint(BCLog::BENCH, " - Connect postprocess: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime5) * MILLI, nTimePostConnect * MICRO, nTimePostConnect * MILLI / nBlocksTotal);
  2084. LogPrint(BCLog::BENCH, "- Connect block: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime6 - nTime1) * MILLI, nTimeTotal * MICRO, nTimeTotal * MILLI / nBlocksTotal);
  2085. connectTrace.BlockConnected(pindexNew, std::move(pthisBlock));
  2086. return true;
  2087. }
  2088. /**
  2089. * Return the tip of the chain with the most work in it, that isn't
  2090. * known to be invalid (it's however far from certain to be valid).
  2091. */
  2092. CBlockIndex* CChainState::FindMostWorkChain() {
  2093. do {
  2094. CBlockIndex *pindexNew = nullptr;
  2095. // Find the best candidate header.
  2096. {
  2097. std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
  2098. if (it == setBlockIndexCandidates.rend())
  2099. return nullptr;
  2100. pindexNew = *it;
  2101. }
  2102. // Check whether all blocks on the path between the currently active chain and the candidate are valid.
  2103. // Just going until the active chain is an optimization, as we know all blocks in it are valid already.
  2104. CBlockIndex *pindexTest = pindexNew;
  2105. bool fInvalidAncestor = false;
  2106. while (pindexTest && !chainActive.Contains(pindexTest)) {
  2107. assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
  2108. // Pruned nodes may have entries in setBlockIndexCandidates for
  2109. // which block files have been deleted. Remove those as candidates
  2110. // for the most work chain if we come across them; we can't switch
  2111. // to a chain unless we have all the non-active-chain parent blocks.
  2112. bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
  2113. bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
  2114. if (fFailedChain || fMissingData) {
  2115. // Candidate chain is not usable (either invalid or missing data)
  2116. if (fFailedChain && (pindexBestInvalid == nullptr || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
  2117. pindexBestInvalid = pindexNew;
  2118. CBlockIndex *pindexFailed = pindexNew;
  2119. // Remove the entire chain from the set.
  2120. while (pindexTest != pindexFailed) {
  2121. if (fFailedChain) {
  2122. pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
  2123. } else if (fMissingData) {
  2124. // If we're missing data, then add back to mapBlocksUnlinked,
  2125. // so that if the block arrives in the future we can try adding
  2126. // to setBlockIndexCandidates again.
  2127. mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
  2128. }
  2129. setBlockIndexCandidates.erase(pindexFailed);
  2130. pindexFailed = pindexFailed->pprev;
  2131. }
  2132. setBlockIndexCandidates.erase(pindexTest);
  2133. fInvalidAncestor = true;
  2134. break;
  2135. }
  2136. pindexTest = pindexTest->pprev;
  2137. }
  2138. if (!fInvalidAncestor)
  2139. return pindexNew;
  2140. } while(true);
  2141. }
  2142. /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
  2143. void CChainState::PruneBlockIndexCandidates() {
  2144. // Note that we can't delete the current block itself, as we may need to return to it later in case a
  2145. // reorganization to a better block fails.
  2146. std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
  2147. while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
  2148. setBlockIndexCandidates.erase(it++);
  2149. }
  2150. // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
  2151. assert(!setBlockIndexCandidates.empty());
  2152. }
  2153. /**
  2154. * Try to make some progress towards making pindexMostWork the active block.
  2155. * pblock is either nullptr or a pointer to a CBlock corresponding to pindexMostWork.
  2156. */
  2157. bool CChainState::ActivateBestChainStep(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexMostWork, const std::shared_ptr<const CBlock>& pblock, bool& fInvalidFound, ConnectTrace& connectTrace)
  2158. {
  2159. AssertLockHeld(cs_main);
  2160. const CBlockIndex *pindexOldTip = chainActive.Tip();
  2161. const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork);
  2162. // Disconnect active blocks which are no longer in the best chain.
  2163. bool fBlocksDisconnected = false;
  2164. DisconnectedBlockTransactions disconnectpool;
  2165. while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
  2166. if (!DisconnectTip(state, chainparams, &disconnectpool)) {
  2167. // This is likely a fatal error, but keep the mempool consistent,
  2168. // just in case. Only remove from the mempool in this case.
  2169. UpdateMempoolForReorg(disconnectpool, false);
  2170. return false;
  2171. }
  2172. fBlocksDisconnected = true;
  2173. }
  2174. // Build list of new blocks to connect.
  2175. std::vector<CBlockIndex*> vpindexToConnect;
  2176. bool fContinue = true;
  2177. int nHeight = pindexFork ? pindexFork->nHeight : -1;
  2178. while (fContinue && nHeight != pindexMostWork->nHeight) {
  2179. // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
  2180. // a few blocks along the way.
  2181. int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
  2182. vpindexToConnect.clear();
  2183. vpindexToConnect.reserve(nTargetHeight - nHeight);
  2184. CBlockIndex *pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
  2185. while (pindexIter && pindexIter->nHeight != nHeight) {
  2186. vpindexToConnect.push_back(pindexIter);
  2187. pindexIter = pindexIter->pprev;
  2188. }
  2189. nHeight = nTargetHeight;
  2190. // Connect new blocks.
  2191. for (CBlockIndex *pindexConnect : reverse_iterate(vpindexToConnect)) {
  2192. if (!ConnectTip(state, chainparams, pindexConnect, pindexConnect == pindexMostWork ? pblock : std::shared_ptr<const CBlock>(), connectTrace, disconnectpool)) {
  2193. if (state.IsInvalid()) {
  2194. // The block violates a consensus rule.
  2195. if (!state.CorruptionPossible())
  2196. InvalidChainFound(vpindexToConnect.back());
  2197. state = CValidationState();
  2198. fInvalidFound = true;
  2199. fContinue = false;
  2200. break;
  2201. } else {
  2202. // A system error occurred (disk space, database error, ...).
  2203. // Make the mempool consistent with the current tip, just in case
  2204. // any observers try to use it before shutdown.
  2205. UpdateMempoolForReorg(disconnectpool, false);
  2206. return false;
  2207. }
  2208. } else {
  2209. PruneBlockIndexCandidates();
  2210. if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
  2211. // We're in a better position than we were. Return temporarily to release the lock.
  2212. fContinue = false;
  2213. break;
  2214. }
  2215. }
  2216. }
  2217. }
  2218. if (fBlocksDisconnected) {
  2219. // If any blocks were disconnected, disconnectpool may be non empty. Add
  2220. // any disconnected transactions back to the mempool.
  2221. UpdateMempoolForReorg(disconnectpool, true);
  2222. }
  2223. mempool.check(pcoinsTip.get());
  2224. // Callbacks/notifications for a new best chain.
  2225. if (fInvalidFound)
  2226. CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
  2227. else
  2228. CheckForkWarningConditions();
  2229. return true;
  2230. }
  2231. static void NotifyHeaderTip() {
  2232. bool fNotify = false;
  2233. bool fInitialBlockDownload = false;
  2234. static CBlockIndex* pindexHeaderOld = nullptr;
  2235. CBlockIndex* pindexHeader = nullptr;
  2236. {
  2237. LOCK(cs_main);
  2238. pindexHeader = pindexBestHeader;
  2239. if (pindexHeader != pindexHeaderOld) {
  2240. fNotify = true;
  2241. fInitialBlockDownload = IsInitialBlockDownload();
  2242. pindexHeaderOld = pindexHeader;
  2243. }
  2244. }
  2245. // Send block tip changed notifications without cs_main
  2246. if (fNotify) {
  2247. uiInterface.NotifyHeaderTip(fInitialBlockDownload, pindexHeader);
  2248. }
  2249. }
  2250. /**
  2251. * Make the best chain active, in multiple steps. The result is either failure
  2252. * or an activated best chain. pblock is either nullptr or a pointer to a block
  2253. * that is already loaded (to avoid loading it again from disk).
  2254. */
  2255. bool CChainState::ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
  2256. // Note that while we're often called here from ProcessNewBlock, this is
  2257. // far from a guarantee. Things in the P2P/RPC will often end up calling
  2258. // us in the middle of ProcessNewBlock - do not assume pblock is set
  2259. // sanely for performance or correctness!
  2260. AssertLockNotHeld(cs_main);
  2261. // ABC maintains a fair degree of expensive-to-calculate internal state
  2262. // because this function periodically releases cs_main so that it does not lock up other threads for too long
  2263. // during large connects - and to allow for e.g. the callback queue to drain
  2264. // we use m_cs_chainstate to enforce mutual exclusion so that only one caller may execute this function at a time
  2265. LOCK(m_cs_chainstate);
  2266. CBlockIndex *pindexMostWork = nullptr;
  2267. CBlockIndex *pindexNewTip = nullptr;
  2268. int nStopAtHeight = gArgs.GetArg("-stopatheight", DEFAULT_STOPATHEIGHT);
  2269. do {
  2270. boost::this_thread::interruption_point();
  2271. if (GetMainSignals().CallbacksPending() > 10) {
  2272. // Block until the validation queue drains. This should largely
  2273. // never happen in normal operation, however may happen during
  2274. // reindex, causing memory blowup if we run too far ahead.
  2275. SyncWithValidationInterfaceQueue();
  2276. }
  2277. {
  2278. LOCK(cs_main);
  2279. CBlockIndex* starting_tip = chainActive.Tip();
  2280. bool blocks_connected = false;
  2281. do {
  2282. // We absolutely may not unlock cs_main until we've made forward progress
  2283. // (with the exception of shutdown due to hardware issues, low disk space, etc).
  2284. ConnectTrace connectTrace(mempool); // Destructed before cs_main is unlocked
  2285. if (pindexMostWork == nullptr) {
  2286. pindexMostWork = FindMostWorkChain();
  2287. }
  2288. // Whether we have anything to do at all.
  2289. if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip()) {
  2290. break;
  2291. }
  2292. bool fInvalidFound = false;
  2293. std::shared_ptr<const CBlock> nullBlockPtr;
  2294. if (!ActivateBestChainStep(state, chainparams, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : nullBlockPtr, fInvalidFound, connectTrace))
  2295. return false;
  2296. blocks_connected = true;
  2297. if (fInvalidFound) {
  2298. // Wipe cache, we may need another branch now.
  2299. pindexMostWork = nullptr;
  2300. }
  2301. pindexNewTip = chainActive.Tip();
  2302. for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) {
  2303. assert(trace.pblock && trace.pindex);
  2304. GetMainSignals().BlockConnected(trace.pblock, trace.pindex, trace.conflictedTxs);
  2305. }
  2306. } while (!chainActive.Tip() || (starting_tip && CBlockIndexWorkComparator()(chainActive.Tip(), starting_tip)));
  2307. if (!blocks_connected) return true;
  2308. const CBlockIndex* pindexFork = chainActive.FindFork(starting_tip);
  2309. bool fInitialDownload = IsInitialBlockDownload();
  2310. // Notify external listeners about the new tip.
  2311. // Enqueue while holding cs_main to ensure that UpdatedBlockTip is called in the order in which blocks are connected
  2312. if (pindexFork != pindexNewTip) {
  2313. // Notify ValidationInterface subscribers
  2314. GetMainSignals().UpdatedBlockTip(pindexNewTip, pindexFork, fInitialDownload);
  2315. // Always notify the UI if a new block tip was connected
  2316. uiInterface.NotifyBlockTip(fInitialDownload, pindexNewTip);
  2317. }
  2318. }
  2319. // When we reach this point, we switched to a new tip (stored in pindexNewTip).
  2320. if (nStopAtHeight && pindexNewTip && pindexNewTip->nHeight >= nStopAtHeight) StartShutdown();
  2321. // We check shutdown only after giving ActivateBestChainStep a chance to run once so that we
  2322. // never shutdown before connecting the genesis block during LoadChainTip(). Previously this
  2323. // caused an assert() failure during shutdown in such cases as the UTXO DB flushing checks
  2324. // that the best block hash is non-null.
  2325. if (ShutdownRequested())
  2326. break;
  2327. } while (pindexNewTip != pindexMostWork);
  2328. CheckBlockIndex(chainparams.GetConsensus());
  2329. // Write changes periodically to disk, after relay.
  2330. if (!FlushStateToDisk(chainparams, state, FLUSH_STATE_PERIODIC)) {
  2331. return false;
  2332. }
  2333. return true;
  2334. }
  2335. bool ActivateBestChain(CValidationState &state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock) {
  2336. return g_chainstate.ActivateBestChain(state, chainparams, std::move(pblock));
  2337. }
  2338. bool CChainState::PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex)
  2339. {
  2340. {
  2341. LOCK(cs_main);
  2342. if (pindex->nChainWork < chainActive.Tip()->nChainWork) {
  2343. // Nothing to do, this block is not at the tip.
  2344. return true;
  2345. }
  2346. if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) {
  2347. // The chain has been extended since the last call, reset the counter.
  2348. nBlockReverseSequenceId = -1;
  2349. }
  2350. nLastPreciousChainwork = chainActive.Tip()->nChainWork;
  2351. setBlockIndexCandidates.erase(pindex);
  2352. pindex->nSequenceId = nBlockReverseSequenceId;
  2353. if (nBlockReverseSequenceId > std::numeric_limits<int32_t>::min()) {
  2354. // We can't keep reducing the counter if somebody really wants to
  2355. // call preciousblock 2**31-1 times on the same set of tips...
  2356. nBlockReverseSequenceId--;
  2357. }
  2358. if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && pindex->nChainTx) {
  2359. setBlockIndexCandidates.insert(pindex);
  2360. PruneBlockIndexCandidates();
  2361. }
  2362. }
  2363. return ActivateBestChain(state, params, std::shared_ptr<const CBlock>());
  2364. }
  2365. bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex) {
  2366. return g_chainstate.PreciousBlock(state, params, pindex);
  2367. }
  2368. bool CChainState::InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex)
  2369. {
  2370. AssertLockHeld(cs_main);
  2371. // We first disconnect backwards and then mark the blocks as invalid.
  2372. // This prevents a case where pruned nodes may fail to invalidateblock
  2373. // and be left unable to start as they have no tip candidates (as there
  2374. // are no blocks that meet the "have data and are not invalid per
  2375. // nStatus" criteria for inclusion in setBlockIndexCandidates).
  2376. bool pindex_was_in_chain = false;
  2377. CBlockIndex *invalid_walk_tip = chainActive.Tip();
  2378. DisconnectedBlockTransactions disconnectpool;
  2379. while (chainActive.Contains(pindex)) {
  2380. pindex_was_in_chain = true;
  2381. // ActivateBestChain considers blocks already in chainActive
  2382. // unconditionally valid already, so force disconnect away from it.
  2383. if (!DisconnectTip(state, chainparams, &disconnectpool)) {
  2384. // It's probably hopeless to try to make the mempool consistent
  2385. // here if DisconnectTip failed, but we can try.
  2386. UpdateMempoolForReorg(disconnectpool, false);
  2387. return false;
  2388. }
  2389. }
  2390. // Now mark the blocks we just disconnected as descendants invalid
  2391. // (note this may not be all descendants).
  2392. while (pindex_was_in_chain && invalid_walk_tip != pindex) {
  2393. invalid_walk_tip->nStatus |= BLOCK_FAILED_CHILD;
  2394. setDirtyBlockIndex.insert(invalid_walk_tip);
  2395. setBlockIndexCandidates.erase(invalid_walk_tip);
  2396. invalid_walk_tip = invalid_walk_tip->pprev;
  2397. }
  2398. // Mark the block itself as invalid.
  2399. pindex->nStatus |= BLOCK_FAILED_VALID;
  2400. setDirtyBlockIndex.insert(pindex);
  2401. setBlockIndexCandidates.erase(pindex);
  2402. g_failed_blocks.insert(pindex);
  2403. // DisconnectTip will add transactions to disconnectpool; try to add these
  2404. // back to the mempool.
  2405. UpdateMempoolForReorg(disconnectpool, true);
  2406. // The resulting new best tip may not be in setBlockIndexCandidates anymore, so
  2407. // add it again.
  2408. BlockMap::iterator it = mapBlockIndex.begin();
  2409. while (it != mapBlockIndex.end()) {
  2410. if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
  2411. setBlockIndexCandidates.insert(it->second);
  2412. }
  2413. it++;
  2414. }
  2415. InvalidChainFound(pindex);
  2416. uiInterface.NotifyBlockTip(IsInitialBlockDownload(), pindex->pprev);
  2417. return true;
  2418. }
  2419. bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex) {
  2420. return g_chainstate.InvalidateBlock(state, chainparams, pindex);
  2421. }
  2422. bool CChainState::ResetBlockFailureFlags(CBlockIndex *pindex) {
  2423. AssertLockHeld(cs_main);
  2424. int nHeight = pindex->nHeight;
  2425. // Remove the invalidity flag from this block and all its descendants.
  2426. BlockMap::iterator it = mapBlockIndex.begin();
  2427. while (it != mapBlockIndex.end()) {
  2428. if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
  2429. it->second->nStatus &= ~BLOCK_FAILED_MASK;
  2430. setDirtyBlockIndex.insert(it->second);
  2431. if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
  2432. setBlockIndexCandidates.insert(it->second);
  2433. }
  2434. if (it->second == pindexBestInvalid) {
  2435. // Reset invalid block marker if it was pointing to one of those.
  2436. pindexBestInvalid = nullptr;
  2437. }
  2438. g_failed_blocks.erase(it->second);
  2439. }
  2440. it++;
  2441. }
  2442. // Remove the invalidity flag from all ancestors too.
  2443. while (pindex != nullptr) {
  2444. if (pindex->nStatus & BLOCK_FAILED_MASK) {
  2445. pindex->nStatus &= ~BLOCK_FAILED_MASK;
  2446. setDirtyBlockIndex.insert(pindex);
  2447. g_failed_blocks.erase(pindex);
  2448. }
  2449. pindex = pindex->pprev;
  2450. }
  2451. return true;
  2452. }
  2453. bool ResetBlockFailureFlags(CBlockIndex *pindex) {
  2454. return g_chainstate.ResetBlockFailureFlags(pindex);
  2455. }
  2456. CBlockIndex* CChainState::AddToBlockIndex(const CBlockHeader& block)
  2457. {
  2458. // Check for duplicate
  2459. uint256 hash = block.GetHash();
  2460. BlockMap::iterator it = mapBlockIndex.find(hash);
  2461. if (it != mapBlockIndex.end())
  2462. return it->second;
  2463. // Construct new block index object
  2464. CBlockIndex* pindexNew = new CBlockIndex(block);
  2465. // We assign the sequence id to blocks only when the full data is available,
  2466. // to avoid miners withholding blocks but broadcasting headers, to get a
  2467. // competitive advantage.
  2468. pindexNew->nSequenceId = 0;
  2469. BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
  2470. pindexNew->phashBlock = &((*mi).first);
  2471. BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
  2472. if (miPrev != mapBlockIndex.end())
  2473. {
  2474. pindexNew->pprev = (*miPrev).second;
  2475. pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
  2476. pindexNew->BuildSkip();
  2477. }
  2478. pindexNew->nTimeMax = (pindexNew->pprev ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime) : pindexNew->nTime);
  2479. pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
  2480. pindexNew->RaiseValidity(BLOCK_VALID_TREE);
  2481. if (pindexBestHeader == nullptr || pindexBestHeader->nChainWork < pindexNew->nChainWork)
  2482. pindexBestHeader = pindexNew;
  2483. setDirtyBlockIndex.insert(pindexNew);
  2484. return pindexNew;
  2485. }
  2486. /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
  2487. bool CChainState::ReceivedBlockTransactions(const CBlock &block, CValidationState& state, CBlockIndex *pindexNew, const CDiskBlockPos& pos, const Consensus::Params& consensusParams)
  2488. {
  2489. pindexNew->nTx = block.vtx.size();
  2490. pindexNew->nChainTx = 0;
  2491. pindexNew->nFile = pos.nFile;
  2492. pindexNew->nDataPos = pos.nPos;
  2493. pindexNew->nUndoPos = 0;
  2494. pindexNew->nStatus |= BLOCK_HAVE_DATA;
  2495. if (IsWitnessEnabled(pindexNew->pprev, consensusParams)) {
  2496. pindexNew->nStatus |= BLOCK_OPT_WITNESS;
  2497. }
  2498. pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
  2499. setDirtyBlockIndex.insert(pindexNew);
  2500. if (pindexNew->pprev == nullptr || pindexNew->pprev->nChainTx) {
  2501. // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
  2502. std::deque<CBlockIndex*> queue;
  2503. queue.push_back(pindexNew);
  2504. // Recursively process any descendant blocks that now may be eligible to be connected.
  2505. while (!queue.empty()) {
  2506. CBlockIndex *pindex = queue.front();
  2507. queue.pop_front();
  2508. pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
  2509. {
  2510. LOCK(cs_nBlockSequenceId);
  2511. pindex->nSequenceId = nBlockSequenceId++;
  2512. }
  2513. if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
  2514. setBlockIndexCandidates.insert(pindex);
  2515. }
  2516. std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
  2517. while (range.first != range.second) {
  2518. std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
  2519. queue.push_back(it->second);
  2520. range.first++;
  2521. mapBlocksUnlinked.erase(it);
  2522. }
  2523. }
  2524. } else {
  2525. if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
  2526. mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
  2527. }
  2528. }
  2529. return true;
  2530. }
  2531. static bool FindBlockPos(CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
  2532. {
  2533. LOCK(cs_LastBlockFile);
  2534. unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
  2535. if (vinfoBlockFile.size() <= nFile) {
  2536. vinfoBlockFile.resize(nFile + 1);
  2537. }
  2538. if (!fKnown) {
  2539. while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
  2540. nFile++;
  2541. if (vinfoBlockFile.size() <= nFile) {
  2542. vinfoBlockFile.resize(nFile + 1);
  2543. }
  2544. }
  2545. pos.nFile = nFile;
  2546. pos.nPos = vinfoBlockFile[nFile].nSize;
  2547. }
  2548. if ((int)nFile != nLastBlockFile) {
  2549. if (!fKnown) {
  2550. LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, vinfoBlockFile[nLastBlockFile].ToString());
  2551. }
  2552. FlushBlockFile(!fKnown);
  2553. nLastBlockFile = nFile;
  2554. }
  2555. vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
  2556. if (fKnown)
  2557. vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
  2558. else
  2559. vinfoBlockFile[nFile].nSize += nAddSize;
  2560. if (!fKnown) {
  2561. unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
  2562. unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
  2563. if (nNewChunks > nOldChunks) {
  2564. if (fPruneMode)
  2565. fCheckForPruning = true;
  2566. if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
  2567. FILE *file = OpenBlockFile(pos);
  2568. if (file) {
  2569. LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
  2570. AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
  2571. fclose(file);
  2572. }
  2573. }
  2574. else
  2575. return error("out of disk space");
  2576. }
  2577. }
  2578. setDirtyFileInfo.insert(nFile);
  2579. return true;
  2580. }
  2581. static bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
  2582. {
  2583. pos.nFile = nFile;
  2584. LOCK(cs_LastBlockFile);
  2585. unsigned int nNewSize;
  2586. pos.nPos = vinfoBlockFile[nFile].nUndoSize;
  2587. nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
  2588. setDirtyFileInfo.insert(nFile);
  2589. unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
  2590. unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
  2591. if (nNewChunks > nOldChunks) {
  2592. if (fPruneMode)
  2593. fCheckForPruning = true;
  2594. if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
  2595. FILE *file = OpenUndoFile(pos);
  2596. if (file) {
  2597. LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
  2598. AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
  2599. fclose(file);
  2600. }
  2601. }
  2602. else
  2603. return state.Error("out of disk space");
  2604. }
  2605. return true;
  2606. }
  2607. static bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
  2608. {
  2609. // Check proof of work matches claimed amount
  2610. if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
  2611. return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
  2612. return true;
  2613. }
  2614. bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
  2615. {
  2616. // These are checks that are independent of context.
  2617. if (block.fChecked)
  2618. return true;
  2619. // Check that the header is valid (particularly PoW). This is mostly
  2620. // redundant with the call in AcceptBlockHeader.
  2621. if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
  2622. return false;
  2623. // Check the merkle root.
  2624. if (fCheckMerkleRoot) {
  2625. bool mutated;
  2626. uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
  2627. if (block.hashMerkleRoot != hashMerkleRoot2)
  2628. return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot", true, "hashMerkleRoot mismatch");
  2629. // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
  2630. // of transactions in a block without affecting the merkle root of a block,
  2631. // while still invalidating it.
  2632. if (mutated)
  2633. return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate", true, "duplicate transaction");
  2634. }
  2635. // All potential-corruption validation must be done before we do any
  2636. // transaction validation, as otherwise we may mark the header as invalid
  2637. // because we receive the wrong transactions for it.
  2638. // Note that witness malleability is checked in ContextualCheckBlock, so no
  2639. // checks that use witness data may be performed here.
  2640. // Size limits
  2641. if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
  2642. return state.DoS(100, false, REJECT_INVALID, "bad-blk-length", false, "size limits failed");
  2643. // First transaction must be coinbase, the rest must not be
  2644. if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
  2645. return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false, "first tx is not coinbase");
  2646. for (unsigned int i = 1; i < block.vtx.size(); i++)
  2647. if (block.vtx[i]->IsCoinBase())
  2648. return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple", false, "more than one coinbase");
  2649. // Check transactions
  2650. for (const auto& tx : block.vtx)
  2651. if (!CheckTransaction(*tx, state, false))
  2652. return state.Invalid(false, state.GetRejectCode(), state.GetRejectReason(),
  2653. strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
  2654. unsigned int nSigOps = 0;
  2655. for (const auto& tx : block.vtx)
  2656. {
  2657. nSigOps += GetLegacySigOpCount(*tx);
  2658. }
  2659. if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
  2660. return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false, "out-of-bounds SigOpCount");
  2661. if (fCheckPOW && fCheckMerkleRoot)
  2662. block.fChecked = true;
  2663. return true;
  2664. }
  2665. bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params)
  2666. {
  2667. LOCK(cs_main);
  2668. return (VersionBitsState(pindexPrev, params, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE);
  2669. }
  2670. // Compute at which vout of the block's coinbase transaction the witness
  2671. // commitment occurs, or -1 if not found.
  2672. static int GetWitnessCommitmentIndex(const CBlock& block)
  2673. {
  2674. int commitpos = -1;
  2675. if (!block.vtx.empty()) {
  2676. for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
  2677. if (block.vtx[0]->vout[o].scriptPubKey.size() >= 38 && block.vtx[0]->vout[o].scriptPubKey[0] == OP_RETURN && block.vtx[0]->vout[o].scriptPubKey[1] == 0x24 && block.vtx[0]->vout[o].scriptPubKey[2] == 0xaa && block.vtx[0]->vout[o].scriptPubKey[3] == 0x21 && block.vtx[0]->vout[o].scriptPubKey[4] == 0xa9 && block.vtx[0]->vout[o].scriptPubKey[5] == 0xed) {
  2678. commitpos = o;
  2679. }
  2680. }
  2681. }
  2682. return commitpos;
  2683. }
  2684. void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
  2685. {
  2686. int commitpos = GetWitnessCommitmentIndex(block);
  2687. static const std::vector<unsigned char> nonce(32, 0x00);
  2688. if (commitpos != -1 && IsWitnessEnabled(pindexPrev, consensusParams) && !block.vtx[0]->HasWitness()) {
  2689. CMutableTransaction tx(*block.vtx[0]);
  2690. tx.vin[0].scriptWitness.stack.resize(1);
  2691. tx.vin[0].scriptWitness.stack[0] = nonce;
  2692. block.vtx[0] = MakeTransactionRef(std::move(tx));
  2693. }
  2694. }
  2695. std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams)
  2696. {
  2697. std::vector<unsigned char> commitment;
  2698. int commitpos = GetWitnessCommitmentIndex(block);
  2699. std::vector<unsigned char> ret(32, 0x00);
  2700. if (consensusParams.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) {
  2701. if (commitpos == -1) {
  2702. uint256 witnessroot = BlockWitnessMerkleRoot(block, nullptr);
  2703. CHash256().Write(witnessroot.begin(), 32).Write(ret.data(), 32).Finalize(witnessroot.begin());
  2704. CTxOut out;
  2705. out.nValue = 0;
  2706. out.scriptPubKey.resize(38);
  2707. out.scriptPubKey[0] = OP_RETURN;
  2708. out.scriptPubKey[1] = 0x24;
  2709. out.scriptPubKey[2] = 0xaa;
  2710. out.scriptPubKey[3] = 0x21;
  2711. out.scriptPubKey[4] = 0xa9;
  2712. out.scriptPubKey[5] = 0xed;
  2713. memcpy(&out.scriptPubKey[6], witnessroot.begin(), 32);
  2714. commitment = std::vector<unsigned char>(out.scriptPubKey.begin(), out.scriptPubKey.end());
  2715. CMutableTransaction tx(*block.vtx[0]);
  2716. tx.vout.push_back(out);
  2717. block.vtx[0] = MakeTransactionRef(std::move(tx));
  2718. }
  2719. }
  2720. UpdateUncommittedBlockStructures(block, pindexPrev, consensusParams);
  2721. return commitment;
  2722. }
  2723. /** Context-dependent validity checks.
  2724. * By "context", we mean only the previous block headers, but not the UTXO
  2725. * set; UTXO-related validity checks are done in ConnectBlock().
  2726. * NOTE: This function is not currently invoked by ConnectBlock(), so we
  2727. * should consider upgrade issues if we change which consensus rules are
  2728. * enforced in this function (eg by adding a new consensus rule). See comment
  2729. * in ConnectBlock().
  2730. * Note that -reindex-chainstate skips the validation that happens here!
  2731. */
  2732. static bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& params, const CBlockIndex* pindexPrev, int64_t nAdjustedTime)
  2733. {
  2734. assert(pindexPrev != nullptr);
  2735. const int nHeight = pindexPrev->nHeight + 1;
  2736. // Check proof of work
  2737. const Consensus::Params& consensusParams = params.GetConsensus();
  2738. if (block.nBits != GetNextWorkRequired(pindexPrev, &block, consensusParams))
  2739. return state.DoS(100, false, REJECT_INVALID, "bad-diffbits", false, "incorrect proof of work");
  2740. // Check against checkpoints
  2741. if (fCheckpointsEnabled) {
  2742. // Don't accept any forks from the main chain prior to last checkpoint.
  2743. // GetLastCheckpoint finds the last checkpoint in MapCheckpoints that's in our
  2744. // MapBlockIndex.
  2745. CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(params.Checkpoints());
  2746. if (pcheckpoint && nHeight < pcheckpoint->nHeight)
  2747. return state.DoS(100, error("%s: forked chain older than last checkpoint (height %d)", __func__, nHeight), REJECT_CHECKPOINT, "bad-fork-prior-to-checkpoint");
  2748. }
  2749. // Check timestamp against prev
  2750. if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
  2751. return state.Invalid(false, REJECT_INVALID, "time-too-old", "block's timestamp is too early");
  2752. // Check timestamp
  2753. if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
  2754. return state.Invalid(false, REJECT_INVALID, "time-too-new", "block timestamp too far in the future");
  2755. // Reject outdated version blocks when 95% (75% on testnet) of the network has upgraded:
  2756. // check for version 2, 3 and 4 upgrades
  2757. if((block.nVersion < 2 && nHeight >= consensusParams.BIP34Height) ||
  2758. (block.nVersion < 3 && nHeight >= consensusParams.BIP66Height) ||
  2759. (block.nVersion < 4 && nHeight >= consensusParams.BIP65Height))
  2760. return state.Invalid(false, REJECT_OBSOLETE, strprintf("bad-version(0x%08x)", block.nVersion),
  2761. strprintf("rejected nVersion=0x%08x block", block.nVersion));
  2762. return true;
  2763. }
  2764. /** NOTE: This function is not currently invoked by ConnectBlock(), so we
  2765. * should consider upgrade issues if we change which consensus rules are
  2766. * enforced in this function (eg by adding a new consensus rule). See comment
  2767. * in ConnectBlock().
  2768. * Note that -reindex-chainstate skips the validation that happens here!
  2769. */
  2770. static bool ContextualCheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
  2771. {
  2772. const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1;
  2773. // Start enforcing BIP113 (Median Time Past) using versionbits logic.
  2774. int nLockTimeFlags = 0;
  2775. if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_CSV, versionbitscache) == THRESHOLD_ACTIVE) {
  2776. nLockTimeFlags |= LOCKTIME_MEDIAN_TIME_PAST;
  2777. }
  2778. int64_t nLockTimeCutoff = (nLockTimeFlags & LOCKTIME_MEDIAN_TIME_PAST)
  2779. ? pindexPrev->GetMedianTimePast()
  2780. : block.GetBlockTime();
  2781. // Check that all transactions are finalized
  2782. for (const auto& tx : block.vtx) {
  2783. if (!IsFinalTx(*tx, nHeight, nLockTimeCutoff)) {
  2784. return state.DoS(10, false, REJECT_INVALID, "bad-txns-nonfinal", false, "non-final transaction");
  2785. }
  2786. }
  2787. // Enforce rule that the coinbase starts with serialized block height
  2788. if (nHeight >= consensusParams.BIP34Height)
  2789. {
  2790. CScript expect = CScript() << nHeight;
  2791. if (block.vtx[0]->vin[0].scriptSig.size() < expect.size() ||
  2792. !std::equal(expect.begin(), expect.end(), block.vtx[0]->vin[0].scriptSig.begin())) {
  2793. return state.DoS(100, false, REJECT_INVALID, "bad-cb-height", false, "block height mismatch in coinbase");
  2794. }
  2795. }
  2796. // Validation for witness commitments.
  2797. // * We compute the witness hash (which is the hash including witnesses) of all the block's transactions, except the
  2798. // coinbase (where 0x0000....0000 is used instead).
  2799. // * The coinbase scriptWitness is a stack of a single 32-byte vector, containing a witness nonce (unconstrained).
  2800. // * We build a merkle tree with all those witness hashes as leaves (similar to the hashMerkleRoot in the block header).
  2801. // * There must be at least one output whose scriptPubKey is a single 36-byte push, the first 4 bytes of which are
  2802. // {0xaa, 0x21, 0xa9, 0xed}, and the following 32 bytes are SHA256^2(witness root, witness nonce). In case there are
  2803. // multiple, the last one is used.
  2804. bool fHaveWitness = false;
  2805. if (VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache) == THRESHOLD_ACTIVE) {
  2806. int commitpos = GetWitnessCommitmentIndex(block);
  2807. if (commitpos != -1) {
  2808. bool malleated = false;
  2809. uint256 hashWitness = BlockWitnessMerkleRoot(block, &malleated);
  2810. // The malleation check is ignored; as the transaction tree itself
  2811. // already does not permit it, it is impossible to trigger in the
  2812. // witness tree.
  2813. if (block.vtx[0]->vin[0].scriptWitness.stack.size() != 1 || block.vtx[0]->vin[0].scriptWitness.stack[0].size() != 32) {
  2814. return state.DoS(100, false, REJECT_INVALID, "bad-witness-nonce-size", true, strprintf("%s : invalid witness nonce size", __func__));
  2815. }
  2816. CHash256().Write(hashWitness.begin(), 32).Write(&block.vtx[0]->vin[0].scriptWitness.stack[0][0], 32).Finalize(hashWitness.begin());
  2817. if (memcmp(hashWitness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {
  2818. return state.DoS(100, false, REJECT_INVALID, "bad-witness-merkle-match", true, strprintf("%s : witness merkle commitment mismatch", __func__));
  2819. }
  2820. fHaveWitness = true;
  2821. }
  2822. }
  2823. // No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam
  2824. if (!fHaveWitness) {
  2825. for (const auto& tx : block.vtx) {
  2826. if (tx->HasWitness()) {
  2827. return state.DoS(100, false, REJECT_INVALID, "unexpected-witness", true, strprintf("%s : unexpected witness data found", __func__));
  2828. }
  2829. }
  2830. }
  2831. // After the coinbase witness nonce and commitment are verified,
  2832. // we can check if the block weight passes (before we've checked the
  2833. // coinbase witness, it would be possible for the weight to be too
  2834. // large by filling up the coinbase witness, which doesn't change
  2835. // the block hash, so we couldn't mark the block as permanently
  2836. // failed).
  2837. if (GetBlockWeight(block) > MAX_BLOCK_WEIGHT) {
  2838. return state.DoS(100, false, REJECT_INVALID, "bad-blk-weight", false, strprintf("%s : weight limit failed", __func__));
  2839. }
  2840. return true;
  2841. }
  2842. bool CChainState::AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex)
  2843. {
  2844. AssertLockHeld(cs_main);
  2845. // Check for duplicate
  2846. uint256 hash = block.GetHash();
  2847. BlockMap::iterator miSelf = mapBlockIndex.find(hash);
  2848. CBlockIndex *pindex = nullptr;
  2849. if (hash != chainparams.GetConsensus().hashGenesisBlock) {
  2850. if (miSelf != mapBlockIndex.end()) {
  2851. // Block header is already known.
  2852. pindex = miSelf->second;
  2853. if (ppindex)
  2854. *ppindex = pindex;
  2855. if (pindex->nStatus & BLOCK_FAILED_MASK)
  2856. return state.Invalid(error("%s: block %s is marked invalid", __func__, hash.ToString()), 0, "duplicate");
  2857. return true;
  2858. }
  2859. if (!CheckBlockHeader(block, state, chainparams.GetConsensus()))
  2860. return error("%s: Consensus::CheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
  2861. // Get prev block index
  2862. CBlockIndex* pindexPrev = nullptr;
  2863. BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
  2864. if (mi == mapBlockIndex.end())
  2865. return state.DoS(10, error("%s: prev block not found", __func__), 0, "prev-blk-not-found");
  2866. pindexPrev = (*mi).second;
  2867. if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
  2868. return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
  2869. if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
  2870. return error("%s: Consensus::ContextualCheckBlockHeader: %s, %s", __func__, hash.ToString(), FormatStateMessage(state));
  2871. if (!pindexPrev->IsValid(BLOCK_VALID_SCRIPTS)) {
  2872. for (const CBlockIndex* failedit : g_failed_blocks) {
  2873. if (pindexPrev->GetAncestor(failedit->nHeight) == failedit) {
  2874. assert(failedit->nStatus & BLOCK_FAILED_VALID);
  2875. CBlockIndex* invalid_walk = pindexPrev;
  2876. while (invalid_walk != failedit) {
  2877. invalid_walk->nStatus |= BLOCK_FAILED_CHILD;
  2878. setDirtyBlockIndex.insert(invalid_walk);
  2879. invalid_walk = invalid_walk->pprev;
  2880. }
  2881. return state.DoS(100, error("%s: prev block invalid", __func__), REJECT_INVALID, "bad-prevblk");
  2882. }
  2883. }
  2884. }
  2885. }
  2886. if (pindex == nullptr)
  2887. pindex = AddToBlockIndex(block);
  2888. if (ppindex)
  2889. *ppindex = pindex;
  2890. CheckBlockIndex(chainparams.GetConsensus());
  2891. return true;
  2892. }
  2893. // Exposed wrapper for AcceptBlockHeader
  2894. bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& headers, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex, CBlockHeader *first_invalid)
  2895. {
  2896. if (first_invalid != nullptr) first_invalid->SetNull();
  2897. {
  2898. LOCK(cs_main);
  2899. for (const CBlockHeader& header : headers) {
  2900. CBlockIndex *pindex = nullptr; // Use a temp pindex instead of ppindex to avoid a const_cast
  2901. if (!g_chainstate.AcceptBlockHeader(header, state, chainparams, &pindex)) {
  2902. if (first_invalid) *first_invalid = header;
  2903. return false;
  2904. }
  2905. if (ppindex) {
  2906. *ppindex = pindex;
  2907. }
  2908. }
  2909. }
  2910. NotifyHeaderTip();
  2911. return true;
  2912. }
  2913. /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
  2914. static CDiskBlockPos SaveBlockToDisk(const CBlock& block, int nHeight, const CChainParams& chainparams, const CDiskBlockPos* dbp) {
  2915. unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
  2916. CDiskBlockPos blockPos;
  2917. if (dbp != nullptr)
  2918. blockPos = *dbp;
  2919. if (!FindBlockPos(blockPos, nBlockSize+8, nHeight, block.GetBlockTime(), dbp != nullptr)) {
  2920. error("%s: FindBlockPos failed", __func__);
  2921. return CDiskBlockPos();
  2922. }
  2923. if (dbp == nullptr) {
  2924. if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) {
  2925. AbortNode("Failed to write block");
  2926. return CDiskBlockPos();
  2927. }
  2928. }
  2929. return blockPos;
  2930. }
  2931. /** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
  2932. bool CChainState::AcceptBlock(const std::shared_ptr<const CBlock>& pblock, CValidationState& state, const CChainParams& chainparams, CBlockIndex** ppindex, bool fRequested, const CDiskBlockPos* dbp, bool* fNewBlock)
  2933. {
  2934. const CBlock& block = *pblock;
  2935. if (fNewBlock) *fNewBlock = false;
  2936. AssertLockHeld(cs_main);
  2937. CBlockIndex *pindexDummy = nullptr;
  2938. CBlockIndex *&pindex = ppindex ? *ppindex : pindexDummy;
  2939. if (!AcceptBlockHeader(block, state, chainparams, &pindex))
  2940. return false;
  2941. // Try to process all requested blocks that we don't have, but only
  2942. // process an unrequested block if it's new and has enough work to
  2943. // advance our tip, and isn't too many blocks ahead.
  2944. bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA;
  2945. bool fHasMoreOrSameWork = (chainActive.Tip() ? pindex->nChainWork >= chainActive.Tip()->nChainWork : true);
  2946. // Blocks that are too out-of-order needlessly limit the effectiveness of
  2947. // pruning, because pruning will not delete block files that contain any
  2948. // blocks which are too close in height to the tip. Apply this test
  2949. // regardless of whether pruning is enabled; it should generally be safe to
  2950. // not process unrequested blocks.
  2951. bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP));
  2952. // TODO: Decouple this function from the block download logic by removing fRequested
  2953. // This requires some new chain data structure to efficiently look up if a
  2954. // block is in a chain leading to a candidate for best tip, despite not
  2955. // being such a candidate itself.
  2956. // TODO: deal better with return value and error conditions for duplicate
  2957. // and unrequested blocks.
  2958. if (fAlreadyHave) return true;
  2959. if (!fRequested) { // If we didn't ask for it:
  2960. if (pindex->nTx != 0) return true; // This is a previously-processed block that was pruned
  2961. if (!fHasMoreOrSameWork) return true; // Don't process less-work chains
  2962. if (fTooFarAhead) return true; // Block height is too high
  2963. // Protect against DoS attacks from low-work chains.
  2964. // If our tip is behind, a peer could try to send us
  2965. // low-work blocks on a fake chain that we would never
  2966. // request; don't process these.
  2967. if (pindex->nChainWork < nMinimumChainWork) return true;
  2968. }
  2969. if (fNewBlock) *fNewBlock = true;
  2970. if (!CheckBlock(block, state, chainparams.GetConsensus()) ||
  2971. !ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindex->pprev)) {
  2972. if (state.IsInvalid() && !state.CorruptionPossible()) {
  2973. pindex->nStatus |= BLOCK_FAILED_VALID;
  2974. setDirtyBlockIndex.insert(pindex);
  2975. }
  2976. return error("%s: %s", __func__, FormatStateMessage(state));
  2977. }
  2978. // Header is valid/has work, merkle tree and segwit merkle tree are good...RELAY NOW
  2979. // (but if it does not build on our best tip, let the SendMessages loop relay it)
  2980. if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev)
  2981. GetMainSignals().NewPoWValidBlock(pindex, pblock);
  2982. // Write block to history file
  2983. try {
  2984. CDiskBlockPos blockPos = SaveBlockToDisk(block, pindex->nHeight, chainparams, dbp);
  2985. if (blockPos.IsNull()) {
  2986. state.Error(strprintf("%s: Failed to find position to write new block to disk", __func__));
  2987. return false;
  2988. }
  2989. if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
  2990. return error("AcceptBlock(): ReceivedBlockTransactions failed");
  2991. } catch (const std::runtime_error& e) {
  2992. return AbortNode(state, std::string("System error: ") + e.what());
  2993. }
  2994. if (fCheckForPruning)
  2995. FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE); // we just allocated more disk space for block files
  2996. CheckBlockIndex(chainparams.GetConsensus());
  2997. return true;
  2998. }
  2999. bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool *fNewBlock)
  3000. {
  3001. AssertLockNotHeld(cs_main);
  3002. {
  3003. CBlockIndex *pindex = nullptr;
  3004. if (fNewBlock) *fNewBlock = false;
  3005. CValidationState state;
  3006. // Ensure that CheckBlock() passes before calling AcceptBlock, as
  3007. // belt-and-suspenders.
  3008. bool ret = CheckBlock(*pblock, state, chainparams.GetConsensus());
  3009. LOCK(cs_main);
  3010. if (ret) {
  3011. // Store to disk
  3012. ret = g_chainstate.AcceptBlock(pblock, state, chainparams, &pindex, fForceProcessing, nullptr, fNewBlock);
  3013. }
  3014. if (!ret) {
  3015. GetMainSignals().BlockChecked(*pblock, state);
  3016. return error("%s: AcceptBlock FAILED (%s)", __func__, state.GetDebugMessage());
  3017. }
  3018. }
  3019. NotifyHeaderTip();
  3020. CValidationState state; // Only used to report errors, not invalidity - ignore it
  3021. if (!g_chainstate.ActivateBestChain(state, chainparams, pblock))
  3022. return error("%s: ActivateBestChain failed", __func__);
  3023. return true;
  3024. }
  3025. bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
  3026. {
  3027. AssertLockHeld(cs_main);
  3028. assert(pindexPrev && pindexPrev == chainActive.Tip());
  3029. CCoinsViewCache viewNew(pcoinsTip.get());
  3030. CBlockIndex indexDummy(block);
  3031. indexDummy.pprev = pindexPrev;
  3032. indexDummy.nHeight = pindexPrev->nHeight + 1;
  3033. // NOTE: CheckBlockHeader is called by CheckBlock
  3034. if (!ContextualCheckBlockHeader(block, state, chainparams, pindexPrev, GetAdjustedTime()))
  3035. return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, FormatStateMessage(state));
  3036. if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
  3037. return error("%s: Consensus::CheckBlock: %s", __func__, FormatStateMessage(state));
  3038. if (!ContextualCheckBlock(block, state, chainparams.GetConsensus(), pindexPrev))
  3039. return error("%s: Consensus::ContextualCheckBlock: %s", __func__, FormatStateMessage(state));
  3040. if (!g_chainstate.ConnectBlock(block, state, &indexDummy, viewNew, chainparams, true))
  3041. return false;
  3042. assert(state.IsValid());
  3043. return true;
  3044. }
  3045. /**
  3046. * BLOCK PRUNING CODE
  3047. */
  3048. /* Calculate the amount of disk space the block & undo files currently use */
  3049. uint64_t CalculateCurrentUsage()
  3050. {
  3051. LOCK(cs_LastBlockFile);
  3052. uint64_t retval = 0;
  3053. for (const CBlockFileInfo &file : vinfoBlockFile) {
  3054. retval += file.nSize + file.nUndoSize;
  3055. }
  3056. return retval;
  3057. }
  3058. /* Prune a block file (modify associated database entries)*/
  3059. void PruneOneBlockFile(const int fileNumber)
  3060. {
  3061. LOCK(cs_LastBlockFile);
  3062. for (const auto& entry : mapBlockIndex) {
  3063. CBlockIndex* pindex = entry.second;
  3064. if (pindex->nFile == fileNumber) {
  3065. pindex->nStatus &= ~BLOCK_HAVE_DATA;
  3066. pindex->nStatus &= ~BLOCK_HAVE_UNDO;
  3067. pindex->nFile = 0;
  3068. pindex->nDataPos = 0;
  3069. pindex->nUndoPos = 0;
  3070. setDirtyBlockIndex.insert(pindex);
  3071. // Prune from mapBlocksUnlinked -- any block we prune would have
  3072. // to be downloaded again in order to consider its chain, at which
  3073. // point it would be considered as a candidate for
  3074. // mapBlocksUnlinked or setBlockIndexCandidates.
  3075. std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex->pprev);
  3076. while (range.first != range.second) {
  3077. std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it = range.first;
  3078. range.first++;
  3079. if (_it->second == pindex) {
  3080. mapBlocksUnlinked.erase(_it);
  3081. }
  3082. }
  3083. }
  3084. }
  3085. vinfoBlockFile[fileNumber].SetNull();
  3086. setDirtyFileInfo.insert(fileNumber);
  3087. }
  3088. void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune)
  3089. {
  3090. for (std::set<int>::iterator it = setFilesToPrune.begin(); it != setFilesToPrune.end(); ++it) {
  3091. CDiskBlockPos pos(*it, 0);
  3092. fs::remove(GetBlockPosFilename(pos, "blk"));
  3093. fs::remove(GetBlockPosFilename(pos, "rev"));
  3094. LogPrintf("Prune: %s deleted blk/rev (%05u)\n", __func__, *it);
  3095. }
  3096. }
  3097. /* Calculate the block/rev files to delete based on height specified by user with RPC command pruneblockchain */
  3098. static void FindFilesToPruneManual(std::set<int>& setFilesToPrune, int nManualPruneHeight)
  3099. {
  3100. assert(fPruneMode && nManualPruneHeight > 0);
  3101. LOCK2(cs_main, cs_LastBlockFile);
  3102. if (chainActive.Tip() == nullptr)
  3103. return;
  3104. // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip)
  3105. unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP);
  3106. int count=0;
  3107. for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
  3108. if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
  3109. continue;
  3110. PruneOneBlockFile(fileNumber);
  3111. setFilesToPrune.insert(fileNumber);
  3112. count++;
  3113. }
  3114. LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n", nLastBlockWeCanPrune, count);
  3115. }
  3116. /* This function is called from the RPC code for pruneblockchain */
  3117. void PruneBlockFilesManual(int nManualPruneHeight)
  3118. {
  3119. CValidationState state;
  3120. const CChainParams& chainparams = Params();
  3121. FlushStateToDisk(chainparams, state, FLUSH_STATE_NONE, nManualPruneHeight);
  3122. }
  3123. /**
  3124. * Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a user-defined target.
  3125. * The user sets the target (in MB) on the command line or in config file. This will be run on startup and whenever new
  3126. * space is allocated in a block or undo file, staying below the target. Changing back to unpruned requires a reindex
  3127. * (which in this case means the blockchain must be re-downloaded.)
  3128. *
  3129. * Pruning functions are called from FlushStateToDisk when the global fCheckForPruning flag has been set.
  3130. * Block and undo files are deleted in lock-step (when blk00003.dat is deleted, so is rev00003.dat.)
  3131. * Pruning cannot take place until the longest chain is at least a certain length (100000 on mainnet, 1000 on testnet, 1000 on regtest).
  3132. * Pruning will never delete a block within a defined distance (currently 288) from the active chain's tip.
  3133. * The block index is updated by unsetting HAVE_DATA and HAVE_UNDO for any blocks that were stored in the deleted files.
  3134. * A db flag records the fact that at least some block files have been pruned.
  3135. *
  3136. * @param[out] setFilesToPrune The set of file indices that can be unlinked will be returned
  3137. */
  3138. static void FindFilesToPrune(std::set<int>& setFilesToPrune, uint64_t nPruneAfterHeight)
  3139. {
  3140. LOCK2(cs_main, cs_LastBlockFile);
  3141. if (chainActive.Tip() == nullptr || nPruneTarget == 0) {
  3142. return;
  3143. }
  3144. if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) {
  3145. return;
  3146. }
  3147. unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP;
  3148. uint64_t nCurrentUsage = CalculateCurrentUsage();
  3149. // We don't check to prune until after we've allocated new space for files
  3150. // So we should leave a buffer under our target to account for another allocation
  3151. // before the next pruning.
  3152. uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
  3153. uint64_t nBytesToPrune;
  3154. int count=0;
  3155. if (nCurrentUsage + nBuffer >= nPruneTarget) {
  3156. for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) {
  3157. nBytesToPrune = vinfoBlockFile[fileNumber].nSize + vinfoBlockFile[fileNumber].nUndoSize;
  3158. if (vinfoBlockFile[fileNumber].nSize == 0)
  3159. continue;
  3160. if (nCurrentUsage + nBuffer < nPruneTarget) // are we below our target?
  3161. break;
  3162. // don't prune files that could have a block within MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
  3163. if (vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune)
  3164. continue;
  3165. PruneOneBlockFile(fileNumber);
  3166. // Queue up the files for removal
  3167. setFilesToPrune.insert(fileNumber);
  3168. nCurrentUsage -= nBytesToPrune;
  3169. count++;
  3170. }
  3171. }
  3172. LogPrint(BCLog::PRUNE, "Prune: target=%dMiB actual=%dMiB diff=%dMiB max_prune_height=%d removed %d blk/rev pairs\n",
  3173. nPruneTarget/1024/1024, nCurrentUsage/1024/1024,
  3174. ((int64_t)nPruneTarget - (int64_t)nCurrentUsage)/1024/1024,
  3175. nLastBlockWeCanPrune, count);
  3176. }
  3177. bool CheckDiskSpace(uint64_t nAdditionalBytes)
  3178. {
  3179. uint64_t nFreeBytesAvailable = fs::space(GetDataDir()).available;
  3180. // Check for nMinDiskSpace bytes (currently 50MB)
  3181. if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
  3182. return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
  3183. return true;
  3184. }
  3185. static FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
  3186. {
  3187. if (pos.IsNull())
  3188. return nullptr;
  3189. fs::path path = GetBlockPosFilename(pos, prefix);
  3190. fs::create_directories(path.parent_path());
  3191. FILE* file = fsbridge::fopen(path, fReadOnly ? "rb": "rb+");
  3192. if (!file && !fReadOnly)
  3193. file = fsbridge::fopen(path, "wb+");
  3194. if (!file) {
  3195. LogPrintf("Unable to open file %s\n", path.string());
  3196. return nullptr;
  3197. }
  3198. if (pos.nPos) {
  3199. if (fseek(file, pos.nPos, SEEK_SET)) {
  3200. LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
  3201. fclose(file);
  3202. return nullptr;
  3203. }
  3204. }
  3205. return file;
  3206. }
  3207. FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
  3208. return OpenDiskFile(pos, "blk", fReadOnly);
  3209. }
  3210. /** Open an undo file (rev?????.dat) */
  3211. static FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
  3212. return OpenDiskFile(pos, "rev", fReadOnly);
  3213. }
  3214. fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix)
  3215. {
  3216. return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
  3217. }
  3218. CBlockIndex * CChainState::InsertBlockIndex(const uint256& hash)
  3219. {
  3220. if (hash.IsNull())
  3221. return nullptr;
  3222. // Return existing
  3223. BlockMap::iterator mi = mapBlockIndex.find(hash);
  3224. if (mi != mapBlockIndex.end())
  3225. return (*mi).second;
  3226. // Create new
  3227. CBlockIndex* pindexNew = new CBlockIndex();
  3228. mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
  3229. pindexNew->phashBlock = &((*mi).first);
  3230. return pindexNew;
  3231. }
  3232. bool CChainState::LoadBlockIndex(const Consensus::Params& consensus_params, CBlockTreeDB& blocktree)
  3233. {
  3234. if (!blocktree.LoadBlockIndexGuts(consensus_params, [this](const uint256& hash){ return this->InsertBlockIndex(hash); }))
  3235. return false;
  3236. boost::this_thread::interruption_point();
  3237. // Calculate nChainWork
  3238. std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
  3239. vSortedByHeight.reserve(mapBlockIndex.size());
  3240. for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
  3241. {
  3242. CBlockIndex* pindex = item.second;
  3243. vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
  3244. }
  3245. sort(vSortedByHeight.begin(), vSortedByHeight.end());
  3246. for (const std::pair<int, CBlockIndex*>& item : vSortedByHeight)
  3247. {
  3248. CBlockIndex* pindex = item.second;
  3249. pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
  3250. pindex->nTimeMax = (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime) : pindex->nTime);
  3251. // We can link the chain of blocks for which we've received transactions at some point.
  3252. // Pruned nodes may have deleted the block.
  3253. if (pindex->nTx > 0) {
  3254. if (pindex->pprev) {
  3255. if (pindex->pprev->nChainTx) {
  3256. pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
  3257. } else {
  3258. pindex->nChainTx = 0;
  3259. mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
  3260. }
  3261. } else {
  3262. pindex->nChainTx = pindex->nTx;
  3263. }
  3264. }
  3265. if (!(pindex->nStatus & BLOCK_FAILED_MASK) && pindex->pprev && (pindex->pprev->nStatus & BLOCK_FAILED_MASK)) {
  3266. pindex->nStatus |= BLOCK_FAILED_CHILD;
  3267. setDirtyBlockIndex.insert(pindex);
  3268. }
  3269. if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == nullptr))
  3270. setBlockIndexCandidates.insert(pindex);
  3271. if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
  3272. pindexBestInvalid = pindex;
  3273. if (pindex->pprev)
  3274. pindex->BuildSkip();
  3275. if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == nullptr || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
  3276. pindexBestHeader = pindex;
  3277. }
  3278. return true;
  3279. }
  3280. bool static LoadBlockIndexDB(const CChainParams& chainparams)
  3281. {
  3282. if (!g_chainstate.LoadBlockIndex(chainparams.GetConsensus(), *pblocktree))
  3283. return false;
  3284. // Load block file info
  3285. pblocktree->ReadLastBlockFile(nLastBlockFile);
  3286. vinfoBlockFile.resize(nLastBlockFile + 1);
  3287. LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
  3288. for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
  3289. pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
  3290. }
  3291. LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
  3292. for (int nFile = nLastBlockFile + 1; true; nFile++) {
  3293. CBlockFileInfo info;
  3294. if (pblocktree->ReadBlockFileInfo(nFile, info)) {
  3295. vinfoBlockFile.push_back(info);
  3296. } else {
  3297. break;
  3298. }
  3299. }
  3300. // Check presence of blk files
  3301. LogPrintf("Checking all blk files are present...\n");
  3302. std::set<int> setBlkDataFiles;
  3303. for (const std::pair<uint256, CBlockIndex*>& item : mapBlockIndex)
  3304. {
  3305. CBlockIndex* pindex = item.second;
  3306. if (pindex->nStatus & BLOCK_HAVE_DATA) {
  3307. setBlkDataFiles.insert(pindex->nFile);
  3308. }
  3309. }
  3310. for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++)
  3311. {
  3312. CDiskBlockPos pos(*it, 0);
  3313. if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
  3314. return false;
  3315. }
  3316. }
  3317. // Check whether we have ever pruned block & undo files
  3318. pblocktree->ReadFlag("prunedblockfiles", fHavePruned);
  3319. if (fHavePruned)
  3320. LogPrintf("LoadBlockIndexDB(): Block files have previously been pruned\n");
  3321. // Check whether we need to continue reindexing
  3322. bool fReindexing = false;
  3323. pblocktree->ReadReindexing(fReindexing);
  3324. if(fReindexing) fReindex = true;
  3325. // Check whether we have a transaction index
  3326. pblocktree->ReadFlag("txindex", fTxIndex);
  3327. LogPrintf("%s: transaction index %s\n", __func__, fTxIndex ? "enabled" : "disabled");
  3328. return true;
  3329. }
  3330. bool LoadChainTip(const CChainParams& chainparams)
  3331. {
  3332. if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true;
  3333. if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) {
  3334. // In case we just added the genesis block, connect it now, so
  3335. // that we always have a chainActive.Tip() when we return.
  3336. LogPrintf("%s: Connecting genesis block...\n", __func__);
  3337. CValidationState state;
  3338. if (!ActivateBestChain(state, chainparams)) {
  3339. return false;
  3340. }
  3341. }
  3342. // Load pointer to end of best chain
  3343. BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
  3344. if (it == mapBlockIndex.end())
  3345. return false;
  3346. chainActive.SetTip(it->second);
  3347. g_chainstate.PruneBlockIndexCandidates();
  3348. LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n",
  3349. chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
  3350. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
  3351. GuessVerificationProgress(chainparams.TxData(), chainActive.Tip()));
  3352. return true;
  3353. }
  3354. CVerifyDB::CVerifyDB()
  3355. {
  3356. uiInterface.ShowProgress(_("Verifying blocks..."), 0, false);
  3357. }
  3358. CVerifyDB::~CVerifyDB()
  3359. {
  3360. uiInterface.ShowProgress("", 100, false);
  3361. }
  3362. bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth)
  3363. {
  3364. LOCK(cs_main);
  3365. if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr)
  3366. return true;
  3367. // Verify blocks in the best chain
  3368. if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height())
  3369. nCheckDepth = chainActive.Height();
  3370. nCheckLevel = std::max(0, std::min(4, nCheckLevel));
  3371. LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
  3372. CCoinsViewCache coins(coinsview);
  3373. CBlockIndex* pindexState = chainActive.Tip();
  3374. CBlockIndex* pindexFailure = nullptr;
  3375. int nGoodTransactions = 0;
  3376. CValidationState state;
  3377. int reportDone = 0;
  3378. LogPrintf("[0%%]...");
  3379. for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
  3380. {
  3381. boost::this_thread::interruption_point();
  3382. int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))));
  3383. if (reportDone < percentageDone/10) {
  3384. // report every 10% step
  3385. LogPrintf("[%d%%]...", percentageDone);
  3386. reportDone = percentageDone/10;
  3387. }
  3388. uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false);
  3389. if (pindex->nHeight < chainActive.Height()-nCheckDepth)
  3390. break;
  3391. if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) {
  3392. // If pruning, only go back as far as we have data.
  3393. LogPrintf("VerifyDB(): block verification stopping at height %d (pruning, no data)\n", pindex->nHeight);
  3394. break;
  3395. }
  3396. CBlock block;
  3397. // check level 0: read from disk
  3398. if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
  3399. return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  3400. // check level 1: verify block validity
  3401. if (nCheckLevel >= 1 && !CheckBlock(block, state, chainparams.GetConsensus()))
  3402. return error("%s: *** found bad block at %d, hash=%s (%s)\n", __func__,
  3403. pindex->nHeight, pindex->GetBlockHash().ToString(), FormatStateMessage(state));
  3404. // check level 2: verify undo validity
  3405. if (nCheckLevel >= 2 && pindex) {
  3406. CBlockUndo undo;
  3407. if (!pindex->GetUndoPos().IsNull()) {
  3408. if (!UndoReadFromDisk(undo, pindex)) {
  3409. return error("VerifyDB(): *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
  3410. }
  3411. }
  3412. }
  3413. // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
  3414. if (nCheckLevel >= 3 && pindex == pindexState && (coins.DynamicMemoryUsage() + pcoinsTip->DynamicMemoryUsage()) <= nCoinCacheUsage) {
  3415. assert(coins.GetBestBlock() == pindex->GetBlockHash());
  3416. DisconnectResult res = g_chainstate.DisconnectBlock(block, pindex, coins);
  3417. if (res == DISCONNECT_FAILED) {
  3418. return error("VerifyDB(): *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  3419. }
  3420. pindexState = pindex->pprev;
  3421. if (res == DISCONNECT_UNCLEAN) {
  3422. nGoodTransactions = 0;
  3423. pindexFailure = pindex;
  3424. } else {
  3425. nGoodTransactions += block.vtx.size();
  3426. }
  3427. }
  3428. if (ShutdownRequested())
  3429. return true;
  3430. }
  3431. if (pindexFailure)
  3432. return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
  3433. // check level 4: try reconnecting blocks
  3434. if (nCheckLevel >= 4) {
  3435. CBlockIndex *pindex = pindexState;
  3436. while (pindex != chainActive.Tip()) {
  3437. boost::this_thread::interruption_point();
  3438. uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))), false);
  3439. pindex = chainActive.Next(pindex);
  3440. CBlock block;
  3441. if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()))
  3442. return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  3443. if (!g_chainstate.ConnectBlock(block, state, pindex, coins, chainparams))
  3444. return error("VerifyDB(): *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  3445. }
  3446. }
  3447. LogPrintf("[DONE].\n");
  3448. LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
  3449. return true;
  3450. }
  3451. /** Apply the effects of a block on the utxo cache, ignoring that it may already have been applied. */
  3452. bool CChainState::RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params)
  3453. {
  3454. // TODO: merge with ConnectBlock
  3455. CBlock block;
  3456. if (!ReadBlockFromDisk(block, pindex, params.GetConsensus())) {
  3457. return error("ReplayBlock(): ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
  3458. }
  3459. for (const CTransactionRef& tx : block.vtx) {
  3460. if (!tx->IsCoinBase()) {
  3461. for (const CTxIn &txin : tx->vin) {
  3462. inputs.SpendCoin(txin.prevout);
  3463. }
  3464. }
  3465. // Pass check = true as every addition may be an overwrite.
  3466. AddCoins(inputs, *tx, pindex->nHeight, true);
  3467. }
  3468. return true;
  3469. }
  3470. bool CChainState::ReplayBlocks(const CChainParams& params, CCoinsView* view)
  3471. {
  3472. LOCK(cs_main);
  3473. CCoinsViewCache cache(view);
  3474. std::vector<uint256> hashHeads = view->GetHeadBlocks();
  3475. if (hashHeads.empty()) return true; // We're already in a consistent state.
  3476. if (hashHeads.size() != 2) return error("ReplayBlocks(): unknown inconsistent state");
  3477. uiInterface.ShowProgress(_("Replaying blocks..."), 0, false);
  3478. LogPrintf("Replaying blocks\n");
  3479. const CBlockIndex* pindexOld = nullptr; // Old tip during the interrupted flush.
  3480. const CBlockIndex* pindexNew; // New tip during the interrupted flush.
  3481. const CBlockIndex* pindexFork = nullptr; // Latest block common to both the old and the new tip.
  3482. if (mapBlockIndex.count(hashHeads[0]) == 0) {
  3483. return error("ReplayBlocks(): reorganization to unknown block requested");
  3484. }
  3485. pindexNew = mapBlockIndex[hashHeads[0]];
  3486. if (!hashHeads[1].IsNull()) { // The old tip is allowed to be 0, indicating it's the first flush.
  3487. if (mapBlockIndex.count(hashHeads[1]) == 0) {
  3488. return error("ReplayBlocks(): reorganization from unknown block requested");
  3489. }
  3490. pindexOld = mapBlockIndex[hashHeads[1]];
  3491. pindexFork = LastCommonAncestor(pindexOld, pindexNew);
  3492. assert(pindexFork != nullptr);
  3493. }
  3494. // Rollback along the old branch.
  3495. while (pindexOld != pindexFork) {
  3496. if (pindexOld->nHeight > 0) { // Never disconnect the genesis block.
  3497. CBlock block;
  3498. if (!ReadBlockFromDisk(block, pindexOld, params.GetConsensus())) {
  3499. return error("RollbackBlock(): ReadBlockFromDisk() failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
  3500. }
  3501. LogPrintf("Rolling back %s (%i)\n", pindexOld->GetBlockHash().ToString(), pindexOld->nHeight);
  3502. DisconnectResult res = DisconnectBlock(block, pindexOld, cache);
  3503. if (res == DISCONNECT_FAILED) {
  3504. return error("RollbackBlock(): DisconnectBlock failed at %d, hash=%s", pindexOld->nHeight, pindexOld->GetBlockHash().ToString());
  3505. }
  3506. // If DISCONNECT_UNCLEAN is returned, it means a non-existing UTXO was deleted, or an existing UTXO was
  3507. // overwritten. It corresponds to cases where the block-to-be-disconnect never had all its operations
  3508. // applied to the UTXO set. However, as both writing a UTXO and deleting a UTXO are idempotent operations,
  3509. // the result is still a version of the UTXO set with the effects of that block undone.
  3510. }
  3511. pindexOld = pindexOld->pprev;
  3512. }
  3513. // Roll forward from the forking point to the new tip.
  3514. int nForkHeight = pindexFork ? pindexFork->nHeight : 0;
  3515. for (int nHeight = nForkHeight + 1; nHeight <= pindexNew->nHeight; ++nHeight) {
  3516. const CBlockIndex* pindex = pindexNew->GetAncestor(nHeight);
  3517. LogPrintf("Rolling forward %s (%i)\n", pindex->GetBlockHash().ToString(), nHeight);
  3518. if (!RollforwardBlock(pindex, cache, params)) return false;
  3519. }
  3520. cache.SetBestBlock(pindexNew->GetBlockHash());
  3521. cache.Flush();
  3522. uiInterface.ShowProgress("", 100, false);
  3523. return true;
  3524. }
  3525. bool ReplayBlocks(const CChainParams& params, CCoinsView* view) {
  3526. return g_chainstate.ReplayBlocks(params, view);
  3527. }
  3528. bool CChainState::RewindBlockIndex(const CChainParams& params)
  3529. {
  3530. LOCK(cs_main);
  3531. // Note that during -reindex-chainstate we are called with an empty chainActive!
  3532. int nHeight = 1;
  3533. while (nHeight <= chainActive.Height()) {
  3534. if (IsWitnessEnabled(chainActive[nHeight - 1], params.GetConsensus()) && !(chainActive[nHeight]->nStatus & BLOCK_OPT_WITNESS)) {
  3535. break;
  3536. }
  3537. nHeight++;
  3538. }
  3539. // nHeight is now the height of the first insufficiently-validated block, or tipheight + 1
  3540. CValidationState state;
  3541. CBlockIndex* pindex = chainActive.Tip();
  3542. while (chainActive.Height() >= nHeight) {
  3543. if (fPruneMode && !(chainActive.Tip()->nStatus & BLOCK_HAVE_DATA)) {
  3544. // If pruning, don't try rewinding past the HAVE_DATA point;
  3545. // since older blocks can't be served anyway, there's
  3546. // no need to walk further, and trying to DisconnectTip()
  3547. // will fail (and require a needless reindex/redownload
  3548. // of the blockchain).
  3549. break;
  3550. }
  3551. if (!DisconnectTip(state, params, nullptr)) {
  3552. return error("RewindBlockIndex: unable to disconnect block at height %i", pindex->nHeight);
  3553. }
  3554. // Occasionally flush state to disk.
  3555. if (!FlushStateToDisk(params, state, FLUSH_STATE_PERIODIC))
  3556. return false;
  3557. }
  3558. // Reduce validity flag and have-data flags.
  3559. // We do this after actual disconnecting, otherwise we'll end up writing the lack of data
  3560. // to disk before writing the chainstate, resulting in a failure to continue if interrupted.
  3561. for (const auto& entry : mapBlockIndex) {
  3562. CBlockIndex* pindexIter = entry.second;
  3563. // Note: If we encounter an insufficiently validated block that
  3564. // is on chainActive, it must be because we are a pruning node, and
  3565. // this block or some successor doesn't HAVE_DATA, so we were unable to
  3566. // rewind all the way. Blocks remaining on chainActive at this point
  3567. // must not have their validity reduced.
  3568. if (IsWitnessEnabled(pindexIter->pprev, params.GetConsensus()) && !(pindexIter->nStatus & BLOCK_OPT_WITNESS) && !chainActive.Contains(pindexIter)) {
  3569. // Reduce validity
  3570. pindexIter->nStatus = std::min<unsigned int>(pindexIter->nStatus & BLOCK_VALID_MASK, BLOCK_VALID_TREE) | (pindexIter->nStatus & ~BLOCK_VALID_MASK);
  3571. // Remove have-data flags.
  3572. pindexIter->nStatus &= ~(BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO);
  3573. // Remove storage location.
  3574. pindexIter->nFile = 0;
  3575. pindexIter->nDataPos = 0;
  3576. pindexIter->nUndoPos = 0;
  3577. // Remove various other things
  3578. pindexIter->nTx = 0;
  3579. pindexIter->nChainTx = 0;
  3580. pindexIter->nSequenceId = 0;
  3581. // Make sure it gets written.
  3582. setDirtyBlockIndex.insert(pindexIter);
  3583. // Update indexes
  3584. setBlockIndexCandidates.erase(pindexIter);
  3585. std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> ret = mapBlocksUnlinked.equal_range(pindexIter->pprev);
  3586. while (ret.first != ret.second) {
  3587. if (ret.first->second == pindexIter) {
  3588. mapBlocksUnlinked.erase(ret.first++);
  3589. } else {
  3590. ++ret.first;
  3591. }
  3592. }
  3593. } else if (pindexIter->IsValid(BLOCK_VALID_TRANSACTIONS) && pindexIter->nChainTx) {
  3594. setBlockIndexCandidates.insert(pindexIter);
  3595. }
  3596. }
  3597. if (chainActive.Tip() != nullptr) {
  3598. // We can't prune block index candidates based on our tip if we have
  3599. // no tip due to chainActive being empty!
  3600. PruneBlockIndexCandidates();
  3601. CheckBlockIndex(params.GetConsensus());
  3602. }
  3603. return true;
  3604. }
  3605. bool RewindBlockIndex(const CChainParams& params) {
  3606. if (!g_chainstate.RewindBlockIndex(params)) {
  3607. return false;
  3608. }
  3609. if (chainActive.Tip() != nullptr) {
  3610. // FlushStateToDisk can possibly read chainActive. Be conservative
  3611. // and skip it here, we're about to -reindex-chainstate anyway, so
  3612. // it'll get called a bunch real soon.
  3613. CValidationState state;
  3614. if (!FlushStateToDisk(params, state, FLUSH_STATE_ALWAYS)) {
  3615. return false;
  3616. }
  3617. }
  3618. return true;
  3619. }
  3620. void CChainState::UnloadBlockIndex() {
  3621. nBlockSequenceId = 1;
  3622. g_failed_blocks.clear();
  3623. setBlockIndexCandidates.clear();
  3624. }
  3625. // May NOT be used after any connections are up as much
  3626. // of the peer-processing logic assumes a consistent
  3627. // block index state
  3628. void UnloadBlockIndex()
  3629. {
  3630. LOCK(cs_main);
  3631. chainActive.SetTip(nullptr);
  3632. pindexBestInvalid = nullptr;
  3633. pindexBestHeader = nullptr;
  3634. mempool.clear();
  3635. mapBlocksUnlinked.clear();
  3636. vinfoBlockFile.clear();
  3637. nLastBlockFile = 0;
  3638. setDirtyBlockIndex.clear();
  3639. setDirtyFileInfo.clear();
  3640. versionbitscache.Clear();
  3641. for (int b = 0; b < VERSIONBITS_NUM_BITS; b++) {
  3642. warningcache[b].clear();
  3643. }
  3644. for (BlockMap::value_type& entry : mapBlockIndex) {
  3645. delete entry.second;
  3646. }
  3647. mapBlockIndex.clear();
  3648. fHavePruned = false;
  3649. g_chainstate.UnloadBlockIndex();
  3650. }
  3651. bool LoadBlockIndex(const CChainParams& chainparams)
  3652. {
  3653. // Load block index from databases
  3654. bool needs_init = fReindex;
  3655. if (!fReindex) {
  3656. bool ret = LoadBlockIndexDB(chainparams);
  3657. if (!ret) return false;
  3658. needs_init = mapBlockIndex.empty();
  3659. }
  3660. if (needs_init) {
  3661. // Everything here is for *new* reindex/DBs. Thus, though
  3662. // LoadBlockIndexDB may have set fReindex if we shut down
  3663. // mid-reindex previously, we don't check fReindex and
  3664. // instead only check it prior to LoadBlockIndexDB to set
  3665. // needs_init.
  3666. LogPrintf("Initializing databases...\n");
  3667. // Use the provided setting for -txindex in the new database
  3668. fTxIndex = gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX);
  3669. pblocktree->WriteFlag("txindex", fTxIndex);
  3670. }
  3671. return true;
  3672. }
  3673. bool CChainState::LoadGenesisBlock(const CChainParams& chainparams)
  3674. {
  3675. LOCK(cs_main);
  3676. // Check whether we're already initialized by checking for genesis in
  3677. // mapBlockIndex. Note that we can't use chainActive here, since it is
  3678. // set based on the coins db, not the block index db, which is the only
  3679. // thing loaded at this point.
  3680. if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash()))
  3681. return true;
  3682. try {
  3683. CBlock &block = const_cast<CBlock&>(chainparams.GenesisBlock());
  3684. CDiskBlockPos blockPos = SaveBlockToDisk(block, 0, chainparams, nullptr);
  3685. if (blockPos.IsNull())
  3686. return error("%s: writing genesis block to disk failed", __func__);
  3687. CBlockIndex *pindex = AddToBlockIndex(block);
  3688. CValidationState state;
  3689. if (!ReceivedBlockTransactions(block, state, pindex, blockPos, chainparams.GetConsensus()))
  3690. return error("%s: genesis block not accepted", __func__);
  3691. } catch (const std::runtime_error& e) {
  3692. return error("%s: failed to write genesis block: %s", __func__, e.what());
  3693. }
  3694. return true;
  3695. }
  3696. bool LoadGenesisBlock(const CChainParams& chainparams)
  3697. {
  3698. return g_chainstate.LoadGenesisBlock(chainparams);
  3699. }
  3700. bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp)
  3701. {
  3702. // Map of disk positions for blocks with unknown parent (only used for reindex)
  3703. static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
  3704. int64_t nStart = GetTimeMillis();
  3705. int nLoaded = 0;
  3706. try {
  3707. // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
  3708. CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SERIALIZED_SIZE, MAX_BLOCK_SERIALIZED_SIZE+8, SER_DISK, CLIENT_VERSION);
  3709. uint64_t nRewind = blkdat.GetPos();
  3710. while (!blkdat.eof()) {
  3711. boost::this_thread::interruption_point();
  3712. blkdat.SetPos(nRewind);
  3713. nRewind++; // start one byte further next time, in case of failure
  3714. blkdat.SetLimit(); // remove former limit
  3715. unsigned int nSize = 0;
  3716. try {
  3717. // locate a header
  3718. unsigned char buf[CMessageHeader::MESSAGE_START_SIZE];
  3719. blkdat.FindByte(chainparams.MessageStart()[0]);
  3720. nRewind = blkdat.GetPos()+1;
  3721. blkdat >> FLATDATA(buf);
  3722. if (memcmp(buf, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE))
  3723. continue;
  3724. // read size
  3725. blkdat >> nSize;
  3726. if (nSize < 80 || nSize > MAX_BLOCK_SERIALIZED_SIZE)
  3727. continue;
  3728. } catch (const std::exception&) {
  3729. // no valid block header found; don't complain
  3730. break;
  3731. }
  3732. try {
  3733. // read block
  3734. uint64_t nBlockPos = blkdat.GetPos();
  3735. if (dbp)
  3736. dbp->nPos = nBlockPos;
  3737. blkdat.SetLimit(nBlockPos + nSize);
  3738. blkdat.SetPos(nBlockPos);
  3739. std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>();
  3740. CBlock& block = *pblock;
  3741. blkdat >> block;
  3742. nRewind = blkdat.GetPos();
  3743. // detect out of order blocks, and store them for later
  3744. uint256 hash = block.GetHash();
  3745. if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
  3746. LogPrint(BCLog::REINDEX, "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
  3747. block.hashPrevBlock.ToString());
  3748. if (dbp)
  3749. mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
  3750. continue;
  3751. }
  3752. // process in case the block isn't known yet
  3753. if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
  3754. LOCK(cs_main);
  3755. CValidationState state;
  3756. if (g_chainstate.AcceptBlock(pblock, state, chainparams, nullptr, true, dbp, nullptr))
  3757. nLoaded++;
  3758. if (state.IsError())
  3759. break;
  3760. } else if (hash != chainparams.GetConsensus().hashGenesisBlock && mapBlockIndex[hash]->nHeight % 1000 == 0) {
  3761. LogPrint(BCLog::REINDEX, "Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
  3762. }
  3763. // Activate the genesis block so normal node progress can continue
  3764. if (hash == chainparams.GetConsensus().hashGenesisBlock) {
  3765. CValidationState state;
  3766. if (!ActivateBestChain(state, chainparams)) {
  3767. break;
  3768. }
  3769. }
  3770. NotifyHeaderTip();
  3771. // Recursively process earlier encountered successors of this block
  3772. std::deque<uint256> queue;
  3773. queue.push_back(hash);
  3774. while (!queue.empty()) {
  3775. uint256 head = queue.front();
  3776. queue.pop_front();
  3777. std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
  3778. while (range.first != range.second) {
  3779. std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
  3780. std::shared_ptr<CBlock> pblockrecursive = std::make_shared<CBlock>();
  3781. if (ReadBlockFromDisk(*pblockrecursive, it->second, chainparams.GetConsensus()))
  3782. {
  3783. LogPrint(BCLog::REINDEX, "%s: Processing out of order child %s of %s\n", __func__, pblockrecursive->GetHash().ToString(),
  3784. head.ToString());
  3785. LOCK(cs_main);
  3786. CValidationState dummy;
  3787. if (g_chainstate.AcceptBlock(pblockrecursive, dummy, chainparams, nullptr, true, &it->second, nullptr))
  3788. {
  3789. nLoaded++;
  3790. queue.push_back(pblockrecursive->GetHash());
  3791. }
  3792. }
  3793. range.first++;
  3794. mapBlocksUnknownParent.erase(it);
  3795. NotifyHeaderTip();
  3796. }
  3797. }
  3798. } catch (const std::exception& e) {
  3799. LogPrintf("%s: Deserialize or I/O error - %s\n", __func__, e.what());
  3800. }
  3801. }
  3802. } catch (const std::runtime_error& e) {
  3803. AbortNode(std::string("System error: ") + e.what());
  3804. }
  3805. if (nLoaded > 0)
  3806. LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
  3807. return nLoaded > 0;
  3808. }
  3809. void CChainState::CheckBlockIndex(const Consensus::Params& consensusParams)
  3810. {
  3811. if (!fCheckBlockIndex) {
  3812. return;
  3813. }
  3814. LOCK(cs_main);
  3815. // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
  3816. // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
  3817. // iterating the block tree require that chainActive has been initialized.)
  3818. if (chainActive.Height() < 0) {
  3819. assert(mapBlockIndex.size() <= 1);
  3820. return;
  3821. }
  3822. // Build forward-pointing map of the entire block tree.
  3823. std::multimap<CBlockIndex*,CBlockIndex*> forward;
  3824. for (auto& entry : mapBlockIndex) {
  3825. forward.insert(std::make_pair(entry.second->pprev, entry.second));
  3826. }
  3827. assert(forward.size() == mapBlockIndex.size());
  3828. std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(nullptr);
  3829. CBlockIndex *pindex = rangeGenesis.first->second;
  3830. rangeGenesis.first++;
  3831. assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent nullptr.
  3832. // Iterate over the entire block tree, using depth-first search.
  3833. // Along the way, remember whether there are blocks on the path from genesis
  3834. // block being explored which are the first to have certain properties.
  3835. size_t nNodes = 0;
  3836. int nHeight = 0;
  3837. CBlockIndex* pindexFirstInvalid = nullptr; // Oldest ancestor of pindex which is invalid.
  3838. CBlockIndex* pindexFirstMissing = nullptr; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
  3839. CBlockIndex* pindexFirstNeverProcessed = nullptr; // Oldest ancestor of pindex for which nTx == 0.
  3840. CBlockIndex* pindexFirstNotTreeValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
  3841. CBlockIndex* pindexFirstNotTransactionsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_TRANSACTIONS (regardless of being valid or not).
  3842. CBlockIndex* pindexFirstNotChainValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
  3843. CBlockIndex* pindexFirstNotScriptsValid = nullptr; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
  3844. while (pindex != nullptr) {
  3845. nNodes++;
  3846. if (pindexFirstInvalid == nullptr && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
  3847. if (pindexFirstMissing == nullptr && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
  3848. if (pindexFirstNeverProcessed == nullptr && pindex->nTx == 0) pindexFirstNeverProcessed = pindex;
  3849. if (pindex->pprev != nullptr && pindexFirstNotTreeValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
  3850. if (pindex->pprev != nullptr && pindexFirstNotTransactionsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TRANSACTIONS) pindexFirstNotTransactionsValid = pindex;
  3851. if (pindex->pprev != nullptr && pindexFirstNotChainValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
  3852. if (pindex->pprev != nullptr && pindexFirstNotScriptsValid == nullptr && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
  3853. // Begin: actual consistency checks.
  3854. if (pindex->pprev == nullptr) {
  3855. // Genesis block checks.
  3856. assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match.
  3857. assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
  3858. }
  3859. if (pindex->nChainTx == 0) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock)
  3860. // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred).
  3861. // HAVE_DATA is only equivalent to nTx > 0 (or VALID_TRANSACTIONS) if no pruning has occurred.
  3862. if (!fHavePruned) {
  3863. // If we've never pruned, then HAVE_DATA should be equivalent to nTx > 0
  3864. assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
  3865. assert(pindexFirstMissing == pindexFirstNeverProcessed);
  3866. } else {
  3867. // If we have pruned, then we can only say that HAVE_DATA implies nTx > 0
  3868. if (pindex->nStatus & BLOCK_HAVE_DATA) assert(pindex->nTx > 0);
  3869. }
  3870. if (pindex->nStatus & BLOCK_HAVE_UNDO) assert(pindex->nStatus & BLOCK_HAVE_DATA);
  3871. assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); // This is pruning-independent.
  3872. // All parents having had data (at some point) is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
  3873. assert((pindexFirstNeverProcessed != nullptr) == (pindex->nChainTx == 0)); // nChainTx != 0 is used to signal that all parent blocks have been processed (but may have been pruned).
  3874. assert((pindexFirstNotTransactionsValid != nullptr) == (pindex->nChainTx == 0));
  3875. assert(pindex->nHeight == nHeight); // nHeight must be consistent.
  3876. assert(pindex->pprev == nullptr || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
  3877. assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
  3878. assert(pindexFirstNotTreeValid == nullptr); // All mapBlockIndex entries must at least be TREE valid
  3879. if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == nullptr); // TREE valid implies all parents are TREE valid
  3880. if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == nullptr); // CHAIN valid implies all parents are CHAIN valid
  3881. if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == nullptr); // SCRIPTS valid implies all parents are SCRIPTS valid
  3882. if (pindexFirstInvalid == nullptr) {
  3883. // Checks for not-invalid blocks.
  3884. assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
  3885. }
  3886. if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) {
  3887. if (pindexFirstInvalid == nullptr) {
  3888. // If this block sorts at least as good as the current tip and
  3889. // is valid and we have all data for its parents, it must be in
  3890. // setBlockIndexCandidates. chainActive.Tip() must also be there
  3891. // even if some data has been pruned.
  3892. if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) {
  3893. assert(setBlockIndexCandidates.count(pindex));
  3894. }
  3895. // If some parent is missing, then it could be that this block was in
  3896. // setBlockIndexCandidates but had to be removed because of the missing data.
  3897. // In this case it must be in mapBlocksUnlinked -- see test below.
  3898. }
  3899. } else { // If this block sorts worse than the current tip or some ancestor's block has never been seen, it cannot be in setBlockIndexCandidates.
  3900. assert(setBlockIndexCandidates.count(pindex) == 0);
  3901. }
  3902. // Check whether this block is in mapBlocksUnlinked.
  3903. std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
  3904. bool foundInUnlinked = false;
  3905. while (rangeUnlinked.first != rangeUnlinked.second) {
  3906. assert(rangeUnlinked.first->first == pindex->pprev);
  3907. if (rangeUnlinked.first->second == pindex) {
  3908. foundInUnlinked = true;
  3909. break;
  3910. }
  3911. rangeUnlinked.first++;
  3912. }
  3913. if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed != nullptr && pindexFirstInvalid == nullptr) {
  3914. // If this block has block data available, some parent was never received, and has no invalid parents, it must be in mapBlocksUnlinked.
  3915. assert(foundInUnlinked);
  3916. }
  3917. if (!(pindex->nStatus & BLOCK_HAVE_DATA)) assert(!foundInUnlinked); // Can't be in mapBlocksUnlinked if we don't HAVE_DATA
  3918. if (pindexFirstMissing == nullptr) assert(!foundInUnlinked); // We aren't missing data for any parent -- cannot be in mapBlocksUnlinked.
  3919. if (pindex->pprev && (pindex->nStatus & BLOCK_HAVE_DATA) && pindexFirstNeverProcessed == nullptr && pindexFirstMissing != nullptr) {
  3920. // We HAVE_DATA for this block, have received data for all parents at some point, but we're currently missing data for some parent.
  3921. assert(fHavePruned); // We must have pruned.
  3922. // This block may have entered mapBlocksUnlinked if:
  3923. // - it has a descendant that at some point had more work than the
  3924. // tip, and
  3925. // - we tried switching to that descendant but were missing
  3926. // data for some intermediate block between chainActive and the
  3927. // tip.
  3928. // So if this block is itself better than chainActive.Tip() and it wasn't in
  3929. // setBlockIndexCandidates, then it must be in mapBlocksUnlinked.
  3930. if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) {
  3931. if (pindexFirstInvalid == nullptr) {
  3932. assert(foundInUnlinked);
  3933. }
  3934. }
  3935. }
  3936. // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
  3937. // End: actual consistency checks.
  3938. // Try descending into the first subnode.
  3939. std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> range = forward.equal_range(pindex);
  3940. if (range.first != range.second) {
  3941. // A subnode was found.
  3942. pindex = range.first->second;
  3943. nHeight++;
  3944. continue;
  3945. }
  3946. // This is a leaf node.
  3947. // Move upwards until we reach a node of which we have not yet visited the last child.
  3948. while (pindex) {
  3949. // We are going to either move to a parent or a sibling of pindex.
  3950. // If pindex was the first with a certain property, unset the corresponding variable.
  3951. if (pindex == pindexFirstInvalid) pindexFirstInvalid = nullptr;
  3952. if (pindex == pindexFirstMissing) pindexFirstMissing = nullptr;
  3953. if (pindex == pindexFirstNeverProcessed) pindexFirstNeverProcessed = nullptr;
  3954. if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = nullptr;
  3955. if (pindex == pindexFirstNotTransactionsValid) pindexFirstNotTransactionsValid = nullptr;
  3956. if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = nullptr;
  3957. if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = nullptr;
  3958. // Find our parent.
  3959. CBlockIndex* pindexPar = pindex->pprev;
  3960. // Find which child we just visited.
  3961. std::pair<std::multimap<CBlockIndex*,CBlockIndex*>::iterator,std::multimap<CBlockIndex*,CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
  3962. while (rangePar.first->second != pindex) {
  3963. assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
  3964. rangePar.first++;
  3965. }
  3966. // Proceed to the next one.
  3967. rangePar.first++;
  3968. if (rangePar.first != rangePar.second) {
  3969. // Move to the sibling.
  3970. pindex = rangePar.first->second;
  3971. break;
  3972. } else {
  3973. // Move up further.
  3974. pindex = pindexPar;
  3975. nHeight--;
  3976. continue;
  3977. }
  3978. }
  3979. }
  3980. // Check that we actually traversed the entire map.
  3981. assert(nNodes == forward.size());
  3982. }
  3983. std::string CBlockFileInfo::ToString() const
  3984. {
  3985. 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));
  3986. }
  3987. CBlockFileInfo* GetBlockFileInfo(size_t n)
  3988. {
  3989. LOCK(cs_LastBlockFile);
  3990. return &vinfoBlockFile.at(n);
  3991. }
  3992. ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos)
  3993. {
  3994. LOCK(cs_main);
  3995. return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache);
  3996. }
  3997. BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos)
  3998. {
  3999. LOCK(cs_main);
  4000. return VersionBitsStatistics(chainActive.Tip(), params, pos);
  4001. }
  4002. int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos)
  4003. {
  4004. LOCK(cs_main);
  4005. return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache);
  4006. }
  4007. static const uint64_t MEMPOOL_DUMP_VERSION = 1;
  4008. bool LoadMempool(void)
  4009. {
  4010. const CChainParams& chainparams = Params();
  4011. int64_t nExpiryTimeout = gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60;
  4012. FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat", "rb");
  4013. CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
  4014. if (file.IsNull()) {
  4015. LogPrintf("Failed to open mempool file from disk. Continuing anyway.\n");
  4016. return false;
  4017. }
  4018. int64_t count = 0;
  4019. int64_t expired = 0;
  4020. int64_t failed = 0;
  4021. int64_t already_there = 0;
  4022. int64_t nNow = GetTime();
  4023. try {
  4024. uint64_t version;
  4025. file >> version;
  4026. if (version != MEMPOOL_DUMP_VERSION) {
  4027. return false;
  4028. }
  4029. uint64_t num;
  4030. file >> num;
  4031. while (num--) {
  4032. CTransactionRef tx;
  4033. int64_t nTime;
  4034. int64_t nFeeDelta;
  4035. file >> tx;
  4036. file >> nTime;
  4037. file >> nFeeDelta;
  4038. CAmount amountdelta = nFeeDelta;
  4039. if (amountdelta) {
  4040. mempool.PrioritiseTransaction(tx->GetHash(), amountdelta);
  4041. }
  4042. CValidationState state;
  4043. if (nTime + nExpiryTimeout > nNow) {
  4044. LOCK(cs_main);
  4045. AcceptToMemoryPoolWithTime(chainparams, mempool, state, tx, nullptr /* pfMissingInputs */, nTime,
  4046. nullptr /* plTxnReplaced */, false /* bypass_limits */, 0 /* nAbsurdFee */);
  4047. if (state.IsValid()) {
  4048. ++count;
  4049. } else {
  4050. // mempool may contain the transaction already, e.g. from
  4051. // wallet(s) having loaded it while we were processing
  4052. // mempool transactions; consider these as valid, instead of
  4053. // failed, but mark them as 'already there'
  4054. if (mempool.exists(tx->GetHash())) {
  4055. ++already_there;
  4056. } else {
  4057. ++failed;
  4058. }
  4059. }
  4060. } else {
  4061. ++expired;
  4062. }
  4063. if (ShutdownRequested())
  4064. return false;
  4065. }
  4066. std::map<uint256, CAmount> mapDeltas;
  4067. file >> mapDeltas;
  4068. for (const auto& i : mapDeltas) {
  4069. mempool.PrioritiseTransaction(i.first, i.second);
  4070. }
  4071. } catch (const std::exception& e) {
  4072. LogPrintf("Failed to deserialize mempool data on disk: %s. Continuing anyway.\n", e.what());
  4073. return false;
  4074. }
  4075. LogPrintf("Imported mempool transactions from disk: %i succeeded, %i failed, %i expired, %i already there\n", count, failed, expired, already_there);
  4076. return true;
  4077. }
  4078. bool DumpMempool(void)
  4079. {
  4080. int64_t start = GetTimeMicros();
  4081. std::map<uint256, CAmount> mapDeltas;
  4082. std::vector<TxMempoolInfo> vinfo;
  4083. {
  4084. LOCK(mempool.cs);
  4085. for (const auto &i : mempool.mapDeltas) {
  4086. mapDeltas[i.first] = i.second;
  4087. }
  4088. vinfo = mempool.infoAll();
  4089. }
  4090. int64_t mid = GetTimeMicros();
  4091. try {
  4092. FILE* filestr = fsbridge::fopen(GetDataDir() / "mempool.dat.new", "wb");
  4093. if (!filestr) {
  4094. return false;
  4095. }
  4096. CAutoFile file(filestr, SER_DISK, CLIENT_VERSION);
  4097. uint64_t version = MEMPOOL_DUMP_VERSION;
  4098. file << version;
  4099. file << (uint64_t)vinfo.size();
  4100. for (const auto& i : vinfo) {
  4101. file << *(i.tx);
  4102. file << (int64_t)i.nTime;
  4103. file << (int64_t)i.nFeeDelta;
  4104. mapDeltas.erase(i.tx->GetHash());
  4105. }
  4106. file << mapDeltas;
  4107. FileCommit(file.Get());
  4108. file.fclose();
  4109. RenameOver(GetDataDir() / "mempool.dat.new", GetDataDir() / "mempool.dat");
  4110. int64_t last = GetTimeMicros();
  4111. LogPrintf("Dumped mempool: %gs to copy, %gs to dump\n", (mid-start)*MICRO, (last-mid)*MICRO);
  4112. } catch (const std::exception& e) {
  4113. LogPrintf("Failed to dump mempool: %s. Continuing anyway.\n", e.what());
  4114. return false;
  4115. }
  4116. return true;
  4117. }
  4118. //! Guess how far we are in the verification process at the given block index
  4119. double GuessVerificationProgress(const ChainTxData& data, const CBlockIndex *pindex) {
  4120. if (pindex == nullptr)
  4121. return 0.0;
  4122. int64_t nNow = time(nullptr);
  4123. double fTxTotal;
  4124. if (pindex->nChainTx <= data.nTxCount) {
  4125. fTxTotal = data.nTxCount + (nNow - data.nTime) * data.dTxRate;
  4126. } else {
  4127. fTxTotal = pindex->nChainTx + (nNow - pindex->GetBlockTime()) * data.dTxRate;
  4128. }
  4129. return pindex->nChainTx / fTxTotal;
  4130. }
  4131. class CMainCleanup
  4132. {
  4133. public:
  4134. CMainCleanup() {}
  4135. ~CMainCleanup() {
  4136. // block headers
  4137. BlockMap::iterator it1 = mapBlockIndex.begin();
  4138. for (; it1 != mapBlockIndex.end(); it1++)
  4139. delete (*it1).second;
  4140. mapBlockIndex.clear();
  4141. }
  4142. } instance_of_cmaincleanup;