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

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