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

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