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

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