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

main.cpp 173KB

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