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

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