Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

main.cpp 247KB

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