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

main.cpp 210KB

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