Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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