main.cpp 139 KB

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