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

main.cpp 196KB

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