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

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