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

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