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

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