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 204KB

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