You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.cpp 110KB

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