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

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