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

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