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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2013 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 "main.h"
  6. #include "addrman.h"
  7. #include "alert.h"
  8. #include "chainparams.h"
  9. #include "checkpoints.h"
  10. #include "checkqueue.h"
  11. #include "init.h"
  12. #include "net.h"
  13. #include "txdb.h"
  14. #include "txmempool.h"
  15. #include "ui_interface.h"
  16. #include "util.h"
  17. #include <inttypes.h>
  18. #include <sstream>
  19. #include <boost/algorithm/string/replace.hpp>
  20. #include <boost/filesystem.hpp>
  21. #include <boost/filesystem/fstream.hpp>
  22. using namespace std;
  23. using namespace boost;
  24. #if defined(NDEBUG)
  25. # error "Bitcoin cannot be compiled without assertions."
  26. #endif
  27. //
  28. // Global state
  29. //
  30. CCriticalSection cs_main;
  31. CTxMemPool mempool;
  32. map<uint256, CBlockIndex*> mapBlockIndex;
  33. CChain chainActive;
  34. int64_t nTimeBestReceived = 0;
  35. int nScriptCheckThreads = 0;
  36. bool fImporting = false;
  37. bool fReindex = false;
  38. bool fBenchmark = false;
  39. bool fTxIndex = false;
  40. unsigned int nCoinCacheSize = 5000;
  41. /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
  42. int64_t CTransaction::nMinTxFee = 10000; // Override with -mintxfee
  43. /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
  44. int64_t CTransaction::nMinRelayTxFee = 10000;
  45. static CMedianFilter<int> cPeerBlockCounts(8, 0); // Amount of blocks that other nodes claim to have
  46. map<uint256, CBlock*> mapOrphanBlocks;
  47. multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
  48. map<uint256, CTransaction> mapOrphanTransactions;
  49. map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
  50. // Constant stuff for coinbase transactions we create:
  51. CScript COINBASE_FLAGS;
  52. const string strMessageMagic = "Bitcoin Signed Message:\n";
  53. // Settings
  54. int64_t nTransactionFee = 0;
  55. // Internal stuff
  56. namespace {
  57. struct CBlockIndexWorkComparator
  58. {
  59. bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
  60. if (pa->nChainWork > pb->nChainWork) return false;
  61. if (pa->nChainWork < pb->nChainWork) return true;
  62. if (pa->GetBlockHash() < pb->GetBlockHash()) return false;
  63. if (pa->GetBlockHash() > pb->GetBlockHash()) return true;
  64. return false; // identical blocks
  65. }
  66. };
  67. CBlockIndex *pindexBestInvalid;
  68. set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
  69. CCriticalSection cs_LastBlockFile;
  70. CBlockFileInfo infoLastBlockFile;
  71. int nLastBlockFile = 0;
  72. }
  73. //////////////////////////////////////////////////////////////////////////////
  74. //
  75. // dispatching functions
  76. //
  77. // These functions dispatch to one or all registered wallets
  78. namespace {
  79. struct CMainSignals {
  80. // Notifies listeners of updated transaction data (passing hash, transaction, and optionally the block it is found in.
  81. boost::signals2::signal<void (const uint256 &, const CTransaction &, const CBlock *)> SyncTransaction;
  82. // Notifies listeners of an erased transaction (currently disabled, requires transaction replacement).
  83. boost::signals2::signal<void (const uint256 &)> EraseTransaction;
  84. // Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible).
  85. boost::signals2::signal<void (const uint256 &)> UpdatedTransaction;
  86. // Notifies listeners of a new active block chain.
  87. boost::signals2::signal<void (const CBlockLocator &)> SetBestChain;
  88. // Notifies listeners about an inventory item being seen on the network.
  89. boost::signals2::signal<void (const uint256 &)> Inventory;
  90. // Tells listeners to broadcast their data.
  91. boost::signals2::signal<void ()> Broadcast;
  92. } g_signals;
  93. }
  94. void RegisterWallet(CWalletInterface* pwalletIn) {
  95. g_signals.SyncTransaction.connect(boost::bind(&CWalletInterface::SyncTransaction, pwalletIn, _1, _2, _3));
  96. g_signals.EraseTransaction.connect(boost::bind(&CWalletInterface::EraseFromWallet, pwalletIn, _1));
  97. g_signals.UpdatedTransaction.connect(boost::bind(&CWalletInterface::UpdatedTransaction, pwalletIn, _1));
  98. g_signals.SetBestChain.connect(boost::bind(&CWalletInterface::SetBestChain, pwalletIn, _1));
  99. g_signals.Inventory.connect(boost::bind(&CWalletInterface::Inventory, pwalletIn, _1));
  100. g_signals.Broadcast.connect(boost::bind(&CWalletInterface::ResendWalletTransactions, pwalletIn));
  101. }
  102. void UnregisterWallet(CWalletInterface* pwalletIn) {
  103. g_signals.Broadcast.disconnect(boost::bind(&CWalletInterface::ResendWalletTransactions, pwalletIn));
  104. g_signals.Inventory.disconnect(boost::bind(&CWalletInterface::Inventory, pwalletIn, _1));
  105. g_signals.SetBestChain.disconnect(boost::bind(&CWalletInterface::SetBestChain, pwalletIn, _1));
  106. g_signals.UpdatedTransaction.disconnect(boost::bind(&CWalletInterface::UpdatedTransaction, pwalletIn, _1));
  107. g_signals.EraseTransaction.disconnect(boost::bind(&CWalletInterface::EraseFromWallet, pwalletIn, _1));
  108. g_signals.SyncTransaction.disconnect(boost::bind(&CWalletInterface::SyncTransaction, pwalletIn, _1, _2, _3));
  109. }
  110. void UnregisterAllWallets() {
  111. g_signals.Broadcast.disconnect_all_slots();
  112. g_signals.Inventory.disconnect_all_slots();
  113. g_signals.SetBestChain.disconnect_all_slots();
  114. g_signals.UpdatedTransaction.disconnect_all_slots();
  115. g_signals.EraseTransaction.disconnect_all_slots();
  116. g_signals.SyncTransaction.disconnect_all_slots();
  117. }
  118. void SyncWithWallets(const uint256 &hash, const CTransaction &tx, const CBlock *pblock) {
  119. g_signals.SyncTransaction(hash, tx, pblock);
  120. }
  121. //////////////////////////////////////////////////////////////////////////////
  122. //
  123. // Registration of network node signals.
  124. //
  125. int static GetHeight()
  126. {
  127. LOCK(cs_main);
  128. return chainActive.Height();
  129. }
  130. void RegisterNodeSignals(CNodeSignals& nodeSignals)
  131. {
  132. nodeSignals.GetHeight.connect(&GetHeight);
  133. nodeSignals.ProcessMessages.connect(&ProcessMessages);
  134. nodeSignals.SendMessages.connect(&SendMessages);
  135. }
  136. void UnregisterNodeSignals(CNodeSignals& nodeSignals)
  137. {
  138. nodeSignals.GetHeight.disconnect(&GetHeight);
  139. nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
  140. nodeSignals.SendMessages.disconnect(&SendMessages);
  141. }
  142. //////////////////////////////////////////////////////////////////////////////
  143. //
  144. // CChain implementation
  145. //
  146. CBlockIndex *CChain::SetTip(CBlockIndex *pindex) {
  147. if (pindex == NULL) {
  148. vChain.clear();
  149. return NULL;
  150. }
  151. vChain.resize(pindex->nHeight + 1);
  152. while (pindex && vChain[pindex->nHeight] != pindex) {
  153. vChain[pindex->nHeight] = pindex;
  154. pindex = pindex->pprev;
  155. }
  156. return pindex;
  157. }
  158. CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
  159. int nStep = 1;
  160. std::vector<uint256> vHave;
  161. vHave.reserve(32);
  162. if (!pindex)
  163. pindex = Tip();
  164. while (pindex) {
  165. vHave.push_back(pindex->GetBlockHash());
  166. // Stop when we have added the genesis block.
  167. if (pindex->nHeight == 0)
  168. break;
  169. // Exponentially larger steps back, plus the genesis block.
  170. int nHeight = std::max(pindex->nHeight - nStep, 0);
  171. // In case pindex is not in this chain, iterate pindex->pprev to find blocks.
  172. while (pindex->nHeight > nHeight && !Contains(pindex))
  173. pindex = pindex->pprev;
  174. // If pindex is in this chain, use direct height-based access.
  175. if (pindex->nHeight > nHeight)
  176. pindex = (*this)[nHeight];
  177. if (vHave.size() > 10)
  178. nStep *= 2;
  179. }
  180. return CBlockLocator(vHave);
  181. }
  182. CBlockIndex *CChain::FindFork(const CBlockLocator &locator) const {
  183. // Find the first block the caller has in the main chain
  184. BOOST_FOREACH(const uint256& hash, locator.vHave) {
  185. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  186. if (mi != mapBlockIndex.end())
  187. {
  188. CBlockIndex* pindex = (*mi).second;
  189. if (Contains(pindex))
  190. return pindex;
  191. }
  192. }
  193. return Genesis();
  194. }
  195. CCoinsViewCache *pcoinsTip = NULL;
  196. CBlockTreeDB *pblocktree = NULL;
  197. //////////////////////////////////////////////////////////////////////////////
  198. //
  199. // mapOrphanTransactions
  200. //
  201. bool AddOrphanTx(const CTransaction& tx)
  202. {
  203. uint256 hash = tx.GetHash();
  204. if (mapOrphanTransactions.count(hash))
  205. return false;
  206. // Ignore big transactions, to avoid a
  207. // send-big-orphans memory exhaustion attack. If a peer has a legitimate
  208. // large transaction with a missing parent then we assume
  209. // it will rebroadcast it later, after the parent transaction(s)
  210. // have been mined or received.
  211. // 10,000 orphans, each of which is at most 5,000 bytes big is
  212. // at most 500 megabytes of orphans:
  213. unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
  214. if (sz > 5000)
  215. {
  216. LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString().c_str());
  217. return false;
  218. }
  219. mapOrphanTransactions[hash] = tx;
  220. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  221. mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
  222. LogPrint("mempool", "stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().c_str(),
  223. mapOrphanTransactions.size());
  224. return true;
  225. }
  226. void static EraseOrphanTx(uint256 hash)
  227. {
  228. if (!mapOrphanTransactions.count(hash))
  229. return;
  230. const CTransaction& tx = mapOrphanTransactions[hash];
  231. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  232. {
  233. mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
  234. if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
  235. mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
  236. }
  237. mapOrphanTransactions.erase(hash);
  238. }
  239. unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
  240. {
  241. unsigned int nEvicted = 0;
  242. while (mapOrphanTransactions.size() > nMaxOrphans)
  243. {
  244. // Evict a random orphan:
  245. uint256 randomhash = GetRandHash();
  246. map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
  247. if (it == mapOrphanTransactions.end())
  248. it = mapOrphanTransactions.begin();
  249. EraseOrphanTx(it->first);
  250. ++nEvicted;
  251. }
  252. return nEvicted;
  253. }
  254. bool IsStandardTx(const CTransaction& tx, string& reason)
  255. {
  256. if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
  257. reason = "version";
  258. return false;
  259. }
  260. if (!IsFinalTx(tx)) {
  261. reason = "non-final";
  262. return false;
  263. }
  264. // Extremely large transactions with lots of inputs can cost the network
  265. // almost as much to process as they cost the sender in fees, because
  266. // computing signature hashes is O(ninputs*txsize). Limiting transactions
  267. // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
  268. unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
  269. if (sz >= MAX_STANDARD_TX_SIZE) {
  270. reason = "tx-size";
  271. return false;
  272. }
  273. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  274. {
  275. // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
  276. // pay-to-script-hash, which is 3 ~80-byte signatures, 3
  277. // ~65-byte public keys, plus a few script ops.
  278. if (txin.scriptSig.size() > 500) {
  279. reason = "scriptsig-size";
  280. return false;
  281. }
  282. if (!txin.scriptSig.IsPushOnly()) {
  283. reason = "scriptsig-not-pushonly";
  284. return false;
  285. }
  286. }
  287. unsigned int nDataOut = 0;
  288. txnouttype whichType;
  289. BOOST_FOREACH(const CTxOut& txout, tx.vout) {
  290. if (!::IsStandard(txout.scriptPubKey, whichType)) {
  291. reason = "scriptpubkey";
  292. return false;
  293. }
  294. if (whichType == TX_NULL_DATA)
  295. nDataOut++;
  296. else if (txout.IsDust(CTransaction::nMinRelayTxFee)) {
  297. reason = "dust";
  298. return false;
  299. }
  300. }
  301. // only one OP_RETURN txout is permitted
  302. if (nDataOut > 1) {
  303. reason = "mucho-data";
  304. return false;
  305. }
  306. return true;
  307. }
  308. bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime)
  309. {
  310. // Time based nLockTime implemented in 0.1.6
  311. if (tx.nLockTime == 0)
  312. return true;
  313. if (nBlockHeight == 0)
  314. nBlockHeight = chainActive.Height();
  315. if (nBlockTime == 0)
  316. nBlockTime = GetAdjustedTime();
  317. if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
  318. return true;
  319. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  320. if (!txin.IsFinal())
  321. return false;
  322. return true;
  323. }
  324. //
  325. // Check transaction inputs, and make sure any
  326. // pay-to-script-hash transactions are evaluating IsStandard scripts
  327. //
  328. // Why bother? To avoid denial-of-service attacks; an attacker
  329. // can submit a standard HASH... OP_EQUAL transaction,
  330. // which will get accepted into blocks. The redemption
  331. // script can be anything; an attacker could use a very
  332. // expensive-to-check-upon-redemption script like:
  333. // DUP CHECKSIG DROP ... repeated 100 times... OP_1
  334. //
  335. bool AreInputsStandard(const CTransaction& tx, CCoinsViewCache& mapInputs)
  336. {
  337. if (tx.IsCoinBase())
  338. return true; // Coinbases don't use vin normally
  339. for (unsigned int i = 0; i < tx.vin.size(); i++)
  340. {
  341. const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
  342. vector<vector<unsigned char> > vSolutions;
  343. txnouttype whichType;
  344. // get the scriptPubKey corresponding to this input:
  345. const CScript& prevScript = prev.scriptPubKey;
  346. if (!Solver(prevScript, whichType, vSolutions))
  347. return false;
  348. int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
  349. if (nArgsExpected < 0)
  350. return false;
  351. // Transactions with extra stuff in their scriptSigs are
  352. // non-standard. Note that this EvalScript() call will
  353. // be quick, because if there are any operations
  354. // beside "push data" in the scriptSig the
  355. // IsStandard() call returns false
  356. vector<vector<unsigned char> > stack;
  357. if (!EvalScript(stack, tx.vin[i].scriptSig, tx, i, false, 0))
  358. return false;
  359. if (whichType == TX_SCRIPTHASH)
  360. {
  361. if (stack.empty())
  362. return false;
  363. CScript subscript(stack.back().begin(), stack.back().end());
  364. vector<vector<unsigned char> > vSolutions2;
  365. txnouttype whichType2;
  366. if (!Solver(subscript, whichType2, vSolutions2))
  367. return false;
  368. if (whichType2 == TX_SCRIPTHASH)
  369. return false;
  370. int tmpExpected;
  371. tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
  372. if (tmpExpected < 0)
  373. return false;
  374. nArgsExpected += tmpExpected;
  375. }
  376. if (stack.size() != (unsigned int)nArgsExpected)
  377. return false;
  378. }
  379. return true;
  380. }
  381. unsigned int GetLegacySigOpCount(const CTransaction& tx)
  382. {
  383. unsigned int nSigOps = 0;
  384. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  385. {
  386. nSigOps += txin.scriptSig.GetSigOpCount(false);
  387. }
  388. BOOST_FOREACH(const CTxOut& txout, tx.vout)
  389. {
  390. nSigOps += txout.scriptPubKey.GetSigOpCount(false);
  391. }
  392. return nSigOps;
  393. }
  394. unsigned int GetP2SHSigOpCount(const CTransaction& tx, CCoinsViewCache& inputs)
  395. {
  396. if (tx.IsCoinBase())
  397. return 0;
  398. unsigned int nSigOps = 0;
  399. for (unsigned int i = 0; i < tx.vin.size(); i++)
  400. {
  401. const CTxOut &prevout = inputs.GetOutputFor(tx.vin[i]);
  402. if (prevout.scriptPubKey.IsPayToScriptHash())
  403. nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
  404. }
  405. return nSigOps;
  406. }
  407. int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
  408. {
  409. CBlock blockTmp;
  410. if (pblock == NULL) {
  411. CCoins coins;
  412. if (pcoinsTip->GetCoins(GetHash(), coins)) {
  413. CBlockIndex *pindex = chainActive[coins.nHeight];
  414. if (pindex) {
  415. if (!ReadBlockFromDisk(blockTmp, pindex))
  416. return 0;
  417. pblock = &blockTmp;
  418. }
  419. }
  420. }
  421. if (pblock) {
  422. // Update the tx's hashBlock
  423. hashBlock = pblock->GetHash();
  424. // Locate the transaction
  425. for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
  426. if (pblock->vtx[nIndex] == *(CTransaction*)this)
  427. break;
  428. if (nIndex == (int)pblock->vtx.size())
  429. {
  430. vMerkleBranch.clear();
  431. nIndex = -1;
  432. LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
  433. return 0;
  434. }
  435. // Fill in merkle branch
  436. vMerkleBranch = pblock->GetMerkleBranch(nIndex);
  437. }
  438. // Is the tx in a block that's in the main chain
  439. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  440. if (mi == mapBlockIndex.end())
  441. return 0;
  442. CBlockIndex* pindex = (*mi).second;
  443. if (!pindex || !chainActive.Contains(pindex))
  444. return 0;
  445. return chainActive.Height() - pindex->nHeight + 1;
  446. }
  447. bool CheckTransaction(const CTransaction& tx, CValidationState &state)
  448. {
  449. // Basic checks that don't depend on any context
  450. if (tx.vin.empty())
  451. return state.DoS(10, error("CheckTransaction() : vin empty"),
  452. REJECT_INVALID, "vin empty");
  453. if (tx.vout.empty())
  454. return state.DoS(10, error("CheckTransaction() : vout empty"),
  455. REJECT_INVALID, "vout empty");
  456. // Size limits
  457. if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
  458. return state.DoS(100, error("CheckTransaction() : size limits failed"),
  459. REJECT_INVALID, "oversize");
  460. // Check for negative or overflow output values
  461. int64_t nValueOut = 0;
  462. BOOST_FOREACH(const CTxOut& txout, tx.vout)
  463. {
  464. if (txout.nValue < 0)
  465. return state.DoS(100, error("CheckTransaction() : txout.nValue negative"),
  466. REJECT_INVALID, "vout negative");
  467. if (txout.nValue > MAX_MONEY)
  468. return state.DoS(100, error("CheckTransaction() : txout.nValue too high"),
  469. REJECT_INVALID, "vout too large");
  470. nValueOut += txout.nValue;
  471. if (!MoneyRange(nValueOut))
  472. return state.DoS(100, error("CheckTransaction() : txout total out of range"),
  473. REJECT_INVALID, "txout total too large");
  474. }
  475. // Check for duplicate inputs
  476. set<COutPoint> vInOutPoints;
  477. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  478. {
  479. if (vInOutPoints.count(txin.prevout))
  480. return state.DoS(100, error("CheckTransaction() : duplicate inputs"),
  481. REJECT_INVALID, "duplicate inputs");
  482. vInOutPoints.insert(txin.prevout);
  483. }
  484. if (tx.IsCoinBase())
  485. {
  486. if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
  487. return state.DoS(100, error("CheckTransaction() : coinbase script size"),
  488. REJECT_INVALID, "coinbase script too large");
  489. }
  490. else
  491. {
  492. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  493. if (txin.prevout.IsNull())
  494. return state.DoS(10, error("CheckTransaction() : prevout is null"),
  495. REJECT_INVALID, "prevout null");
  496. }
  497. return true;
  498. }
  499. int64_t GetMinFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree, enum GetMinFee_mode mode)
  500. {
  501. // Base fee is either nMinTxFee or nMinRelayTxFee
  502. int64_t nBaseFee = (mode == GMF_RELAY) ? tx.nMinRelayTxFee : tx.nMinTxFee;
  503. int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
  504. if (fAllowFree)
  505. {
  506. // There is a free transaction area in blocks created by most miners,
  507. // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
  508. // to be considered to fall into this category. We don't want to encourage sending
  509. // multiple transactions instead of one big transaction to avoid fees.
  510. // * If we are creating a transaction we allow transactions up to 1,000 bytes
  511. // to be considered safe and assume they can likely make it into this section.
  512. if (nBytes < (mode == GMF_SEND ? 1000 : (DEFAULT_BLOCK_PRIORITY_SIZE - 1000)))
  513. nMinFee = 0;
  514. }
  515. // This code can be removed after enough miners have upgraded to version 0.9.
  516. // Until then, be safe when sending and require a fee if any output
  517. // is less than CENT:
  518. if (nMinFee < nBaseFee && mode == GMF_SEND)
  519. {
  520. BOOST_FOREACH(const CTxOut& txout, tx.vout)
  521. if (txout.nValue < CENT)
  522. nMinFee = nBaseFee;
  523. }
  524. if (!MoneyRange(nMinFee))
  525. nMinFee = MAX_MONEY;
  526. return nMinFee;
  527. }
  528. bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransaction &tx, bool fLimitFree,
  529. bool* pfMissingInputs, bool fRejectInsaneFee)
  530. {
  531. if (pfMissingInputs)
  532. *pfMissingInputs = false;
  533. if (!CheckTransaction(tx, state))
  534. return error("AcceptToMemoryPool: : CheckTransaction failed");
  535. // Coinbase is only valid in a block, not as a loose transaction
  536. if (tx.IsCoinBase())
  537. return state.DoS(100, error("AcceptToMemoryPool: : coinbase as individual tx"),
  538. REJECT_INVALID, "coinbase");
  539. // Rather not work on nonstandard transactions (unless -testnet/-regtest)
  540. string reason;
  541. if (Params().NetworkID() == CChainParams::MAIN && !IsStandardTx(tx, reason))
  542. return state.DoS(0,
  543. error("AcceptToMemoryPool : nonstandard transaction: %s", reason.c_str()),
  544. REJECT_NONSTANDARD, reason);
  545. // is it already in the memory pool?
  546. uint256 hash = tx.GetHash();
  547. if (pool.exists(hash))
  548. return false;
  549. // Check for conflicts with in-memory transactions
  550. {
  551. LOCK(pool.cs); // protect pool.mapNextTx
  552. for (unsigned int i = 0; i < tx.vin.size(); i++)
  553. {
  554. COutPoint outpoint = tx.vin[i].prevout;
  555. if (pool.mapNextTx.count(outpoint))
  556. {
  557. // Disable replacement feature for now
  558. return false;
  559. }
  560. }
  561. }
  562. {
  563. CCoinsView dummy;
  564. CCoinsViewCache view(dummy);
  565. {
  566. LOCK(pool.cs);
  567. CCoinsViewMemPool viewMemPool(*pcoinsTip, pool);
  568. view.SetBackend(viewMemPool);
  569. // do we already have it?
  570. if (view.HaveCoins(hash))
  571. return false;
  572. // do all inputs exist?
  573. // Note that this does not check for the presence of actual outputs (see the next check for that),
  574. // only helps filling in pfMissingInputs (to determine missing vs spent).
  575. BOOST_FOREACH(const CTxIn txin, tx.vin) {
  576. if (!view.HaveCoins(txin.prevout.hash)) {
  577. if (pfMissingInputs)
  578. *pfMissingInputs = true;
  579. return false;
  580. }
  581. }
  582. // are the actual inputs available?
  583. if (!view.HaveInputs(tx))
  584. return state.Invalid(error("AcceptToMemoryPool : inputs already spent"),
  585. REJECT_DUPLICATE, "inputs spent");
  586. // Bring the best block into scope
  587. view.GetBestBlock();
  588. // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
  589. view.SetBackend(dummy);
  590. }
  591. // Check for non-standard pay-to-script-hash in inputs
  592. if (Params().NetworkID() == CChainParams::MAIN && !AreInputsStandard(tx, view))
  593. return error("AcceptToMemoryPool: : nonstandard transaction input");
  594. // Note: if you modify this code to accept non-standard transactions, then
  595. // you should add code here to check that the transaction does a
  596. // reasonable number of ECDSA signature verifications.
  597. int64_t nValueIn = view.GetValueIn(tx);
  598. int64_t nValueOut = tx.GetValueOut();
  599. int64_t nFees = nValueIn-nValueOut;
  600. double dPriority = view.GetPriority(tx, chainActive.Height());
  601. CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
  602. unsigned int nSize = entry.GetTxSize();
  603. // Don't accept it if it can't get into a block
  604. int64_t txMinFee = GetMinFee(tx, nSize, true, GMF_RELAY);
  605. if (fLimitFree && nFees < txMinFee)
  606. return state.DoS(0, error("AcceptToMemoryPool : not enough fees %s, %"PRId64" < %"PRId64,
  607. hash.ToString().c_str(), nFees, txMinFee),
  608. REJECT_INSUFFICIENTFEE, "insufficient fee");
  609. // Continuously rate-limit free transactions
  610. // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
  611. // be annoying or make others' transactions take longer to confirm.
  612. if (fLimitFree && nFees < CTransaction::nMinRelayTxFee)
  613. {
  614. static CCriticalSection csFreeLimiter;
  615. static double dFreeCount;
  616. static int64_t nLastTime;
  617. int64_t nNow = GetTime();
  618. LOCK(csFreeLimiter);
  619. // Use an exponentially decaying ~10-minute window:
  620. dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
  621. nLastTime = nNow;
  622. // -limitfreerelay unit is thousand-bytes-per-minute
  623. // At default rate it would take over a month to fill 1GB
  624. if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
  625. return state.DoS(0, error("AcceptToMemoryPool : free transaction rejected by rate limiter"),
  626. REJECT_INSUFFICIENTFEE, "insufficient priority");
  627. LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
  628. dFreeCount += nSize;
  629. }
  630. if (fRejectInsaneFee && nFees > CTransaction::nMinRelayTxFee * 10000)
  631. return error("AcceptToMemoryPool: : insane fees %s, %"PRId64" > %"PRId64,
  632. hash.ToString().c_str(),
  633. nFees, CTransaction::nMinRelayTxFee * 10000);
  634. // Check against previous transactions
  635. // This is done last to help prevent CPU exhaustion denial-of-service attacks.
  636. if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC))
  637. {
  638. return error("AcceptToMemoryPool: : ConnectInputs failed %s", hash.ToString().c_str());
  639. }
  640. // Store transaction in memory
  641. pool.addUnchecked(hash, entry);
  642. }
  643. g_signals.SyncTransaction(hash, tx, NULL);
  644. return true;
  645. }
  646. int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
  647. {
  648. if (hashBlock == 0 || nIndex == -1)
  649. return 0;
  650. // Find the block it claims to be in
  651. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  652. if (mi == mapBlockIndex.end())
  653. return 0;
  654. CBlockIndex* pindex = (*mi).second;
  655. if (!pindex || !chainActive.Contains(pindex))
  656. return 0;
  657. // Make sure the merkle branch connects to this block
  658. if (!fMerkleVerified)
  659. {
  660. if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
  661. return 0;
  662. fMerkleVerified = true;
  663. }
  664. pindexRet = pindex;
  665. return chainActive.Height() - pindex->nHeight + 1;
  666. }
  667. int CMerkleTx::GetBlocksToMaturity() const
  668. {
  669. if (!IsCoinBase())
  670. return 0;
  671. return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
  672. }
  673. bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree)
  674. {
  675. CValidationState state;
  676. return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL);
  677. }
  678. // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
  679. bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
  680. {
  681. CBlockIndex *pindexSlow = NULL;
  682. {
  683. LOCK(cs_main);
  684. {
  685. if (mempool.lookup(hash, txOut))
  686. {
  687. return true;
  688. }
  689. }
  690. if (fTxIndex) {
  691. CDiskTxPos postx;
  692. if (pblocktree->ReadTxIndex(hash, postx)) {
  693. CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
  694. CBlockHeader header;
  695. try {
  696. file >> header;
  697. fseek(file, postx.nTxOffset, SEEK_CUR);
  698. file >> txOut;
  699. } catch (std::exception &e) {
  700. return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
  701. }
  702. hashBlock = header.GetHash();
  703. if (txOut.GetHash() != hash)
  704. return error("%s() : txid mismatch", __PRETTY_FUNCTION__);
  705. return true;
  706. }
  707. }
  708. if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
  709. int nHeight = -1;
  710. {
  711. CCoinsViewCache &view = *pcoinsTip;
  712. CCoins coins;
  713. if (view.GetCoins(hash, coins))
  714. nHeight = coins.nHeight;
  715. }
  716. if (nHeight > 0)
  717. pindexSlow = chainActive[nHeight];
  718. }
  719. }
  720. if (pindexSlow) {
  721. CBlock block;
  722. if (ReadBlockFromDisk(block, pindexSlow)) {
  723. BOOST_FOREACH(const CTransaction &tx, block.vtx) {
  724. if (tx.GetHash() == hash) {
  725. txOut = tx;
  726. hashBlock = pindexSlow->GetBlockHash();
  727. return true;
  728. }
  729. }
  730. }
  731. }
  732. return false;
  733. }
  734. //////////////////////////////////////////////////////////////////////////////
  735. //
  736. // CBlock and CBlockIndex
  737. //
  738. bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos)
  739. {
  740. // Open history file to append
  741. CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
  742. if (!fileout)
  743. return error("WriteBlockToDisk() : OpenBlockFile failed");
  744. // Write index header
  745. unsigned int nSize = fileout.GetSerializeSize(block);
  746. fileout << FLATDATA(Params().MessageStart()) << nSize;
  747. // Write block
  748. long fileOutPos = ftell(fileout);
  749. if (fileOutPos < 0)
  750. return error("WriteBlockToDisk() : ftell failed");
  751. pos.nPos = (unsigned int)fileOutPos;
  752. fileout << block;
  753. // Flush stdio buffers and commit to disk before returning
  754. fflush(fileout);
  755. if (!IsInitialBlockDownload())
  756. FileCommit(fileout);
  757. return true;
  758. }
  759. bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
  760. {
  761. block.SetNull();
  762. // Open history file to read
  763. CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
  764. if (!filein)
  765. return error("ReadBlockFromDisk(CBlock&, CDiskBlockPos&) : OpenBlockFile failed");
  766. // Read block
  767. try {
  768. filein >> block;
  769. }
  770. catch (std::exception &e) {
  771. return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
  772. }
  773. // Check the header
  774. if (!CheckProofOfWork(block.GetHash(), block.nBits))
  775. return error("ReadBlockFromDisk(CBlock&, CDiskBlockPos&) : errors in block header");
  776. return true;
  777. }
  778. bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
  779. {
  780. if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
  781. return false;
  782. if (block.GetHash() != pindex->GetBlockHash())
  783. return error("ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index");
  784. return true;
  785. }
  786. uint256 static GetOrphanRoot(const CBlockHeader* pblock)
  787. {
  788. // Work back to the first block in the orphan chain
  789. while (mapOrphanBlocks.count(pblock->hashPrevBlock))
  790. pblock = mapOrphanBlocks[pblock->hashPrevBlock];
  791. return pblock->GetHash();
  792. }
  793. int64_t GetBlockValue(int nHeight, int64_t nFees)
  794. {
  795. int64_t nSubsidy = 50 * COIN;
  796. // Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
  797. nSubsidy >>= (nHeight / Params().SubsidyHalvingInterval());
  798. return nSubsidy + nFees;
  799. }
  800. static const int64_t nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
  801. static const int64_t nTargetSpacing = 10 * 60;
  802. static const int64_t nInterval = nTargetTimespan / nTargetSpacing;
  803. //
  804. // minimum amount of work that could possibly be required nTime after
  805. // minimum work required was nBase
  806. //
  807. unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
  808. {
  809. const CBigNum &bnLimit = Params().ProofOfWorkLimit();
  810. // Testnet has min-difficulty blocks
  811. // after nTargetSpacing*2 time between blocks:
  812. if (TestNet() && nTime > nTargetSpacing*2)
  813. return bnLimit.GetCompact();
  814. CBigNum bnResult;
  815. bnResult.SetCompact(nBase);
  816. while (nTime > 0 && bnResult < bnLimit)
  817. {
  818. // Maximum 400% adjustment...
  819. bnResult *= 4;
  820. // ... in best-case exactly 4-times-normal target time
  821. nTime -= nTargetTimespan*4;
  822. }
  823. if (bnResult > bnLimit)
  824. bnResult = bnLimit;
  825. return bnResult.GetCompact();
  826. }
  827. unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
  828. {
  829. unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact();
  830. // Genesis block
  831. if (pindexLast == NULL)
  832. return nProofOfWorkLimit;
  833. // Only change once per interval
  834. if ((pindexLast->nHeight+1) % nInterval != 0)
  835. {
  836. if (TestNet())
  837. {
  838. // Special difficulty rule for testnet:
  839. // If the new block's timestamp is more than 2* 10 minutes
  840. // then allow mining of a min-difficulty block.
  841. if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
  842. return nProofOfWorkLimit;
  843. else
  844. {
  845. // Return the last non-special-min-difficulty-rules-block
  846. const CBlockIndex* pindex = pindexLast;
  847. while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
  848. pindex = pindex->pprev;
  849. return pindex->nBits;
  850. }
  851. }
  852. return pindexLast->nBits;
  853. }
  854. // Go back by what we want to be 14 days worth of blocks
  855. const CBlockIndex* pindexFirst = pindexLast;
  856. for (int i = 0; pindexFirst && i < nInterval-1; i++)
  857. pindexFirst = pindexFirst->pprev;
  858. assert(pindexFirst);
  859. // Limit adjustment step
  860. int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
  861. LogPrintf(" nActualTimespan = %"PRId64" before bounds\n", nActualTimespan);
  862. if (nActualTimespan < nTargetTimespan/4)
  863. nActualTimespan = nTargetTimespan/4;
  864. if (nActualTimespan > nTargetTimespan*4)
  865. nActualTimespan = nTargetTimespan*4;
  866. // Retarget
  867. CBigNum bnNew;
  868. bnNew.SetCompact(pindexLast->nBits);
  869. bnNew *= nActualTimespan;
  870. bnNew /= nTargetTimespan;
  871. if (bnNew > Params().ProofOfWorkLimit())
  872. bnNew = Params().ProofOfWorkLimit();
  873. /// debug print
  874. LogPrintf("GetNextWorkRequired RETARGET\n");
  875. LogPrintf("nTargetTimespan = %"PRId64" nActualTimespan = %"PRId64"\n", nTargetTimespan, nActualTimespan);
  876. LogPrintf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
  877. LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
  878. return bnNew.GetCompact();
  879. }
  880. bool CheckProofOfWork(uint256 hash, unsigned int nBits)
  881. {
  882. CBigNum bnTarget;
  883. bnTarget.SetCompact(nBits);
  884. // Check range
  885. if (bnTarget <= 0 || bnTarget > Params().ProofOfWorkLimit())
  886. return error("CheckProofOfWork() : nBits below minimum work");
  887. // Check proof of work matches claimed amount
  888. if (hash > bnTarget.getuint256())
  889. return error("CheckProofOfWork() : hash doesn't match nBits");
  890. return true;
  891. }
  892. // Return maximum amount of blocks that other nodes claim to have
  893. int GetNumBlocksOfPeers()
  894. {
  895. return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
  896. }
  897. bool IsInitialBlockDownload()
  898. {
  899. if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
  900. return true;
  901. static int64_t nLastUpdate;
  902. static CBlockIndex* pindexLastBest;
  903. if (chainActive.Tip() != pindexLastBest)
  904. {
  905. pindexLastBest = chainActive.Tip();
  906. nLastUpdate = GetTime();
  907. }
  908. return (GetTime() - nLastUpdate < 10 &&
  909. chainActive.Tip()->GetBlockTime() < GetTime() - 24 * 60 * 60);
  910. }
  911. bool fLargeWorkForkFound = false;
  912. bool fLargeWorkInvalidChainFound = false;
  913. CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
  914. void CheckForkWarningConditions()
  915. {
  916. // Before we get past initial download, we cannot reliably alert about forks
  917. // (we assume we don't get stuck on a fork before the last checkpoint)
  918. if (IsInitialBlockDownload())
  919. return;
  920. // If our best fork is no longer within 72 blocks (+/- 12 hours if no one mines it)
  921. // of our head, drop it
  922. if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
  923. pindexBestForkTip = NULL;
  924. if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (chainActive.Tip()->GetBlockWork() * 6).getuint256()))
  925. {
  926. if (!fLargeWorkForkFound)
  927. {
  928. std::string strCmd = GetArg("-alertnotify", "");
  929. if (!strCmd.empty())
  930. {
  931. std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
  932. pindexBestForkBase->phashBlock->ToString() + std::string("'");
  933. boost::replace_all(strCmd, "%s", warning);
  934. boost::thread t(runCommand, strCmd); // thread runs free
  935. }
  936. }
  937. if (pindexBestForkTip)
  938. {
  939. LogPrintf("CheckForkWarningConditions: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n",
  940. pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString().c_str(),
  941. pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString().c_str());
  942. fLargeWorkForkFound = true;
  943. }
  944. else
  945. {
  946. LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
  947. fLargeWorkInvalidChainFound = true;
  948. }
  949. }
  950. else
  951. {
  952. fLargeWorkForkFound = false;
  953. fLargeWorkInvalidChainFound = false;
  954. }
  955. }
  956. void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
  957. {
  958. // If we are on a fork that is sufficiently large, set a warning flag
  959. CBlockIndex* pfork = pindexNewForkTip;
  960. CBlockIndex* plonger = chainActive.Tip();
  961. while (pfork && pfork != plonger)
  962. {
  963. while (plonger && plonger->nHeight > pfork->nHeight)
  964. plonger = plonger->pprev;
  965. if (pfork == plonger)
  966. break;
  967. pfork = pfork->pprev;
  968. }
  969. // We define a condition which we should warn the user about as a fork of at least 7 blocks
  970. // who's tip is within 72 blocks (+/- 12 hours if no one mines it) of ours
  971. // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
  972. // hash rate operating on the fork.
  973. // or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
  974. // We define it this way because it allows us to only store the highest fork tip (+ base) which meets
  975. // the 7-block condition and from this always have the most-likely-to-cause-warning fork
  976. if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
  977. pindexNewForkTip->nChainWork - pfork->nChainWork > (pfork->GetBlockWork() * 7).getuint256() &&
  978. chainActive.Height() - pindexNewForkTip->nHeight < 72)
  979. {
  980. pindexBestForkTip = pindexNewForkTip;
  981. pindexBestForkBase = pfork;
  982. }
  983. CheckForkWarningConditions();
  984. }
  985. void static InvalidChainFound(CBlockIndex* pindexNew)
  986. {
  987. if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
  988. {
  989. pindexBestInvalid = pindexNew;
  990. // The current code doesn't actually read the BestInvalidWork entry in
  991. // the block database anymore, as it is derived from the flags in block
  992. // index entry. We only write it for backward compatibility.
  993. pblocktree->WriteBestInvalidWork(CBigNum(pindexBestInvalid->nChainWork));
  994. uiInterface.NotifyBlocksChanged();
  995. }
  996. LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
  997. pindexNew->GetBlockHash().ToString().c_str(), pindexNew->nHeight,
  998. log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
  999. pindexNew->GetBlockTime()).c_str());
  1000. LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
  1001. chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
  1002. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str());
  1003. CheckForkWarningConditions();
  1004. }
  1005. void static InvalidBlockFound(CBlockIndex *pindex) {
  1006. pindex->nStatus |= BLOCK_FAILED_VALID;
  1007. pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
  1008. setBlockIndexValid.erase(pindex);
  1009. InvalidChainFound(pindex);
  1010. if (chainActive.Next(pindex)) {
  1011. CValidationState stateDummy;
  1012. ConnectBestBlock(stateDummy); // reorganise away from the failed block
  1013. }
  1014. }
  1015. bool ConnectBestBlock(CValidationState &state) {
  1016. do {
  1017. CBlockIndex *pindexNewBest;
  1018. {
  1019. std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
  1020. if (it == setBlockIndexValid.rend())
  1021. return true;
  1022. pindexNewBest = *it;
  1023. }
  1024. if (pindexNewBest == chainActive.Tip() || (chainActive.Tip() && pindexNewBest->nChainWork == chainActive.Tip()->nChainWork))
  1025. return true; // nothing to do
  1026. // check ancestry
  1027. CBlockIndex *pindexTest = pindexNewBest;
  1028. std::vector<CBlockIndex*> vAttach;
  1029. do {
  1030. if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
  1031. // mark descendants failed
  1032. CBlockIndex *pindexFailed = pindexNewBest;
  1033. while (pindexTest != pindexFailed) {
  1034. pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
  1035. setBlockIndexValid.erase(pindexFailed);
  1036. pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
  1037. pindexFailed = pindexFailed->pprev;
  1038. }
  1039. InvalidChainFound(pindexNewBest);
  1040. break;
  1041. }
  1042. if (chainActive.Tip() == NULL || pindexTest->nChainWork > chainActive.Tip()->nChainWork)
  1043. vAttach.push_back(pindexTest);
  1044. if (pindexTest->pprev == NULL || chainActive.Next(pindexTest)) {
  1045. reverse(vAttach.begin(), vAttach.end());
  1046. BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) {
  1047. boost::this_thread::interruption_point();
  1048. try {
  1049. if (!SetBestChain(state, pindexSwitch))
  1050. return false;
  1051. } catch(std::runtime_error &e) {
  1052. return state.Abort(_("System error: ") + e.what());
  1053. }
  1054. }
  1055. return true;
  1056. }
  1057. pindexTest = pindexTest->pprev;
  1058. } while(true);
  1059. } while(true);
  1060. }
  1061. void UpdateTime(CBlockHeader& block, const CBlockIndex* pindexPrev)
  1062. {
  1063. block.nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
  1064. // Updating time can change work required on testnet:
  1065. if (TestNet())
  1066. block.nBits = GetNextWorkRequired(pindexPrev, &block);
  1067. }
  1068. void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash)
  1069. {
  1070. bool ret;
  1071. // mark inputs spent
  1072. if (!tx.IsCoinBase()) {
  1073. BOOST_FOREACH(const CTxIn &txin, tx.vin) {
  1074. CCoins &coins = inputs.GetCoins(txin.prevout.hash);
  1075. CTxInUndo undo;
  1076. ret = coins.Spend(txin.prevout, undo);
  1077. assert(ret);
  1078. txundo.vprevout.push_back(undo);
  1079. }
  1080. }
  1081. // add outputs
  1082. ret = inputs.SetCoins(txhash, CCoins(tx, nHeight));
  1083. assert(ret);
  1084. }
  1085. bool CScriptCheck::operator()() const {
  1086. const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
  1087. if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
  1088. return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().c_str());
  1089. return true;
  1090. }
  1091. bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
  1092. {
  1093. return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
  1094. }
  1095. bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
  1096. {
  1097. if (!tx.IsCoinBase())
  1098. {
  1099. if (pvChecks)
  1100. pvChecks->reserve(tx.vin.size());
  1101. // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
  1102. // for an attacker to attempt to split the network.
  1103. if (!inputs.HaveInputs(tx))
  1104. return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString().c_str()));
  1105. // While checking, GetBestBlock() refers to the parent block.
  1106. // This is also true for mempool checks.
  1107. CBlockIndex *pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
  1108. int nSpendHeight = pindexPrev->nHeight + 1;
  1109. int64_t nValueIn = 0;
  1110. int64_t nFees = 0;
  1111. for (unsigned int i = 0; i < tx.vin.size(); i++)
  1112. {
  1113. const COutPoint &prevout = tx.vin[i].prevout;
  1114. const CCoins &coins = inputs.GetCoins(prevout.hash);
  1115. // If prev is coinbase, check that it's matured
  1116. if (coins.IsCoinBase()) {
  1117. if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
  1118. return state.Invalid(
  1119. error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight),
  1120. REJECT_INVALID, "premature spend of coinbase");
  1121. }
  1122. // Check for negative or overflow input values
  1123. nValueIn += coins.vout[prevout.n].nValue;
  1124. if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
  1125. return state.DoS(100, error("CheckInputs() : txin values out of range"),
  1126. REJECT_INVALID, "input values out of range");
  1127. }
  1128. if (nValueIn < tx.GetValueOut())
  1129. return state.DoS(100, error("CheckInputs() : %s value in < value out", tx.GetHash().ToString().c_str()),
  1130. REJECT_INVALID, "in < out");
  1131. // Tally transaction fees
  1132. int64_t nTxFee = nValueIn - tx.GetValueOut();
  1133. if (nTxFee < 0)
  1134. return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString().c_str()),
  1135. REJECT_INVALID, "fee < 0");
  1136. nFees += nTxFee;
  1137. if (!MoneyRange(nFees))
  1138. return state.DoS(100, error("CheckInputs() : nFees out of range"),
  1139. REJECT_INVALID, "fee out of range");
  1140. // The first loop above does all the inexpensive checks.
  1141. // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
  1142. // Helps prevent CPU exhaustion attacks.
  1143. // Skip ECDSA signature verification when connecting blocks
  1144. // before the last block chain checkpoint. This is safe because block merkle hashes are
  1145. // still computed and checked, and any change will be caught at the next checkpoint.
  1146. if (fScriptChecks) {
  1147. for (unsigned int i = 0; i < tx.vin.size(); i++) {
  1148. const COutPoint &prevout = tx.vin[i].prevout;
  1149. const CCoins &coins = inputs.GetCoins(prevout.hash);
  1150. // Verify signature
  1151. CScriptCheck check(coins, tx, i, flags, 0);
  1152. if (pvChecks) {
  1153. pvChecks->push_back(CScriptCheck());
  1154. check.swap(pvChecks->back());
  1155. } else if (!check()) {
  1156. if (flags & SCRIPT_VERIFY_STRICTENC) {
  1157. // For now, check whether the failure was caused by non-canonical
  1158. // encodings or not; if so, don't trigger DoS protection.
  1159. CScriptCheck check(coins, tx, i, flags & (~SCRIPT_VERIFY_STRICTENC), 0);
  1160. if (check())
  1161. return state.Invalid(false, REJECT_NONSTANDARD, "non-canonical");
  1162. }
  1163. return state.DoS(100,false, REJECT_NONSTANDARD, "non-canonical");
  1164. }
  1165. }
  1166. }
  1167. }
  1168. return true;
  1169. }
  1170. bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
  1171. {
  1172. assert(pindex->GetBlockHash() == view.GetBestBlock());
  1173. if (pfClean)
  1174. *pfClean = false;
  1175. bool fClean = true;
  1176. CBlockUndo blockUndo;
  1177. CDiskBlockPos pos = pindex->GetUndoPos();
  1178. if (pos.IsNull())
  1179. return error("DisconnectBlock() : no undo data available");
  1180. if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
  1181. return error("DisconnectBlock() : failure reading undo data");
  1182. if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
  1183. return error("DisconnectBlock() : block and undo data inconsistent");
  1184. // undo transactions in reverse order
  1185. for (int i = block.vtx.size() - 1; i >= 0; i--) {
  1186. const CTransaction &tx = block.vtx[i];
  1187. uint256 hash = tx.GetHash();
  1188. // Check that all outputs are available and match the outputs in the block itself
  1189. // exactly. Note that transactions with only provably unspendable outputs won't
  1190. // have outputs available even in the block itself, so we handle that case
  1191. // specially with outsEmpty.
  1192. CCoins outsEmpty;
  1193. CCoins &outs = view.HaveCoins(hash) ? view.GetCoins(hash) : outsEmpty;
  1194. outs.ClearUnspendable();
  1195. CCoins outsBlock = CCoins(tx, pindex->nHeight);
  1196. // The CCoins serialization does not serialize negative numbers.
  1197. // No network rules currently depend on the version here, so an inconsistency is harmless
  1198. // but it must be corrected before txout nversion ever influences a network rule.
  1199. if (outsBlock.nVersion < 0)
  1200. outs.nVersion = outsBlock.nVersion;
  1201. if (outs != outsBlock)
  1202. fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
  1203. // remove outputs
  1204. outs = CCoins();
  1205. // restore inputs
  1206. if (i > 0) { // not coinbases
  1207. const CTxUndo &txundo = blockUndo.vtxundo[i-1];
  1208. if (txundo.vprevout.size() != tx.vin.size())
  1209. return error("DisconnectBlock() : transaction and undo data inconsistent");
  1210. for (unsigned int j = tx.vin.size(); j-- > 0;) {
  1211. const COutPoint &out = tx.vin[j].prevout;
  1212. const CTxInUndo &undo = txundo.vprevout[j];
  1213. CCoins coins;
  1214. view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
  1215. if (undo.nHeight != 0) {
  1216. // undo data contains height: this is the last output of the prevout tx being spent
  1217. if (!coins.IsPruned())
  1218. fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
  1219. coins = CCoins();
  1220. coins.fCoinBase = undo.fCoinBase;
  1221. coins.nHeight = undo.nHeight;
  1222. coins.nVersion = undo.nVersion;
  1223. } else {
  1224. if (coins.IsPruned())
  1225. fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
  1226. }
  1227. if (coins.IsAvailable(out.n))
  1228. fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
  1229. if (coins.vout.size() < out.n+1)
  1230. coins.vout.resize(out.n+1);
  1231. coins.vout[out.n] = undo.txout;
  1232. if (!view.SetCoins(out.hash, coins))
  1233. return error("DisconnectBlock() : cannot restore coin inputs");
  1234. }
  1235. }
  1236. }
  1237. // move best block pointer to prevout block
  1238. view.SetBestBlock(pindex->pprev->GetBlockHash());
  1239. if (pfClean) {
  1240. *pfClean = fClean;
  1241. return true;
  1242. } else {
  1243. return fClean;
  1244. }
  1245. }
  1246. void static FlushBlockFile(bool fFinalize = false)
  1247. {
  1248. LOCK(cs_LastBlockFile);
  1249. CDiskBlockPos posOld(nLastBlockFile, 0);
  1250. FILE *fileOld = OpenBlockFile(posOld);
  1251. if (fileOld) {
  1252. if (fFinalize)
  1253. TruncateFile(fileOld, infoLastBlockFile.nSize);
  1254. FileCommit(fileOld);
  1255. fclose(fileOld);
  1256. }
  1257. fileOld = OpenUndoFile(posOld);
  1258. if (fileOld) {
  1259. if (fFinalize)
  1260. TruncateFile(fileOld, infoLastBlockFile.nUndoSize);
  1261. FileCommit(fileOld);
  1262. fclose(fileOld);
  1263. }
  1264. }
  1265. bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
  1266. static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
  1267. void ThreadScriptCheck() {
  1268. RenameThread("bitcoin-scriptch");
  1269. scriptcheckqueue.Thread();
  1270. }
  1271. bool ConnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck)
  1272. {
  1273. // Check it again in case a previous version let a bad block in
  1274. if (!CheckBlock(block, state, !fJustCheck, !fJustCheck))
  1275. return false;
  1276. // verify that the view's current state corresponds to the previous block
  1277. uint256 hashPrevBlock = pindex->pprev == NULL ? uint256(0) : pindex->pprev->GetBlockHash();
  1278. assert(hashPrevBlock == view.GetBestBlock());
  1279. // Special case for the genesis block, skipping connection of its transactions
  1280. // (its coinbase is unspendable)
  1281. if (block.GetHash() == Params().HashGenesisBlock()) {
  1282. view.SetBestBlock(pindex->GetBlockHash());
  1283. return true;
  1284. }
  1285. bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
  1286. // Do not allow blocks that contain transactions which 'overwrite' older transactions,
  1287. // unless those are already completely spent.
  1288. // If such overwrites are allowed, coinbases and transactions depending upon those
  1289. // can be duplicated to remove the ability to spend the first instance -- even after
  1290. // being sent to another address.
  1291. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
  1292. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
  1293. // already refuses previously-known transaction ids entirely.
  1294. // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
  1295. // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
  1296. // two in the chain that violate it. This prevents exploiting the issue against nodes in their
  1297. // initial block download.
  1298. bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
  1299. !((pindex->nHeight==91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
  1300. (pindex->nHeight==91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
  1301. if (fEnforceBIP30) {
  1302. for (unsigned int i = 0; i < block.vtx.size(); i++) {
  1303. uint256 hash = block.GetTxHash(i);
  1304. if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
  1305. return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"),
  1306. REJECT_INVALID, "BIP30");
  1307. }
  1308. }
  1309. // BIP16 didn't become active until Apr 1 2012
  1310. int64_t nBIP16SwitchTime = 1333238400;
  1311. bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
  1312. unsigned int flags = SCRIPT_VERIFY_NOCACHE |
  1313. (fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE);
  1314. CBlockUndo blockundo;
  1315. CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
  1316. int64_t nStart = GetTimeMicros();
  1317. int64_t nFees = 0;
  1318. int nInputs = 0;
  1319. unsigned int nSigOps = 0;
  1320. CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
  1321. std::vector<std::pair<uint256, CDiskTxPos> > vPos;
  1322. vPos.reserve(block.vtx.size());
  1323. for (unsigned int i = 0; i < block.vtx.size(); i++)
  1324. {
  1325. const CTransaction &tx = block.vtx[i];
  1326. nInputs += tx.vin.size();
  1327. nSigOps += GetLegacySigOpCount(tx);
  1328. if (nSigOps > MAX_BLOCK_SIGOPS)
  1329. return state.DoS(100, error("ConnectBlock() : too many sigops"),
  1330. REJECT_INVALID, "too many sigops");
  1331. if (!tx.IsCoinBase())
  1332. {
  1333. if (!view.HaveInputs(tx))
  1334. return state.DoS(100, error("ConnectBlock() : inputs missing/spent"),
  1335. REJECT_INVALID, "inputs missing/spent");
  1336. if (fStrictPayToScriptHash)
  1337. {
  1338. // Add in sigops done by pay-to-script-hash inputs;
  1339. // this is to prevent a "rogue miner" from creating
  1340. // an incredibly-expensive-to-validate block.
  1341. nSigOps += GetP2SHSigOpCount(tx, view);
  1342. if (nSigOps > MAX_BLOCK_SIGOPS)
  1343. return state.DoS(100, error("ConnectBlock() : too many sigops"),
  1344. REJECT_INVALID, "too many sigops");
  1345. }
  1346. nFees += view.GetValueIn(tx)-tx.GetValueOut();
  1347. std::vector<CScriptCheck> vChecks;
  1348. if (!CheckInputs(tx, state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
  1349. return false;
  1350. control.Add(vChecks);
  1351. }
  1352. CTxUndo txundo;
  1353. UpdateCoins(tx, state, view, txundo, pindex->nHeight, block.GetTxHash(i));
  1354. if (!tx.IsCoinBase())
  1355. blockundo.vtxundo.push_back(txundo);
  1356. vPos.push_back(std::make_pair(block.GetTxHash(i), pos));
  1357. pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
  1358. }
  1359. int64_t nTime = GetTimeMicros() - nStart;
  1360. if (fBenchmark)
  1361. LogPrintf("- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (unsigned)block.vtx.size(), 0.001 * nTime, 0.001 * nTime / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
  1362. if (block.vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
  1363. return state.DoS(100,
  1364. error("ConnectBlock() : coinbase pays too much (actual=%"PRId64" vs limit=%"PRId64")",
  1365. block.vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)),
  1366. REJECT_INVALID, "coinbase too large");
  1367. if (!control.Wait())
  1368. return state.DoS(100, false);
  1369. int64_t nTime2 = GetTimeMicros() - nStart;
  1370. if (fBenchmark)
  1371. LogPrintf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
  1372. if (fJustCheck)
  1373. return true;
  1374. // Write undo information to disk
  1375. if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
  1376. {
  1377. if (pindex->GetUndoPos().IsNull()) {
  1378. CDiskBlockPos pos;
  1379. if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
  1380. return error("ConnectBlock() : FindUndoPos failed");
  1381. if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
  1382. return state.Abort(_("Failed to write undo data"));
  1383. // update nUndoPos in block index
  1384. pindex->nUndoPos = pos.nPos;
  1385. pindex->nStatus |= BLOCK_HAVE_UNDO;
  1386. }
  1387. pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
  1388. CDiskBlockIndex blockindex(pindex);
  1389. if (!pblocktree->WriteBlockIndex(blockindex))
  1390. return state.Abort(_("Failed to write block index"));
  1391. }
  1392. if (fTxIndex)
  1393. if (!pblocktree->WriteTxIndex(vPos))
  1394. return state.Abort(_("Failed to write transaction index"));
  1395. // add this block to the view's block chain
  1396. bool ret;
  1397. ret = view.SetBestBlock(pindex->GetBlockHash());
  1398. assert(ret);
  1399. // Watch for transactions paying to me
  1400. for (unsigned int i = 0; i < block.vtx.size(); i++)
  1401. g_signals.SyncTransaction(block.GetTxHash(i), block.vtx[i], &block);
  1402. return true;
  1403. }
  1404. bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
  1405. {
  1406. mempool.check(pcoinsTip);
  1407. // All modifications to the coin state will be done in this cache.
  1408. // Only when all have succeeded, we push it to pcoinsTip.
  1409. CCoinsViewCache view(*pcoinsTip, true);
  1410. // Find the fork (typically, there is none)
  1411. std::map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(view.GetBestBlock());
  1412. CBlockIndex* ptip = (it != mapBlockIndex.end()) ? it->second : NULL;
  1413. CBlockIndex* pfork = ptip;
  1414. CBlockIndex* plonger = pindexNew;
  1415. while (pfork && pfork != plonger)
  1416. {
  1417. while (plonger->nHeight > pfork->nHeight) {
  1418. plonger = plonger->pprev;
  1419. assert(plonger != NULL);
  1420. }
  1421. if (pfork == plonger)
  1422. break;
  1423. pfork = pfork->pprev;
  1424. assert(pfork != NULL);
  1425. }
  1426. // List of what to disconnect (typically nothing)
  1427. vector<CBlockIndex*> vDisconnect;
  1428. for (CBlockIndex* pindex = ptip; pindex != pfork; pindex = pindex->pprev)
  1429. vDisconnect.push_back(pindex);
  1430. // List of what to connect (typically only pindexNew)
  1431. vector<CBlockIndex*> vConnect;
  1432. for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
  1433. vConnect.push_back(pindex);
  1434. reverse(vConnect.begin(), vConnect.end());
  1435. if (vDisconnect.size() > 0) {
  1436. LogPrintf("REORGANIZE: Disconnect %"PRIszu" blocks; %s...\n", vDisconnect.size(), pfork->GetBlockHash().ToString().c_str());
  1437. LogPrintf("REORGANIZE: Connect %"PRIszu" blocks; ...%s\n", vConnect.size(), pindexNew->GetBlockHash().ToString().c_str());
  1438. }
  1439. // Disconnect shorter branch
  1440. list<CTransaction> vResurrect;
  1441. BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
  1442. CBlock block;
  1443. if (!ReadBlockFromDisk(block, pindex))
  1444. return state.Abort(_("Failed to read block"));
  1445. int64_t nStart = GetTimeMicros();
  1446. if (!DisconnectBlock(block, state, pindex, view))
  1447. return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
  1448. if (fBenchmark)
  1449. LogPrintf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
  1450. // Queue memory transactions to resurrect.
  1451. // We only do this for blocks after the last checkpoint (reorganisation before that
  1452. // point should only happen with -reindex/-loadblock, or a misbehaving peer.
  1453. BOOST_REVERSE_FOREACH(const CTransaction& tx, block.vtx)
  1454. if (!tx.IsCoinBase() && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
  1455. vResurrect.push_front(tx);
  1456. }
  1457. // Connect longer branch
  1458. vector<CTransaction> vDelete;
  1459. BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
  1460. CBlock block;
  1461. if (!ReadBlockFromDisk(block, pindex))
  1462. return state.Abort(_("Failed to read block"));
  1463. int64_t nStart = GetTimeMicros();
  1464. if (!ConnectBlock(block, state, pindex, view)) {
  1465. if (state.IsInvalid()) {
  1466. InvalidChainFound(pindexNew);
  1467. InvalidBlockFound(pindex);
  1468. }
  1469. return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
  1470. }
  1471. if (fBenchmark)
  1472. LogPrintf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
  1473. // Queue memory transactions to delete
  1474. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  1475. vDelete.push_back(tx);
  1476. }
  1477. // Flush changes to global coin state
  1478. int64_t nStart = GetTimeMicros();
  1479. int nModified = view.GetCacheSize();
  1480. bool ret;
  1481. ret = view.Flush();
  1482. assert(ret);
  1483. int64_t nTime = GetTimeMicros() - nStart;
  1484. if (fBenchmark)
  1485. LogPrintf("- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified);
  1486. // Make sure it's successfully written to disk before changing memory structure
  1487. bool fIsInitialDownload = IsInitialBlockDownload();
  1488. if (!fIsInitialDownload || pcoinsTip->GetCacheSize() > nCoinCacheSize) {
  1489. // Typical CCoins structures on disk are around 100 bytes in size.
  1490. // Pushing a new one to the database can cause it to be written
  1491. // twice (once in the log, and once in the tables). This is already
  1492. // an overestimation, as most will delete an existing entry or
  1493. // overwrite one. Still, use a conservative safety factor of 2.
  1494. if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
  1495. return state.Error();
  1496. FlushBlockFile();
  1497. pblocktree->Sync();
  1498. if (!pcoinsTip->Flush())
  1499. return state.Abort(_("Failed to write to coin database"));
  1500. }
  1501. // At this point, all changes have been done to the database.
  1502. // Proceed by updating the memory structures.
  1503. // Register new best chain
  1504. chainActive.SetTip(pindexNew);
  1505. // Resurrect memory transactions that were in the disconnected branch
  1506. BOOST_FOREACH(CTransaction& tx, vResurrect) {
  1507. // ignore validation errors in resurrected transactions
  1508. CValidationState stateDummy;
  1509. if (!AcceptToMemoryPool(mempool,stateDummy, tx, false, NULL))
  1510. mempool.remove(tx, true);
  1511. }
  1512. // Delete redundant memory transactions that are in the connected branch
  1513. BOOST_FOREACH(CTransaction& tx, vDelete) {
  1514. mempool.remove(tx);
  1515. mempool.removeConflicts(tx);
  1516. }
  1517. mempool.check(pcoinsTip);
  1518. // Update best block in wallet (so we can detect restored wallets)
  1519. if ((pindexNew->nHeight % 20160) == 0 || (!fIsInitialDownload && (pindexNew->nHeight % 144) == 0))
  1520. g_signals.SetBestChain(chainActive.GetLocator(pindexNew));
  1521. // New best block
  1522. nTimeBestReceived = GetTime();
  1523. mempool.AddTransactionsUpdated(1);
  1524. LogPrintf("SetBestChain: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n",
  1525. chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
  1526. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str(),
  1527. Checkpoints::GuessVerificationProgress(chainActive.Tip()));
  1528. // Check the version of the last 100 blocks to see if we need to upgrade:
  1529. if (!fIsInitialDownload)
  1530. {
  1531. int nUpgraded = 0;
  1532. const CBlockIndex* pindex = chainActive.Tip();
  1533. for (int i = 0; i < 100 && pindex != NULL; i++)
  1534. {
  1535. if (pindex->nVersion > CBlock::CURRENT_VERSION)
  1536. ++nUpgraded;
  1537. pindex = pindex->pprev;
  1538. }
  1539. if (nUpgraded > 0)
  1540. LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
  1541. if (nUpgraded > 100/2)
  1542. // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
  1543. strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
  1544. }
  1545. std::string strCmd = GetArg("-blocknotify", "");
  1546. if (!fIsInitialDownload && !strCmd.empty())
  1547. {
  1548. boost::replace_all(strCmd, "%s", chainActive.Tip()->GetBlockHash().GetHex());
  1549. boost::thread t(runCommand, strCmd); // thread runs free
  1550. }
  1551. return true;
  1552. }
  1553. bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos& pos)
  1554. {
  1555. // Check for duplicate
  1556. uint256 hash = block.GetHash();
  1557. if (mapBlockIndex.count(hash))
  1558. return state.Invalid(error("AddToBlockIndex() : %s already exists", hash.ToString().c_str()));
  1559. // Construct new block index object
  1560. CBlockIndex* pindexNew = new CBlockIndex(block);
  1561. assert(pindexNew);
  1562. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  1563. pindexNew->phashBlock = &((*mi).first);
  1564. map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
  1565. if (miPrev != mapBlockIndex.end())
  1566. {
  1567. pindexNew->pprev = (*miPrev).second;
  1568. pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
  1569. }
  1570. pindexNew->nTx = block.vtx.size();
  1571. pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + pindexNew->GetBlockWork().getuint256();
  1572. pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
  1573. pindexNew->nFile = pos.nFile;
  1574. pindexNew->nDataPos = pos.nPos;
  1575. pindexNew->nUndoPos = 0;
  1576. pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
  1577. setBlockIndexValid.insert(pindexNew);
  1578. if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew)))
  1579. return state.Abort(_("Failed to write block index"));
  1580. // New best?
  1581. if (!ConnectBestBlock(state))
  1582. return false;
  1583. if (pindexNew == chainActive.Tip())
  1584. {
  1585. // Clear fork warning if its no longer applicable
  1586. CheckForkWarningConditions();
  1587. // Notify UI to display prev block's coinbase if it was ours
  1588. static uint256 hashPrevBestCoinBase;
  1589. g_signals.UpdatedTransaction(hashPrevBestCoinBase);
  1590. hashPrevBestCoinBase = block.GetTxHash(0);
  1591. } else
  1592. CheckForkWarningConditionsOnNewFork(pindexNew);
  1593. if (!pblocktree->Flush())
  1594. return state.Abort(_("Failed to sync block index"));
  1595. uiInterface.NotifyBlocksChanged();
  1596. return true;
  1597. }
  1598. bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
  1599. {
  1600. bool fUpdatedLast = false;
  1601. LOCK(cs_LastBlockFile);
  1602. if (fKnown) {
  1603. if (nLastBlockFile != pos.nFile) {
  1604. nLastBlockFile = pos.nFile;
  1605. infoLastBlockFile.SetNull();
  1606. pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile);
  1607. fUpdatedLast = true;
  1608. }
  1609. } else {
  1610. while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
  1611. LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
  1612. FlushBlockFile(true);
  1613. nLastBlockFile++;
  1614. infoLastBlockFile.SetNull();
  1615. pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
  1616. fUpdatedLast = true;
  1617. }
  1618. pos.nFile = nLastBlockFile;
  1619. pos.nPos = infoLastBlockFile.nSize;
  1620. }
  1621. infoLastBlockFile.nSize += nAddSize;
  1622. infoLastBlockFile.AddBlock(nHeight, nTime);
  1623. if (!fKnown) {
  1624. unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
  1625. unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
  1626. if (nNewChunks > nOldChunks) {
  1627. if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
  1628. FILE *file = OpenBlockFile(pos);
  1629. if (file) {
  1630. LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
  1631. AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
  1632. fclose(file);
  1633. }
  1634. }
  1635. else
  1636. return state.Error();
  1637. }
  1638. }
  1639. if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
  1640. return state.Abort(_("Failed to write file info"));
  1641. if (fUpdatedLast)
  1642. pblocktree->WriteLastBlockFile(nLastBlockFile);
  1643. return true;
  1644. }
  1645. bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
  1646. {
  1647. pos.nFile = nFile;
  1648. LOCK(cs_LastBlockFile);
  1649. unsigned int nNewSize;
  1650. if (nFile == nLastBlockFile) {
  1651. pos.nPos = infoLastBlockFile.nUndoSize;
  1652. nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
  1653. if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
  1654. return state.Abort(_("Failed to write block info"));
  1655. } else {
  1656. CBlockFileInfo info;
  1657. if (!pblocktree->ReadBlockFileInfo(nFile, info))
  1658. return state.Abort(_("Failed to read block info"));
  1659. pos.nPos = info.nUndoSize;
  1660. nNewSize = (info.nUndoSize += nAddSize);
  1661. if (!pblocktree->WriteBlockFileInfo(nFile, info))
  1662. return state.Abort(_("Failed to write block info"));
  1663. }
  1664. unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
  1665. unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
  1666. if (nNewChunks > nOldChunks) {
  1667. if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
  1668. FILE *file = OpenUndoFile(pos);
  1669. if (file) {
  1670. LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
  1671. AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
  1672. fclose(file);
  1673. }
  1674. }
  1675. else
  1676. return state.Error();
  1677. }
  1678. return true;
  1679. }
  1680. bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot)
  1681. {
  1682. // These are checks that are independent of context
  1683. // that can be verified before saving an orphan block.
  1684. // Size limits
  1685. if (block.vtx.empty() || block.vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
  1686. return state.DoS(100, error("CheckBlock() : size limits failed"),
  1687. REJECT_INVALID, "block size too large");
  1688. // Check proof of work matches claimed amount
  1689. if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits))
  1690. return state.DoS(50, error("CheckBlock() : proof of work failed"),
  1691. REJECT_INVALID, "invalid pow");
  1692. // Check timestamp
  1693. if (block.GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
  1694. return state.Invalid(error("CheckBlock() : block timestamp too far in the future"),
  1695. REJECT_INVALID, "time in future");
  1696. // First transaction must be coinbase, the rest must not be
  1697. if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
  1698. return state.DoS(100, error("CheckBlock() : first tx is not coinbase"),
  1699. REJECT_INVALID, "no coinbase");
  1700. for (unsigned int i = 1; i < block.vtx.size(); i++)
  1701. if (block.vtx[i].IsCoinBase())
  1702. return state.DoS(100, error("CheckBlock() : more than one coinbase"),
  1703. REJECT_INVALID, "duplicate coinbase");
  1704. // Check transactions
  1705. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  1706. if (!CheckTransaction(tx, state))
  1707. return error("CheckBlock() : CheckTransaction failed");
  1708. // Build the merkle tree already. We need it anyway later, and it makes the
  1709. // block cache the transaction hashes, which means they don't need to be
  1710. // recalculated many times during this block's validation.
  1711. block.BuildMerkleTree();
  1712. // Check for duplicate txids. This is caught by ConnectInputs(),
  1713. // but catching it earlier avoids a potential DoS attack:
  1714. set<uint256> uniqueTx;
  1715. for (unsigned int i = 0; i < block.vtx.size(); i++) {
  1716. uniqueTx.insert(block.GetTxHash(i));
  1717. }
  1718. if (uniqueTx.size() != block.vtx.size())
  1719. return state.DoS(100, error("CheckBlock() : duplicate transaction"),
  1720. REJECT_INVALID, "duplicate transaction", true);
  1721. unsigned int nSigOps = 0;
  1722. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  1723. {
  1724. nSigOps += GetLegacySigOpCount(tx);
  1725. }
  1726. if (nSigOps > MAX_BLOCK_SIGOPS)
  1727. return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"),
  1728. REJECT_INVALID, "sig op count", true);
  1729. // Check merkle root
  1730. if (fCheckMerkleRoot && block.hashMerkleRoot != block.vMerkleTree.back())
  1731. return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"),
  1732. REJECT_INVALID, "bad merkle root", true);
  1733. return true;
  1734. }
  1735. bool AcceptBlock(CBlock& block, CValidationState& state, CDiskBlockPos* dbp)
  1736. {
  1737. // Check for duplicate
  1738. uint256 hash = block.GetHash();
  1739. if (mapBlockIndex.count(hash))
  1740. return state.Invalid(error("AcceptBlock() : block already in mapBlockIndex"));
  1741. // Get prev block index
  1742. CBlockIndex* pindexPrev = NULL;
  1743. int nHeight = 0;
  1744. if (hash != Params().HashGenesisBlock()) {
  1745. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
  1746. if (mi == mapBlockIndex.end())
  1747. return state.DoS(10, error("AcceptBlock() : prev block not found"));
  1748. pindexPrev = (*mi).second;
  1749. nHeight = pindexPrev->nHeight+1;
  1750. // Check proof of work
  1751. if (block.nBits != GetNextWorkRequired(pindexPrev, &block))
  1752. return state.DoS(100, error("AcceptBlock() : incorrect proof of work"),
  1753. REJECT_INVALID, "bad pow");
  1754. // Check timestamp against prev
  1755. if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast())
  1756. return state.Invalid(error("AcceptBlock() : block's timestamp is too early"),
  1757. REJECT_INVALID, "timestamp too early");
  1758. // Check that all transactions are finalized
  1759. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  1760. if (!IsFinalTx(tx, nHeight, block.GetBlockTime()))
  1761. return state.DoS(10, error("AcceptBlock() : contains a non-final transaction"),
  1762. REJECT_INVALID, "non-final tx");
  1763. // Check that the block chain matches the known block chain up to a checkpoint
  1764. if (!Checkpoints::CheckBlock(nHeight, hash))
  1765. return state.DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight),
  1766. REJECT_CHECKPOINT, "checkpoint mismatch");
  1767. // Reject block.nVersion=1 blocks when 95% (75% on testnet) of the network has upgraded:
  1768. if (block.nVersion < 2)
  1769. {
  1770. if ((!TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 950, 1000)) ||
  1771. (TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 75, 100)))
  1772. {
  1773. return state.Invalid(error("AcceptBlock() : rejected nVersion=1 block"),
  1774. REJECT_OBSOLETE, "version 1 blocks obsolete");
  1775. }
  1776. }
  1777. // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
  1778. if (block.nVersion >= 2)
  1779. {
  1780. // if 750 of the last 1,000 blocks are version 2 or greater (51/100 if testnet):
  1781. if ((!TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 750, 1000)) ||
  1782. (TestNet() && CBlockIndex::IsSuperMajority(2, pindexPrev, 51, 100)))
  1783. {
  1784. CScript expect = CScript() << nHeight;
  1785. if (block.vtx[0].vin[0].scriptSig.size() < expect.size() ||
  1786. !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin()))
  1787. return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase"),
  1788. REJECT_INVALID, "height incorrect in coinbase");
  1789. }
  1790. }
  1791. }
  1792. // Write block to history file
  1793. try {
  1794. unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
  1795. CDiskBlockPos blockPos;
  1796. if (dbp != NULL)
  1797. blockPos = *dbp;
  1798. if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, block.nTime, dbp != NULL))
  1799. return error("AcceptBlock() : FindBlockPos failed");
  1800. if (dbp == NULL)
  1801. if (!WriteBlockToDisk(block, blockPos))
  1802. return state.Abort(_("Failed to write block"));
  1803. if (!AddToBlockIndex(block, state, blockPos))
  1804. return error("AcceptBlock() : AddToBlockIndex failed");
  1805. } catch(std::runtime_error &e) {
  1806. return state.Abort(_("System error: ") + e.what());
  1807. }
  1808. // Relay inventory, but don't relay old inventory during initial block download
  1809. int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
  1810. if (chainActive.Tip()->GetBlockHash() == hash)
  1811. {
  1812. LOCK(cs_vNodes);
  1813. BOOST_FOREACH(CNode* pnode, vNodes)
  1814. if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
  1815. pnode->PushInventory(CInv(MSG_BLOCK, hash));
  1816. }
  1817. return true;
  1818. }
  1819. bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
  1820. {
  1821. unsigned int nFound = 0;
  1822. for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
  1823. {
  1824. if (pstart->nVersion >= minVersion)
  1825. ++nFound;
  1826. pstart = pstart->pprev;
  1827. }
  1828. return (nFound >= nRequired);
  1829. }
  1830. int64_t CBlockIndex::GetMedianTime() const
  1831. {
  1832. const CBlockIndex* pindex = this;
  1833. for (int i = 0; i < nMedianTimeSpan/2; i++)
  1834. {
  1835. if (!chainActive.Next(pindex))
  1836. return GetBlockTime();
  1837. pindex = chainActive.Next(pindex);
  1838. }
  1839. return pindex->GetMedianTimePast();
  1840. }
  1841. void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd)
  1842. {
  1843. // Filter out duplicate requests
  1844. if (pindexBegin == pnode->pindexLastGetBlocksBegin && hashEnd == pnode->hashLastGetBlocksEnd)
  1845. return;
  1846. pnode->pindexLastGetBlocksBegin = pindexBegin;
  1847. pnode->hashLastGetBlocksEnd = hashEnd;
  1848. pnode->PushMessage("getblocks", chainActive.GetLocator(pindexBegin), hashEnd);
  1849. }
  1850. bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
  1851. {
  1852. AssertLockHeld("cs_main");
  1853. // Check for duplicate
  1854. uint256 hash = pblock->GetHash();
  1855. if (mapBlockIndex.count(hash))
  1856. return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().c_str()));
  1857. if (mapOrphanBlocks.count(hash))
  1858. return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", hash.ToString().c_str()));
  1859. // Preliminary checks
  1860. if (!CheckBlock(*pblock, state))
  1861. return error("ProcessBlock() : CheckBlock FAILED");
  1862. CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
  1863. if (pcheckpoint && pblock->hashPrevBlock != (chainActive.Tip() ? chainActive.Tip()->GetBlockHash() : uint256(0)))
  1864. {
  1865. // Extra checks to prevent "fill up memory by spamming with bogus blocks"
  1866. int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
  1867. if (deltaTime < 0)
  1868. {
  1869. return state.DoS(100, error("ProcessBlock() : block with timestamp before last checkpoint"),
  1870. REJECT_CHECKPOINT, "timestamp before checkpoint");
  1871. }
  1872. CBigNum bnNewBlock;
  1873. bnNewBlock.SetCompact(pblock->nBits);
  1874. CBigNum bnRequired;
  1875. bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
  1876. if (bnNewBlock > bnRequired)
  1877. {
  1878. return state.DoS(100, error("ProcessBlock() : block with too little proof-of-work"),
  1879. REJECT_INVALID, "invalid pow");
  1880. }
  1881. }
  1882. // If we don't already have its previous block, shunt it off to holding area until we get it
  1883. if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
  1884. {
  1885. LogPrintf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().c_str());
  1886. // Accept orphans as long as there is a node to request its parents from
  1887. if (pfrom) {
  1888. CBlock* pblock2 = new CBlock(*pblock);
  1889. mapOrphanBlocks.insert(make_pair(hash, pblock2));
  1890. mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
  1891. // Ask this guy to fill in what we're missing
  1892. PushGetBlocks(pfrom, chainActive.Tip(), GetOrphanRoot(pblock2));
  1893. }
  1894. return true;
  1895. }
  1896. // Store to disk
  1897. if (!AcceptBlock(*pblock, state, dbp))
  1898. return error("ProcessBlock() : AcceptBlock FAILED");
  1899. // Recursively process any orphan blocks that depended on this one
  1900. vector<uint256> vWorkQueue;
  1901. vWorkQueue.push_back(hash);
  1902. for (unsigned int i = 0; i < vWorkQueue.size(); i++)
  1903. {
  1904. uint256 hashPrev = vWorkQueue[i];
  1905. for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
  1906. mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
  1907. ++mi)
  1908. {
  1909. CBlock* pblockOrphan = (*mi).second;
  1910. // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan resolution (that is, feeding people an invalid block based on LegitBlockX in order to get anyone relaying LegitBlockX banned)
  1911. CValidationState stateDummy;
  1912. if (AcceptBlock(*pblockOrphan, stateDummy))
  1913. vWorkQueue.push_back(pblockOrphan->GetHash());
  1914. mapOrphanBlocks.erase(pblockOrphan->GetHash());
  1915. delete pblockOrphan;
  1916. }
  1917. mapOrphanBlocksByPrev.erase(hashPrev);
  1918. }
  1919. LogPrintf("ProcessBlock: ACCEPTED\n");
  1920. return true;
  1921. }
  1922. CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
  1923. {
  1924. header = block.GetBlockHeader();
  1925. vector<bool> vMatch;
  1926. vector<uint256> vHashes;
  1927. vMatch.reserve(block.vtx.size());
  1928. vHashes.reserve(block.vtx.size());
  1929. for (unsigned int i = 0; i < block.vtx.size(); i++)
  1930. {
  1931. uint256 hash = block.vtx[i].GetHash();
  1932. if (filter.IsRelevantAndUpdate(block.vtx[i], hash))
  1933. {
  1934. vMatch.push_back(true);
  1935. vMatchedTxn.push_back(make_pair(i, hash));
  1936. }
  1937. else
  1938. vMatch.push_back(false);
  1939. vHashes.push_back(hash);
  1940. }
  1941. txn = CPartialMerkleTree(vHashes, vMatch);
  1942. }
  1943. uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
  1944. if (height == 0) {
  1945. // hash at height 0 is the txids themself
  1946. return vTxid[pos];
  1947. } else {
  1948. // calculate left hash
  1949. uint256 left = CalcHash(height-1, pos*2, vTxid), right;
  1950. // calculate right hash if not beyong the end of the array - copy left hash otherwise1
  1951. if (pos*2+1 < CalcTreeWidth(height-1))
  1952. right = CalcHash(height-1, pos*2+1, vTxid);
  1953. else
  1954. right = left;
  1955. // combine subhashes
  1956. return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
  1957. }
  1958. }
  1959. void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
  1960. // determine whether this node is the parent of at least one matched txid
  1961. bool fParentOfMatch = false;
  1962. for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
  1963. fParentOfMatch |= vMatch[p];
  1964. // store as flag bit
  1965. vBits.push_back(fParentOfMatch);
  1966. if (height==0 || !fParentOfMatch) {
  1967. // if at height 0, or nothing interesting below, store hash and stop
  1968. vHash.push_back(CalcHash(height, pos, vTxid));
  1969. } else {
  1970. // otherwise, don't store any hash, but descend into the subtrees
  1971. TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
  1972. if (pos*2+1 < CalcTreeWidth(height-1))
  1973. TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
  1974. }
  1975. }
  1976. uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
  1977. if (nBitsUsed >= vBits.size()) {
  1978. // overflowed the bits array - failure
  1979. fBad = true;
  1980. return 0;
  1981. }
  1982. bool fParentOfMatch = vBits[nBitsUsed++];
  1983. if (height==0 || !fParentOfMatch) {
  1984. // if at height 0, or nothing interesting below, use stored hash and do not descend
  1985. if (nHashUsed >= vHash.size()) {
  1986. // overflowed the hash array - failure
  1987. fBad = true;
  1988. return 0;
  1989. }
  1990. const uint256 &hash = vHash[nHashUsed++];
  1991. if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
  1992. vMatch.push_back(hash);
  1993. return hash;
  1994. } else {
  1995. // otherwise, descend into the subtrees to extract matched txids and hashes
  1996. uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
  1997. if (pos*2+1 < CalcTreeWidth(height-1))
  1998. right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
  1999. else
  2000. right = left;
  2001. // and combine them before returning
  2002. return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
  2003. }
  2004. }
  2005. CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
  2006. // reset state
  2007. vBits.clear();
  2008. vHash.clear();
  2009. // calculate height of tree
  2010. int nHeight = 0;
  2011. while (CalcTreeWidth(nHeight) > 1)
  2012. nHeight++;
  2013. // traverse the partial tree
  2014. TraverseAndBuild(nHeight, 0, vTxid, vMatch);
  2015. }
  2016. CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
  2017. uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
  2018. vMatch.clear();
  2019. // An empty set will not work
  2020. if (nTransactions == 0)
  2021. return 0;
  2022. // check for excessively high numbers of transactions
  2023. if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
  2024. return 0;
  2025. // there can never be more hashes provided than one for every txid
  2026. if (vHash.size() > nTransactions)
  2027. return 0;
  2028. // there must be at least one bit per node in the partial tree, and at least one node per hash
  2029. if (vBits.size() < vHash.size())
  2030. return 0;
  2031. // calculate height of tree
  2032. int nHeight = 0;
  2033. while (CalcTreeWidth(nHeight) > 1)
  2034. nHeight++;
  2035. // traverse the partial tree
  2036. unsigned int nBitsUsed = 0, nHashUsed = 0;
  2037. uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
  2038. // verify that no problems occured during the tree traversal
  2039. if (fBad)
  2040. return 0;
  2041. // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
  2042. if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
  2043. return 0;
  2044. // verify that all hashes were consumed
  2045. if (nHashUsed != vHash.size())
  2046. return 0;
  2047. return hashMerkleRoot;
  2048. }
  2049. bool AbortNode(const std::string &strMessage) {
  2050. strMiscWarning = strMessage;
  2051. LogPrintf("*** %s\n", strMessage.c_str());
  2052. uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR);
  2053. StartShutdown();
  2054. return false;
  2055. }
  2056. bool CheckDiskSpace(uint64_t nAdditionalBytes)
  2057. {
  2058. uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
  2059. // Check for nMinDiskSpace bytes (currently 50MB)
  2060. if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
  2061. return AbortNode(_("Error: Disk space is low!"));
  2062. return true;
  2063. }
  2064. FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
  2065. {
  2066. if (pos.IsNull())
  2067. return NULL;
  2068. boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
  2069. boost::filesystem::create_directories(path.parent_path());
  2070. FILE* file = fopen(path.string().c_str(), "rb+");
  2071. if (!file && !fReadOnly)
  2072. file = fopen(path.string().c_str(), "wb+");
  2073. if (!file) {
  2074. LogPrintf("Unable to open file %s\n", path.string().c_str());
  2075. return NULL;
  2076. }
  2077. if (pos.nPos) {
  2078. if (fseek(file, pos.nPos, SEEK_SET)) {
  2079. LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
  2080. fclose(file);
  2081. return NULL;
  2082. }
  2083. }
  2084. return file;
  2085. }
  2086. FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
  2087. return OpenDiskFile(pos, "blk", fReadOnly);
  2088. }
  2089. FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
  2090. return OpenDiskFile(pos, "rev", fReadOnly);
  2091. }
  2092. CBlockIndex * InsertBlockIndex(uint256 hash)
  2093. {
  2094. if (hash == 0)
  2095. return NULL;
  2096. // Return existing
  2097. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  2098. if (mi != mapBlockIndex.end())
  2099. return (*mi).second;
  2100. // Create new
  2101. CBlockIndex* pindexNew = new CBlockIndex();
  2102. if (!pindexNew)
  2103. throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
  2104. mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  2105. pindexNew->phashBlock = &((*mi).first);
  2106. return pindexNew;
  2107. }
  2108. bool static LoadBlockIndexDB()
  2109. {
  2110. if (!pblocktree->LoadBlockIndexGuts())
  2111. return false;
  2112. boost::this_thread::interruption_point();
  2113. // Calculate nChainWork
  2114. vector<pair<int, CBlockIndex*> > vSortedByHeight;
  2115. vSortedByHeight.reserve(mapBlockIndex.size());
  2116. BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
  2117. {
  2118. CBlockIndex* pindex = item.second;
  2119. vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
  2120. }
  2121. sort(vSortedByHeight.begin(), vSortedByHeight.end());
  2122. BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
  2123. {
  2124. CBlockIndex* pindex = item.second;
  2125. pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + pindex->GetBlockWork().getuint256();
  2126. pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
  2127. if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
  2128. setBlockIndexValid.insert(pindex);
  2129. if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
  2130. pindexBestInvalid = pindex;
  2131. }
  2132. // Load block file info
  2133. pblocktree->ReadLastBlockFile(nLastBlockFile);
  2134. LogPrintf("LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
  2135. if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
  2136. LogPrintf("LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString().c_str());
  2137. // Check whether we need to continue reindexing
  2138. bool fReindexing = false;
  2139. pblocktree->ReadReindexing(fReindexing);
  2140. fReindex |= fReindexing;
  2141. // Check whether we have a transaction index
  2142. pblocktree->ReadFlag("txindex", fTxIndex);
  2143. LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
  2144. // Load pointer to end of best chain
  2145. std::map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
  2146. if (it == mapBlockIndex.end())
  2147. return true;
  2148. chainActive.SetTip(it->second);
  2149. LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s\n",
  2150. chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(),
  2151. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str());
  2152. return true;
  2153. }
  2154. bool VerifyDB(int nCheckLevel, int nCheckDepth)
  2155. {
  2156. if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
  2157. return true;
  2158. // Verify blocks in the best chain
  2159. if (nCheckDepth <= 0)
  2160. nCheckDepth = 1000000000; // suffices until the year 19000
  2161. if (nCheckDepth > chainActive.Height())
  2162. nCheckDepth = chainActive.Height();
  2163. nCheckLevel = std::max(0, std::min(4, nCheckLevel));
  2164. LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
  2165. CCoinsViewCache coins(*pcoinsTip, true);
  2166. CBlockIndex* pindexState = chainActive.Tip();
  2167. CBlockIndex* pindexFailure = NULL;
  2168. int nGoodTransactions = 0;
  2169. CValidationState state;
  2170. for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev)
  2171. {
  2172. boost::this_thread::interruption_point();
  2173. if (pindex->nHeight < chainActive.Height()-nCheckDepth)
  2174. break;
  2175. CBlock block;
  2176. // check level 0: read from disk
  2177. if (!ReadBlockFromDisk(block, pindex))
  2178. return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2179. // check level 1: verify block validity
  2180. if (nCheckLevel >= 1 && !CheckBlock(block, state))
  2181. return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2182. // check level 2: verify undo validity
  2183. if (nCheckLevel >= 2 && pindex) {
  2184. CBlockUndo undo;
  2185. CDiskBlockPos pos = pindex->GetUndoPos();
  2186. if (!pos.IsNull()) {
  2187. if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
  2188. return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2189. }
  2190. }
  2191. // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
  2192. if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
  2193. bool fClean = true;
  2194. if (!DisconnectBlock(block, state, pindex, coins, &fClean))
  2195. return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2196. pindexState = pindex->pprev;
  2197. if (!fClean) {
  2198. nGoodTransactions = 0;
  2199. pindexFailure = pindex;
  2200. } else
  2201. nGoodTransactions += block.vtx.size();
  2202. }
  2203. }
  2204. if (pindexFailure)
  2205. return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
  2206. // check level 4: try reconnecting blocks
  2207. if (nCheckLevel >= 4) {
  2208. CBlockIndex *pindex = pindexState;
  2209. while (pindex != chainActive.Tip()) {
  2210. boost::this_thread::interruption_point();
  2211. pindex = chainActive.Next(pindex);
  2212. CBlock block;
  2213. if (!ReadBlockFromDisk(block, pindex))
  2214. return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2215. if (!ConnectBlock(block, state, pindex, coins))
  2216. return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2217. }
  2218. }
  2219. LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
  2220. return true;
  2221. }
  2222. void UnloadBlockIndex()
  2223. {
  2224. mapBlockIndex.clear();
  2225. setBlockIndexValid.clear();
  2226. chainActive.SetTip(NULL);
  2227. pindexBestInvalid = NULL;
  2228. }
  2229. bool LoadBlockIndex()
  2230. {
  2231. // Load block index from databases
  2232. if (!fReindex && !LoadBlockIndexDB())
  2233. return false;
  2234. return true;
  2235. }
  2236. bool InitBlockIndex() {
  2237. // Check whether we're already initialized
  2238. if (chainActive.Genesis() != NULL)
  2239. return true;
  2240. // Use the provided setting for -txindex in the new database
  2241. fTxIndex = GetBoolArg("-txindex", false);
  2242. pblocktree->WriteFlag("txindex", fTxIndex);
  2243. LogPrintf("Initializing databases...\n");
  2244. // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
  2245. if (!fReindex) {
  2246. try {
  2247. CBlock &block = const_cast<CBlock&>(Params().GenesisBlock());
  2248. // Start new block file
  2249. unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
  2250. CDiskBlockPos blockPos;
  2251. CValidationState state;
  2252. if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.nTime))
  2253. return error("LoadBlockIndex() : FindBlockPos failed");
  2254. if (!WriteBlockToDisk(block, blockPos))
  2255. return error("LoadBlockIndex() : writing genesis block to disk failed");
  2256. if (!AddToBlockIndex(block, state, blockPos))
  2257. return error("LoadBlockIndex() : genesis block not accepted");
  2258. } catch(std::runtime_error &e) {
  2259. return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
  2260. }
  2261. }
  2262. return true;
  2263. }
  2264. void PrintBlockTree()
  2265. {
  2266. // pre-compute tree structure
  2267. map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
  2268. for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
  2269. {
  2270. CBlockIndex* pindex = (*mi).second;
  2271. mapNext[pindex->pprev].push_back(pindex);
  2272. // test
  2273. //while (rand() % 3 == 0)
  2274. // mapNext[pindex->pprev].push_back(pindex);
  2275. }
  2276. vector<pair<int, CBlockIndex*> > vStack;
  2277. vStack.push_back(make_pair(0, chainActive.Genesis()));
  2278. int nPrevCol = 0;
  2279. while (!vStack.empty())
  2280. {
  2281. int nCol = vStack.back().first;
  2282. CBlockIndex* pindex = vStack.back().second;
  2283. vStack.pop_back();
  2284. // print split or gap
  2285. if (nCol > nPrevCol)
  2286. {
  2287. for (int i = 0; i < nCol-1; i++)
  2288. LogPrintf("| ");
  2289. LogPrintf("|\\\n");
  2290. }
  2291. else if (nCol < nPrevCol)
  2292. {
  2293. for (int i = 0; i < nCol; i++)
  2294. LogPrintf("| ");
  2295. LogPrintf("|\n");
  2296. }
  2297. nPrevCol = nCol;
  2298. // print columns
  2299. for (int i = 0; i < nCol; i++)
  2300. LogPrintf("| ");
  2301. // print item
  2302. CBlock block;
  2303. ReadBlockFromDisk(block, pindex);
  2304. LogPrintf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
  2305. pindex->nHeight,
  2306. pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
  2307. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
  2308. block.vtx.size());
  2309. // put the main time-chain first
  2310. vector<CBlockIndex*>& vNext = mapNext[pindex];
  2311. for (unsigned int i = 0; i < vNext.size(); i++)
  2312. {
  2313. if (chainActive.Next(vNext[i]))
  2314. {
  2315. swap(vNext[0], vNext[i]);
  2316. break;
  2317. }
  2318. }
  2319. // iterate children
  2320. for (unsigned int i = 0; i < vNext.size(); i++)
  2321. vStack.push_back(make_pair(nCol+i, vNext[i]));
  2322. }
  2323. }
  2324. bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
  2325. {
  2326. int64_t nStart = GetTimeMillis();
  2327. int nLoaded = 0;
  2328. try {
  2329. CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
  2330. uint64_t nStartByte = 0;
  2331. if (dbp) {
  2332. // (try to) skip already indexed part
  2333. CBlockFileInfo info;
  2334. if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) {
  2335. nStartByte = info.nSize;
  2336. blkdat.Seek(info.nSize);
  2337. }
  2338. }
  2339. uint64_t nRewind = blkdat.GetPos();
  2340. while (blkdat.good() && !blkdat.eof()) {
  2341. boost::this_thread::interruption_point();
  2342. blkdat.SetPos(nRewind);
  2343. nRewind++; // start one byte further next time, in case of failure
  2344. blkdat.SetLimit(); // remove former limit
  2345. unsigned int nSize = 0;
  2346. try {
  2347. // locate a header
  2348. unsigned char buf[4];
  2349. blkdat.FindByte(Params().MessageStart()[0]);
  2350. nRewind = blkdat.GetPos()+1;
  2351. blkdat >> FLATDATA(buf);
  2352. if (memcmp(buf, Params().MessageStart(), 4))
  2353. continue;
  2354. // read size
  2355. blkdat >> nSize;
  2356. if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
  2357. continue;
  2358. } catch (std::exception &e) {
  2359. // no valid block header found; don't complain
  2360. break;
  2361. }
  2362. try {
  2363. // read block
  2364. uint64_t nBlockPos = blkdat.GetPos();
  2365. blkdat.SetLimit(nBlockPos + nSize);
  2366. CBlock block;
  2367. blkdat >> block;
  2368. nRewind = blkdat.GetPos();
  2369. // process block
  2370. if (nBlockPos >= nStartByte) {
  2371. LOCK(cs_main);
  2372. if (dbp)
  2373. dbp->nPos = nBlockPos;
  2374. CValidationState state;
  2375. if (ProcessBlock(state, NULL, &block, dbp))
  2376. nLoaded++;
  2377. if (state.IsError())
  2378. break;
  2379. }
  2380. } catch (std::exception &e) {
  2381. LogPrintf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__);
  2382. }
  2383. }
  2384. fclose(fileIn);
  2385. } catch(std::runtime_error &e) {
  2386. AbortNode(_("Error: system error: ") + e.what());
  2387. }
  2388. if (nLoaded > 0)
  2389. LogPrintf("Loaded %i blocks from external file in %"PRId64"ms\n", nLoaded, GetTimeMillis() - nStart);
  2390. return nLoaded > 0;
  2391. }
  2392. //////////////////////////////////////////////////////////////////////////////
  2393. //
  2394. // CAlert
  2395. //
  2396. string GetWarnings(string strFor)
  2397. {
  2398. int nPriority = 0;
  2399. string strStatusBar;
  2400. string strRPC;
  2401. if (GetBoolArg("-testsafemode", false))
  2402. strRPC = "test";
  2403. if (!CLIENT_VERSION_IS_RELEASE)
  2404. strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
  2405. // Misc warnings like out of disk space and clock is wrong
  2406. if (strMiscWarning != "")
  2407. {
  2408. nPriority = 1000;
  2409. strStatusBar = strMiscWarning;
  2410. }
  2411. if (fLargeWorkForkFound)
  2412. {
  2413. nPriority = 2000;
  2414. strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
  2415. }
  2416. else if (fLargeWorkInvalidChainFound)
  2417. {
  2418. nPriority = 2000;
  2419. strStatusBar = strRPC = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
  2420. }
  2421. // Alerts
  2422. {
  2423. LOCK(cs_mapAlerts);
  2424. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  2425. {
  2426. const CAlert& alert = item.second;
  2427. if (alert.AppliesToMe() && alert.nPriority > nPriority)
  2428. {
  2429. nPriority = alert.nPriority;
  2430. strStatusBar = alert.strStatusBar;
  2431. }
  2432. }
  2433. }
  2434. if (strFor == "statusbar")
  2435. return strStatusBar;
  2436. else if (strFor == "rpc")
  2437. return strRPC;
  2438. assert(!"GetWarnings() : invalid parameter");
  2439. return "error";
  2440. }
  2441. //////////////////////////////////////////////////////////////////////////////
  2442. //
  2443. // Messages
  2444. //
  2445. bool static AlreadyHave(const CInv& inv)
  2446. {
  2447. switch (inv.type)
  2448. {
  2449. case MSG_TX:
  2450. {
  2451. bool txInMap = false;
  2452. txInMap = mempool.exists(inv.hash);
  2453. return txInMap || mapOrphanTransactions.count(inv.hash) ||
  2454. pcoinsTip->HaveCoins(inv.hash);
  2455. }
  2456. case MSG_BLOCK:
  2457. return mapBlockIndex.count(inv.hash) ||
  2458. mapOrphanBlocks.count(inv.hash);
  2459. }
  2460. // Don't know what it is, just say we already got one
  2461. return true;
  2462. }
  2463. void static ProcessGetData(CNode* pfrom)
  2464. {
  2465. std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
  2466. vector<CInv> vNotFound;
  2467. LOCK(cs_main);
  2468. while (it != pfrom->vRecvGetData.end()) {
  2469. // Don't bother if send buffer is too full to respond anyway
  2470. if (pfrom->nSendSize >= SendBufferSize())
  2471. break;
  2472. const CInv &inv = *it;
  2473. {
  2474. boost::this_thread::interruption_point();
  2475. it++;
  2476. if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
  2477. {
  2478. // Send block from disk
  2479. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
  2480. if (mi != mapBlockIndex.end())
  2481. {
  2482. CBlock block;
  2483. ReadBlockFromDisk(block, (*mi).second);
  2484. if (inv.type == MSG_BLOCK)
  2485. pfrom->PushMessage("block", block);
  2486. else // MSG_FILTERED_BLOCK)
  2487. {
  2488. LOCK(pfrom->cs_filter);
  2489. if (pfrom->pfilter)
  2490. {
  2491. CMerkleBlock merkleBlock(block, *pfrom->pfilter);
  2492. pfrom->PushMessage("merkleblock", merkleBlock);
  2493. // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
  2494. // This avoids hurting performance by pointlessly requiring a round-trip
  2495. // Note that there is currently no way for a node to request any single transactions we didnt send here -
  2496. // they must either disconnect and retry or request the full block.
  2497. // Thus, the protocol spec specified allows for us to provide duplicate txn here,
  2498. // however we MUST always provide at least what the remote peer needs
  2499. typedef std::pair<unsigned int, uint256> PairType;
  2500. BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
  2501. if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
  2502. pfrom->PushMessage("tx", block.vtx[pair.first]);
  2503. }
  2504. // else
  2505. // no response
  2506. }
  2507. // Trigger them to send a getblocks request for the next batch of inventory
  2508. if (inv.hash == pfrom->hashContinue)
  2509. {
  2510. // Bypass PushInventory, this must send even if redundant,
  2511. // and we want it right after the last block so they don't
  2512. // wait for other stuff first.
  2513. vector<CInv> vInv;
  2514. vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
  2515. pfrom->PushMessage("inv", vInv);
  2516. pfrom->hashContinue = 0;
  2517. }
  2518. }
  2519. }
  2520. else if (inv.IsKnownType())
  2521. {
  2522. // Send stream from relay memory
  2523. bool pushed = false;
  2524. {
  2525. LOCK(cs_mapRelay);
  2526. map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
  2527. if (mi != mapRelay.end()) {
  2528. pfrom->PushMessage(inv.GetCommand(), (*mi).second);
  2529. pushed = true;
  2530. }
  2531. }
  2532. if (!pushed && inv.type == MSG_TX) {
  2533. CTransaction tx;
  2534. if (mempool.lookup(inv.hash, tx)) {
  2535. CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
  2536. ss.reserve(1000);
  2537. ss << tx;
  2538. pfrom->PushMessage("tx", ss);
  2539. pushed = true;
  2540. }
  2541. }
  2542. if (!pushed) {
  2543. vNotFound.push_back(inv);
  2544. }
  2545. }
  2546. // Track requests for our stuff.
  2547. g_signals.Inventory(inv.hash);
  2548. if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
  2549. break;
  2550. }
  2551. }
  2552. pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
  2553. if (!vNotFound.empty()) {
  2554. // Let the peer know that we didn't find what it asked for, so it doesn't
  2555. // have to wait around forever. Currently only SPV clients actually care
  2556. // about this message: it's needed when they are recursively walking the
  2557. // dependencies of relevant unconfirmed transactions. SPV clients want to
  2558. // do that because they want to know about (and store and rebroadcast and
  2559. // risk analyze) the dependencies of transactions relevant to them, without
  2560. // having to download the entire memory pool.
  2561. pfrom->PushMessage("notfound", vNotFound);
  2562. }
  2563. }
  2564. bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
  2565. {
  2566. RandAddSeedPerfmon();
  2567. LogPrint("net", "received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
  2568. if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
  2569. {
  2570. LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
  2571. return true;
  2572. }
  2573. if (strCommand == "version")
  2574. {
  2575. // Each connection can only send one version message
  2576. if (pfrom->nVersion != 0)
  2577. {
  2578. pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
  2579. pfrom->Misbehaving(1);
  2580. return false;
  2581. }
  2582. int64_t nTime;
  2583. CAddress addrMe;
  2584. CAddress addrFrom;
  2585. uint64_t nNonce = 1;
  2586. vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
  2587. if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
  2588. {
  2589. // disconnect from peers older than this proto version
  2590. LogPrintf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
  2591. pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
  2592. strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
  2593. pfrom->fDisconnect = true;
  2594. return false;
  2595. }
  2596. if (pfrom->nVersion == 10300)
  2597. pfrom->nVersion = 300;
  2598. if (!vRecv.empty())
  2599. vRecv >> addrFrom >> nNonce;
  2600. if (!vRecv.empty()) {
  2601. vRecv >> pfrom->strSubVer;
  2602. pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
  2603. }
  2604. if (!vRecv.empty())
  2605. vRecv >> pfrom->nStartingHeight;
  2606. if (!vRecv.empty())
  2607. vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
  2608. else
  2609. pfrom->fRelayTxes = true;
  2610. if (pfrom->fInbound && addrMe.IsRoutable())
  2611. {
  2612. pfrom->addrLocal = addrMe;
  2613. SeenLocal(addrMe);
  2614. }
  2615. // Disconnect if we connected to ourself
  2616. if (nNonce == nLocalHostNonce && nNonce > 1)
  2617. {
  2618. LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
  2619. pfrom->fDisconnect = true;
  2620. return true;
  2621. }
  2622. // Be shy and don't send version until we hear
  2623. if (pfrom->fInbound)
  2624. pfrom->PushVersion();
  2625. pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
  2626. // Change version
  2627. pfrom->PushMessage("verack");
  2628. pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
  2629. if (!pfrom->fInbound)
  2630. {
  2631. // Advertise our address
  2632. if (!fNoListen && !IsInitialBlockDownload())
  2633. {
  2634. CAddress addr = GetLocalAddress(&pfrom->addr);
  2635. if (addr.IsRoutable())
  2636. pfrom->PushAddress(addr);
  2637. }
  2638. // Get recent addresses
  2639. if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
  2640. {
  2641. pfrom->PushMessage("getaddr");
  2642. pfrom->fGetAddr = true;
  2643. }
  2644. addrman.Good(pfrom->addr);
  2645. } else {
  2646. if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
  2647. {
  2648. addrman.Add(addrFrom, addrFrom);
  2649. addrman.Good(addrFrom);
  2650. }
  2651. }
  2652. // Relay alerts
  2653. {
  2654. LOCK(cs_mapAlerts);
  2655. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  2656. item.second.RelayTo(pfrom);
  2657. }
  2658. pfrom->fSuccessfullyConnected = true;
  2659. LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->cleanSubVer.c_str(), pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
  2660. AddTimeData(pfrom->addr, nTime);
  2661. LOCK(cs_main);
  2662. cPeerBlockCounts.input(pfrom->nStartingHeight);
  2663. }
  2664. else if (pfrom->nVersion == 0)
  2665. {
  2666. // Must have a version message before anything else
  2667. pfrom->Misbehaving(1);
  2668. return false;
  2669. }
  2670. else if (strCommand == "verack")
  2671. {
  2672. pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
  2673. }
  2674. else if (strCommand == "addr")
  2675. {
  2676. vector<CAddress> vAddr;
  2677. vRecv >> vAddr;
  2678. // Don't want addr from older versions unless seeding
  2679. if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
  2680. return true;
  2681. if (vAddr.size() > 1000)
  2682. {
  2683. pfrom->Misbehaving(20);
  2684. return error("message addr size() = %"PRIszu"", vAddr.size());
  2685. }
  2686. // Store the new addresses
  2687. vector<CAddress> vAddrOk;
  2688. int64_t nNow = GetAdjustedTime();
  2689. int64_t nSince = nNow - 10 * 60;
  2690. BOOST_FOREACH(CAddress& addr, vAddr)
  2691. {
  2692. boost::this_thread::interruption_point();
  2693. if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
  2694. addr.nTime = nNow - 5 * 24 * 60 * 60;
  2695. pfrom->AddAddressKnown(addr);
  2696. bool fReachable = IsReachable(addr);
  2697. if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
  2698. {
  2699. // Relay to a limited number of other nodes
  2700. {
  2701. LOCK(cs_vNodes);
  2702. // Use deterministic randomness to send to the same nodes for 24 hours
  2703. // at a time so the setAddrKnowns of the chosen nodes prevent repeats
  2704. static uint256 hashSalt;
  2705. if (hashSalt == 0)
  2706. hashSalt = GetRandHash();
  2707. uint64_t hashAddr = addr.GetHash();
  2708. uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
  2709. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  2710. multimap<uint256, CNode*> mapMix;
  2711. BOOST_FOREACH(CNode* pnode, vNodes)
  2712. {
  2713. if (pnode->nVersion < CADDR_TIME_VERSION)
  2714. continue;
  2715. unsigned int nPointer;
  2716. memcpy(&nPointer, &pnode, sizeof(nPointer));
  2717. uint256 hashKey = hashRand ^ nPointer;
  2718. hashKey = Hash(BEGIN(hashKey), END(hashKey));
  2719. mapMix.insert(make_pair(hashKey, pnode));
  2720. }
  2721. int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
  2722. for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
  2723. ((*mi).second)->PushAddress(addr);
  2724. }
  2725. }
  2726. // Do not store addresses outside our network
  2727. if (fReachable)
  2728. vAddrOk.push_back(addr);
  2729. }
  2730. addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
  2731. if (vAddr.size() < 1000)
  2732. pfrom->fGetAddr = false;
  2733. if (pfrom->fOneShot)
  2734. pfrom->fDisconnect = true;
  2735. }
  2736. else if (strCommand == "inv")
  2737. {
  2738. vector<CInv> vInv;
  2739. vRecv >> vInv;
  2740. if (vInv.size() > MAX_INV_SZ)
  2741. {
  2742. pfrom->Misbehaving(20);
  2743. return error("message inv size() = %"PRIszu"", vInv.size());
  2744. }
  2745. // find last block in inv vector
  2746. unsigned int nLastBlock = (unsigned int)(-1);
  2747. for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
  2748. if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
  2749. nLastBlock = vInv.size() - 1 - nInv;
  2750. break;
  2751. }
  2752. }
  2753. LOCK(cs_main);
  2754. for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
  2755. {
  2756. const CInv &inv = vInv[nInv];
  2757. boost::this_thread::interruption_point();
  2758. pfrom->AddInventoryKnown(inv);
  2759. bool fAlreadyHave = AlreadyHave(inv);
  2760. LogPrint("net", " got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
  2761. if (!fAlreadyHave) {
  2762. if (!fImporting && !fReindex)
  2763. pfrom->AskFor(inv);
  2764. } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
  2765. PushGetBlocks(pfrom, chainActive.Tip(), GetOrphanRoot(mapOrphanBlocks[inv.hash]));
  2766. } else if (nInv == nLastBlock) {
  2767. // In case we are on a very long side-chain, it is possible that we already have
  2768. // the last block in an inv bundle sent in response to getblocks. Try to detect
  2769. // this situation and push another getblocks to continue.
  2770. PushGetBlocks(pfrom, mapBlockIndex[inv.hash], uint256(0));
  2771. if (fDebug)
  2772. LogPrintf("force request: %s\n", inv.ToString().c_str());
  2773. }
  2774. // Track requests for our stuff
  2775. g_signals.Inventory(inv.hash);
  2776. }
  2777. }
  2778. else if (strCommand == "getdata")
  2779. {
  2780. vector<CInv> vInv;
  2781. vRecv >> vInv;
  2782. if (vInv.size() > MAX_INV_SZ)
  2783. {
  2784. pfrom->Misbehaving(20);
  2785. return error("message getdata size() = %"PRIszu"", vInv.size());
  2786. }
  2787. if (fDebug || (vInv.size() != 1))
  2788. LogPrint("net", "received getdata (%"PRIszu" invsz)\n", vInv.size());
  2789. if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
  2790. LogPrint("net", "received getdata for: %s\n", vInv[0].ToString().c_str());
  2791. pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
  2792. ProcessGetData(pfrom);
  2793. }
  2794. else if (strCommand == "getblocks")
  2795. {
  2796. CBlockLocator locator;
  2797. uint256 hashStop;
  2798. vRecv >> locator >> hashStop;
  2799. LOCK(cs_main);
  2800. // Find the last block the caller has in the main chain
  2801. CBlockIndex* pindex = chainActive.FindFork(locator);
  2802. // Send the rest of the chain
  2803. if (pindex)
  2804. pindex = chainActive.Next(pindex);
  2805. int nLimit = 500;
  2806. LogPrint("net", "getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str(), nLimit);
  2807. for (; pindex; pindex = chainActive.Next(pindex))
  2808. {
  2809. if (pindex->GetBlockHash() == hashStop)
  2810. {
  2811. LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2812. break;
  2813. }
  2814. pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
  2815. if (--nLimit <= 0)
  2816. {
  2817. // When this block is requested, we'll send an inv that'll make them
  2818. // getblocks the next batch of inventory.
  2819. LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2820. pfrom->hashContinue = pindex->GetBlockHash();
  2821. break;
  2822. }
  2823. }
  2824. }
  2825. else if (strCommand == "getheaders")
  2826. {
  2827. CBlockLocator locator;
  2828. uint256 hashStop;
  2829. vRecv >> locator >> hashStop;
  2830. LOCK(cs_main);
  2831. CBlockIndex* pindex = NULL;
  2832. if (locator.IsNull())
  2833. {
  2834. // If locator is null, return the hashStop block
  2835. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
  2836. if (mi == mapBlockIndex.end())
  2837. return true;
  2838. pindex = (*mi).second;
  2839. }
  2840. else
  2841. {
  2842. // Find the last block the caller has in the main chain
  2843. pindex = chainActive.FindFork(locator);
  2844. if (pindex)
  2845. pindex = chainActive.Next(pindex);
  2846. }
  2847. // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
  2848. vector<CBlock> vHeaders;
  2849. int nLimit = 2000;
  2850. LogPrint("net", "getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str());
  2851. for (; pindex; pindex = chainActive.Next(pindex))
  2852. {
  2853. vHeaders.push_back(pindex->GetBlockHeader());
  2854. if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
  2855. break;
  2856. }
  2857. pfrom->PushMessage("headers", vHeaders);
  2858. }
  2859. else if (strCommand == "tx")
  2860. {
  2861. vector<uint256> vWorkQueue;
  2862. vector<uint256> vEraseQueue;
  2863. CTransaction tx;
  2864. vRecv >> tx;
  2865. CInv inv(MSG_TX, tx.GetHash());
  2866. pfrom->AddInventoryKnown(inv);
  2867. LOCK(cs_main);
  2868. bool fMissingInputs = false;
  2869. CValidationState state;
  2870. if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs))
  2871. {
  2872. mempool.check(pcoinsTip);
  2873. RelayTransaction(tx, inv.hash);
  2874. mapAlreadyAskedFor.erase(inv);
  2875. vWorkQueue.push_back(inv.hash);
  2876. vEraseQueue.push_back(inv.hash);
  2877. LogPrint("mempool", "AcceptToMemoryPool: %s %s : accepted %s (poolsz %"PRIszu")\n",
  2878. pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
  2879. tx.GetHash().ToString().c_str(),
  2880. mempool.mapTx.size());
  2881. // Recursively process any orphan transactions that depended on this one
  2882. for (unsigned int i = 0; i < vWorkQueue.size(); i++)
  2883. {
  2884. uint256 hashPrev = vWorkQueue[i];
  2885. for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
  2886. mi != mapOrphanTransactionsByPrev[hashPrev].end();
  2887. ++mi)
  2888. {
  2889. const uint256& orphanHash = *mi;
  2890. const CTransaction& orphanTx = mapOrphanTransactions[orphanHash];
  2891. bool fMissingInputs2 = false;
  2892. // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
  2893. // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
  2894. // anyone relaying LegitTxX banned)
  2895. CValidationState stateDummy;
  2896. if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
  2897. {
  2898. LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString().c_str());
  2899. RelayTransaction(orphanTx, orphanHash);
  2900. mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanHash));
  2901. vWorkQueue.push_back(orphanHash);
  2902. vEraseQueue.push_back(orphanHash);
  2903. }
  2904. else if (!fMissingInputs2)
  2905. {
  2906. // invalid or too-little-fee orphan
  2907. vEraseQueue.push_back(orphanHash);
  2908. LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString().c_str());
  2909. }
  2910. mempool.check(pcoinsTip);
  2911. }
  2912. }
  2913. BOOST_FOREACH(uint256 hash, vEraseQueue)
  2914. EraseOrphanTx(hash);
  2915. }
  2916. else if (fMissingInputs)
  2917. {
  2918. AddOrphanTx(tx);
  2919. // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
  2920. unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
  2921. if (nEvicted > 0)
  2922. LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
  2923. }
  2924. int nDoS = 0;
  2925. if (state.IsInvalid(nDoS))
  2926. {
  2927. LogPrint("mempool", "%s from %s %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString().c_str(),
  2928. pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
  2929. state.GetRejectReason().c_str());
  2930. pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
  2931. state.GetRejectReason(), inv.hash);
  2932. if (nDoS > 0)
  2933. pfrom->Misbehaving(nDoS);
  2934. }
  2935. }
  2936. else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
  2937. {
  2938. CBlock block;
  2939. vRecv >> block;
  2940. LogPrint("net", "received block %s\n", block.GetHash().ToString().c_str());
  2941. // block.print();
  2942. CInv inv(MSG_BLOCK, block.GetHash());
  2943. pfrom->AddInventoryKnown(inv);
  2944. LOCK(cs_main);
  2945. CValidationState state;
  2946. if (ProcessBlock(state, pfrom, &block) || state.CorruptionPossible())
  2947. mapAlreadyAskedFor.erase(inv);
  2948. int nDoS = 0;
  2949. if (state.IsInvalid(nDoS))
  2950. {
  2951. pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
  2952. state.GetRejectReason(), inv.hash);
  2953. if (nDoS > 0)
  2954. pfrom->Misbehaving(nDoS);
  2955. }
  2956. }
  2957. else if (strCommand == "getaddr")
  2958. {
  2959. pfrom->vAddrToSend.clear();
  2960. vector<CAddress> vAddr = addrman.GetAddr();
  2961. BOOST_FOREACH(const CAddress &addr, vAddr)
  2962. pfrom->PushAddress(addr);
  2963. }
  2964. else if (strCommand == "mempool")
  2965. {
  2966. LOCK2(cs_main, pfrom->cs_filter);
  2967. std::vector<uint256> vtxid;
  2968. mempool.queryHashes(vtxid);
  2969. vector<CInv> vInv;
  2970. BOOST_FOREACH(uint256& hash, vtxid) {
  2971. CInv inv(MSG_TX, hash);
  2972. CTransaction tx;
  2973. bool fInMemPool = mempool.lookup(hash, tx);
  2974. if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
  2975. if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx, hash)) ||
  2976. (!pfrom->pfilter))
  2977. vInv.push_back(inv);
  2978. if (vInv.size() == MAX_INV_SZ) {
  2979. pfrom->PushMessage("inv", vInv);
  2980. vInv.clear();
  2981. }
  2982. }
  2983. if (vInv.size() > 0)
  2984. pfrom->PushMessage("inv", vInv);
  2985. }
  2986. else if (strCommand == "ping")
  2987. {
  2988. if (pfrom->nVersion > BIP0031_VERSION)
  2989. {
  2990. uint64_t nonce = 0;
  2991. vRecv >> nonce;
  2992. // Echo the message back with the nonce. This allows for two useful features:
  2993. //
  2994. // 1) A remote node can quickly check if the connection is operational
  2995. // 2) Remote nodes can measure the latency of the network thread. If this node
  2996. // is overloaded it won't respond to pings quickly and the remote node can
  2997. // avoid sending us more work, like chain download requests.
  2998. //
  2999. // The nonce stops the remote getting confused between different pings: without
  3000. // it, if the remote node sends a ping once per second and this node takes 5
  3001. // seconds to respond to each, the 5th ping the remote sends would appear to
  3002. // return very quickly.
  3003. pfrom->PushMessage("pong", nonce);
  3004. }
  3005. }
  3006. else if (strCommand == "pong")
  3007. {
  3008. int64_t pingUsecEnd = GetTimeMicros();
  3009. uint64_t nonce = 0;
  3010. size_t nAvail = vRecv.in_avail();
  3011. bool bPingFinished = false;
  3012. std::string sProblem;
  3013. if (nAvail >= sizeof(nonce)) {
  3014. vRecv >> nonce;
  3015. // Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
  3016. if (pfrom->nPingNonceSent != 0) {
  3017. if (nonce == pfrom->nPingNonceSent) {
  3018. // Matching pong received, this ping is no longer outstanding
  3019. bPingFinished = true;
  3020. int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
  3021. if (pingUsecTime > 0) {
  3022. // Successful ping time measurement, replace previous
  3023. pfrom->nPingUsecTime = pingUsecTime;
  3024. } else {
  3025. // This should never happen
  3026. sProblem = "Timing mishap";
  3027. }
  3028. } else {
  3029. // Nonce mismatches are normal when pings are overlapping
  3030. sProblem = "Nonce mismatch";
  3031. if (nonce == 0) {
  3032. // This is most likely a bug in another implementation somewhere, cancel this ping
  3033. bPingFinished = true;
  3034. sProblem = "Nonce zero";
  3035. }
  3036. }
  3037. } else {
  3038. sProblem = "Unsolicited pong without ping";
  3039. }
  3040. } else {
  3041. // This is most likely a bug in another implementation somewhere, cancel this ping
  3042. bPingFinished = true;
  3043. sProblem = "Short payload";
  3044. }
  3045. if (!(sProblem.empty())) {
  3046. LogPrint("net", "pong %s %s: %s, %"PRIx64" expected, %"PRIx64" received, %"PRIszu" bytes\n",
  3047. pfrom->addr.ToString().c_str(),
  3048. pfrom->cleanSubVer.c_str(),
  3049. sProblem.c_str(),
  3050. pfrom->nPingNonceSent,
  3051. nonce,
  3052. nAvail);
  3053. }
  3054. if (bPingFinished) {
  3055. pfrom->nPingNonceSent = 0;
  3056. }
  3057. }
  3058. else if (strCommand == "alert")
  3059. {
  3060. CAlert alert;
  3061. vRecv >> alert;
  3062. uint256 alertHash = alert.GetHash();
  3063. if (pfrom->setKnown.count(alertHash) == 0)
  3064. {
  3065. if (alert.ProcessAlert())
  3066. {
  3067. // Relay
  3068. pfrom->setKnown.insert(alertHash);
  3069. {
  3070. LOCK(cs_vNodes);
  3071. BOOST_FOREACH(CNode* pnode, vNodes)
  3072. alert.RelayTo(pnode);
  3073. }
  3074. }
  3075. else {
  3076. // Small DoS penalty so peers that send us lots of
  3077. // duplicate/expired/invalid-signature/whatever alerts
  3078. // eventually get banned.
  3079. // This isn't a Misbehaving(100) (immediate ban) because the
  3080. // peer might be an older or different implementation with
  3081. // a different signature key, etc.
  3082. pfrom->Misbehaving(10);
  3083. }
  3084. }
  3085. }
  3086. else if (strCommand == "filterload")
  3087. {
  3088. CBloomFilter filter;
  3089. vRecv >> filter;
  3090. if (!filter.IsWithinSizeConstraints())
  3091. // There is no excuse for sending a too-large filter
  3092. pfrom->Misbehaving(100);
  3093. else
  3094. {
  3095. LOCK(pfrom->cs_filter);
  3096. delete pfrom->pfilter;
  3097. pfrom->pfilter = new CBloomFilter(filter);
  3098. pfrom->pfilter->UpdateEmptyFull();
  3099. }
  3100. pfrom->fRelayTxes = true;
  3101. }
  3102. else if (strCommand == "filteradd")
  3103. {
  3104. vector<unsigned char> vData;
  3105. vRecv >> vData;
  3106. // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
  3107. // and thus, the maximum size any matched object can have) in a filteradd message
  3108. if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
  3109. {
  3110. pfrom->Misbehaving(100);
  3111. } else {
  3112. LOCK(pfrom->cs_filter);
  3113. if (pfrom->pfilter)
  3114. pfrom->pfilter->insert(vData);
  3115. else
  3116. pfrom->Misbehaving(100);
  3117. }
  3118. }
  3119. else if (strCommand == "filterclear")
  3120. {
  3121. LOCK(pfrom->cs_filter);
  3122. delete pfrom->pfilter;
  3123. pfrom->pfilter = new CBloomFilter();
  3124. pfrom->fRelayTxes = true;
  3125. }
  3126. else if (strCommand == "reject")
  3127. {
  3128. if (fDebug)
  3129. {
  3130. string strMsg; unsigned char ccode; string strReason;
  3131. vRecv >> strMsg >> ccode >> strReason;
  3132. ostringstream ss;
  3133. ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
  3134. if (strMsg == "block" || strMsg == "tx")
  3135. {
  3136. uint256 hash;
  3137. vRecv >> hash;
  3138. ss << ": hash " << hash.ToString();
  3139. }
  3140. // Truncate to reasonable length and sanitize before printing:
  3141. string s = ss.str();
  3142. if (s.size() > 111) s.erase(111, string::npos);
  3143. LogPrint("net", "Reject %s\n", SanitizeString(s).c_str());
  3144. }
  3145. }
  3146. else
  3147. {
  3148. // Ignore unknown commands for extensibility
  3149. }
  3150. // Update the last seen time for this node's address
  3151. if (pfrom->fNetworkNode)
  3152. if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
  3153. AddressCurrentlyConnected(pfrom->addr);
  3154. return true;
  3155. }
  3156. // requires LOCK(cs_vRecvMsg)
  3157. bool ProcessMessages(CNode* pfrom)
  3158. {
  3159. //if (fDebug)
  3160. // LogPrintf("ProcessMessages(%"PRIszu" messages)\n", pfrom->vRecvMsg.size());
  3161. //
  3162. // Message format
  3163. // (4) message start
  3164. // (12) command
  3165. // (4) size
  3166. // (4) checksum
  3167. // (x) data
  3168. //
  3169. bool fOk = true;
  3170. if (!pfrom->vRecvGetData.empty())
  3171. ProcessGetData(pfrom);
  3172. // this maintains the order of responses
  3173. if (!pfrom->vRecvGetData.empty()) return fOk;
  3174. std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
  3175. while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
  3176. // Don't bother if send buffer is too full to respond anyway
  3177. if (pfrom->nSendSize >= SendBufferSize())
  3178. break;
  3179. // get next message
  3180. CNetMessage& msg = *it;
  3181. //if (fDebug)
  3182. // LogPrintf("ProcessMessages(message %u msgsz, %"PRIszu" bytes, complete:%s)\n",
  3183. // msg.hdr.nMessageSize, msg.vRecv.size(),
  3184. // msg.complete() ? "Y" : "N");
  3185. // end, if an incomplete message is found
  3186. if (!msg.complete())
  3187. break;
  3188. // at this point, any failure means we can delete the current message
  3189. it++;
  3190. // Scan for message start
  3191. if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
  3192. LogPrintf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
  3193. fOk = false;
  3194. break;
  3195. }
  3196. // Read header
  3197. CMessageHeader& hdr = msg.hdr;
  3198. if (!hdr.IsValid())
  3199. {
  3200. LogPrintf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
  3201. continue;
  3202. }
  3203. string strCommand = hdr.GetCommand();
  3204. // Message size
  3205. unsigned int nMessageSize = hdr.nMessageSize;
  3206. // Checksum
  3207. CDataStream& vRecv = msg.vRecv;
  3208. uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
  3209. unsigned int nChecksum = 0;
  3210. memcpy(&nChecksum, &hash, sizeof(nChecksum));
  3211. if (nChecksum != hdr.nChecksum)
  3212. {
  3213. LogPrintf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
  3214. strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
  3215. continue;
  3216. }
  3217. // Process message
  3218. bool fRet = false;
  3219. try
  3220. {
  3221. fRet = ProcessMessage(pfrom, strCommand, vRecv);
  3222. boost::this_thread::interruption_point();
  3223. }
  3224. catch (std::ios_base::failure& e)
  3225. {
  3226. pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
  3227. if (strstr(e.what(), "end of data"))
  3228. {
  3229. // Allow exceptions from under-length message on vRecv
  3230. LogPrintf("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());
  3231. }
  3232. else if (strstr(e.what(), "size too large"))
  3233. {
  3234. // Allow exceptions from over-long size
  3235. LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
  3236. }
  3237. else
  3238. {
  3239. PrintExceptionContinue(&e, "ProcessMessages()");
  3240. }
  3241. }
  3242. catch (boost::thread_interrupted) {
  3243. throw;
  3244. }
  3245. catch (std::exception& e) {
  3246. PrintExceptionContinue(&e, "ProcessMessages()");
  3247. } catch (...) {
  3248. PrintExceptionContinue(NULL, "ProcessMessages()");
  3249. }
  3250. if (!fRet)
  3251. LogPrintf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
  3252. break;
  3253. }
  3254. // In case the connection got shut down, its receive buffer was wiped
  3255. if (!pfrom->fDisconnect)
  3256. pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
  3257. return fOk;
  3258. }
  3259. bool SendMessages(CNode* pto, bool fSendTrickle)
  3260. {
  3261. {
  3262. // Don't send anything until we get their version message
  3263. if (pto->nVersion == 0)
  3264. return true;
  3265. //
  3266. // Message: ping
  3267. //
  3268. bool pingSend = false;
  3269. if (pto->fPingQueued) {
  3270. // RPC ping request by user
  3271. pingSend = true;
  3272. }
  3273. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSendMsg.empty()) {
  3274. // Ping automatically sent as a keepalive
  3275. pingSend = true;
  3276. }
  3277. if (pingSend) {
  3278. uint64_t nonce = 0;
  3279. while (nonce == 0) {
  3280. RAND_bytes((unsigned char*)&nonce, sizeof(nonce));
  3281. }
  3282. pto->nPingNonceSent = nonce;
  3283. pto->fPingQueued = false;
  3284. if (pto->nVersion > BIP0031_VERSION) {
  3285. // Take timestamp as close as possible before transmitting ping
  3286. pto->nPingUsecStart = GetTimeMicros();
  3287. pto->PushMessage("ping", nonce);
  3288. } else {
  3289. // Peer is too old to support ping command with nonce, pong will never arrive, disable timing
  3290. pto->nPingUsecStart = 0;
  3291. pto->PushMessage("ping");
  3292. }
  3293. }
  3294. // Address refresh broadcast
  3295. static int64_t nLastRebroadcast;
  3296. if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
  3297. {
  3298. {
  3299. LOCK(cs_vNodes);
  3300. BOOST_FOREACH(CNode* pnode, vNodes)
  3301. {
  3302. // Periodically clear setAddrKnown to allow refresh broadcasts
  3303. if (nLastRebroadcast)
  3304. pnode->setAddrKnown.clear();
  3305. // Rebroadcast our address
  3306. if (!fNoListen)
  3307. {
  3308. CAddress addr = GetLocalAddress(&pnode->addr);
  3309. if (addr.IsRoutable())
  3310. pnode->PushAddress(addr);
  3311. }
  3312. }
  3313. }
  3314. nLastRebroadcast = GetTime();
  3315. }
  3316. //
  3317. // Message: addr
  3318. //
  3319. if (fSendTrickle)
  3320. {
  3321. vector<CAddress> vAddr;
  3322. vAddr.reserve(pto->vAddrToSend.size());
  3323. BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
  3324. {
  3325. // returns true if wasn't already contained in the set
  3326. if (pto->setAddrKnown.insert(addr).second)
  3327. {
  3328. vAddr.push_back(addr);
  3329. // receiver rejects addr messages larger than 1000
  3330. if (vAddr.size() >= 1000)
  3331. {
  3332. pto->PushMessage("addr", vAddr);
  3333. vAddr.clear();
  3334. }
  3335. }
  3336. }
  3337. pto->vAddrToSend.clear();
  3338. if (!vAddr.empty())
  3339. pto->PushMessage("addr", vAddr);
  3340. }
  3341. TRY_LOCK(cs_main, lockMain);
  3342. if (!lockMain)
  3343. return true;
  3344. // Start block sync
  3345. if (pto->fStartSync && !fImporting && !fReindex) {
  3346. pto->fStartSync = false;
  3347. PushGetBlocks(pto, chainActive.Tip(), uint256(0));
  3348. }
  3349. // Resend wallet transactions that haven't gotten in a block yet
  3350. // Except during reindex, importing and IBD, when old wallet
  3351. // transactions become unconfirmed and spams other nodes.
  3352. if (!fReindex && !fImporting && !IsInitialBlockDownload())
  3353. {
  3354. g_signals.Broadcast();
  3355. }
  3356. //
  3357. // Message: inventory
  3358. //
  3359. vector<CInv> vInv;
  3360. vector<CInv> vInvWait;
  3361. {
  3362. LOCK(pto->cs_inventory);
  3363. vInv.reserve(pto->vInventoryToSend.size());
  3364. vInvWait.reserve(pto->vInventoryToSend.size());
  3365. BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
  3366. {
  3367. if (pto->setInventoryKnown.count(inv))
  3368. continue;
  3369. // trickle out tx inv to protect privacy
  3370. if (inv.type == MSG_TX && !fSendTrickle)
  3371. {
  3372. // 1/4 of tx invs blast to all immediately
  3373. static uint256 hashSalt;
  3374. if (hashSalt == 0)
  3375. hashSalt = GetRandHash();
  3376. uint256 hashRand = inv.hash ^ hashSalt;
  3377. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  3378. bool fTrickleWait = ((hashRand & 3) != 0);
  3379. if (fTrickleWait)
  3380. {
  3381. vInvWait.push_back(inv);
  3382. continue;
  3383. }
  3384. }
  3385. // returns true if wasn't already contained in the set
  3386. if (pto->setInventoryKnown.insert(inv).second)
  3387. {
  3388. vInv.push_back(inv);
  3389. if (vInv.size() >= 1000)
  3390. {
  3391. pto->PushMessage("inv", vInv);
  3392. vInv.clear();
  3393. }
  3394. }
  3395. }
  3396. pto->vInventoryToSend = vInvWait;
  3397. }
  3398. if (!vInv.empty())
  3399. pto->PushMessage("inv", vInv);
  3400. //
  3401. // Message: getdata
  3402. //
  3403. vector<CInv> vGetData;
  3404. int64_t nNow = GetTime() * 1000000;
  3405. while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
  3406. {
  3407. const CInv& inv = (*pto->mapAskFor.begin()).second;
  3408. if (!AlreadyHave(inv))
  3409. {
  3410. if (fDebug)
  3411. LogPrint("net", "sending getdata: %s\n", inv.ToString().c_str());
  3412. vGetData.push_back(inv);
  3413. if (vGetData.size() >= 1000)
  3414. {
  3415. pto->PushMessage("getdata", vGetData);
  3416. vGetData.clear();
  3417. }
  3418. }
  3419. pto->mapAskFor.erase(pto->mapAskFor.begin());
  3420. }
  3421. if (!vGetData.empty())
  3422. pto->PushMessage("getdata", vGetData);
  3423. }
  3424. return true;
  3425. }
  3426. class CMainCleanup
  3427. {
  3428. public:
  3429. CMainCleanup() {}
  3430. ~CMainCleanup() {
  3431. // block headers
  3432. std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
  3433. for (; it1 != mapBlockIndex.end(); it1++)
  3434. delete (*it1).second;
  3435. mapBlockIndex.clear();
  3436. // orphan blocks
  3437. std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
  3438. for (; it2 != mapOrphanBlocks.end(); it2++)
  3439. delete (*it2).second;
  3440. mapOrphanBlocks.clear();
  3441. // orphan transactions
  3442. mapOrphanTransactions.clear();
  3443. }
  3444. } instance_of_cmaincleanup;