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

main.cpp 224KB

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