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

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