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

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