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

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