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

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