You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.cpp 163KB

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