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

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