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

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