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

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