Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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