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

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