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

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