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

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