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

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