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

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