Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

main.cpp 162KB

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