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

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