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

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