main.h 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  1. // ECOin - Copyright (c) - 2014/2022 - GPLv3 - epsylon@riseup.net (https://03c8.net)
  2. #ifndef ECOIN_MAIN_H
  3. #define ECOIN_MAIN_H
  4. #include "bignum.h"
  5. #include "sync.h"
  6. #include "net.h"
  7. #include "script.h"
  8. #include "scrypt.h"
  9. #include "zerocoin/Zerocoin.h"
  10. #include "base58.h"
  11. #include <list>
  12. class CWallet;
  13. class CBlock;
  14. class CBlockIndex;
  15. class CKeyItem;
  16. class CReserveKey;
  17. class COutPoint;
  18. class CAddress;
  19. class CInv;
  20. class CRequestTracker;
  21. class CNode;
  22. static const unsigned int MAX_BLOCK_SIZE = 1000000;
  23. static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
  24. static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
  25. static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
  26. static const unsigned int MAX_INV_SZ = 50000;
  27. static const int64 MIN_TX_FEE = CENT;
  28. static const int64 MIN_RELAY_TX_FEE = CENT;
  29. static const int64 MAX_MONEY = 50000000000LL * COIN;
  30. static const int64 MAX_MINT_PROOF_OF_WORK = 10000 * COIN;
  31. static const int64 MAX_MINT_PROOF_OF_STAKE = 1 * COIN;
  32. static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE;
  33. static const unsigned int ENTROPY_SWITCH_TIME = 1420070399; // Dec 31 2014, 23:59:59 PM GMT
  34. static const unsigned int FORK_FINAL = 1397936903;
  35. string SearchTerm(const char *chAddress);
  36. string SearchTermV2(const char *chAddress);
  37. bool fAddrMiner (const char *chHash, const char *chTerm);
  38. inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
  39. static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
  40. #ifdef USE_UPNP
  41. static const int fHaveUPnP = true;
  42. #else
  43. static const int fHaveUPnP = false;
  44. #endif
  45. static const uint256 hashGenesisBlock("0x000003e158b5cdd1a1bf05dac19d9c171998f9a9c62307adac2cb842029b0dbd"); // ECOIN - Genesis Hash
  46. static const uint256 hashGenesisBlockTestNet("0x0000568ef00493151a15b68b6d12713ec52df65077d4bdd8235f98420da6cc33"); // ECOIN - TestNet Genesis Hash
  47. inline int64 PastDrift(int64 nTime) { return nTime - 2 * 60 * 60; } // up to 2 hours from the past
  48. inline int64 FutureDrift(int64 nTime) { return nTime + 2 * 60 * 60; } // up to 2 hours from the future
  49. extern libzerocoin::Params* ZCParams;
  50. extern CScript COINBASE_FLAGS;
  51. extern CCriticalSection cs_main;
  52. extern std::map<uint256, CBlockIndex*> mapBlockIndex;
  53. extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
  54. extern CBlockIndex* pindexGenesisBlock;
  55. extern unsigned int nStakeMinAge;
  56. extern unsigned int nNodeLifespan;
  57. extern int nCoinbaseMaturity;
  58. extern int nBestHeight;
  59. extern uint256 nBestChainTrust;
  60. extern uint256 nBestInvalidTrust;
  61. extern uint256 hashBestChain;
  62. extern CBlockIndex* pindexBest;
  63. extern unsigned int nTransactionsUpdated;
  64. extern uint64 nLastBlockTx;
  65. extern uint64 nLastBlockSize;
  66. extern int64 nLastCoinStakeSearchInterval;
  67. extern const std::string strMessageMagic;
  68. extern int64 nTimeBestReceived;
  69. extern CCriticalSection cs_setpwalletRegistered;
  70. extern std::set<CWallet*> setpwalletRegistered;
  71. extern unsigned char pchMessageStart[4];
  72. extern std::map<uint256, CBlock*> mapOrphanBlocks;
  73. // Settings
  74. extern int64 nTransactionFee;
  75. extern int64 nMinimumInputValue;
  76. extern bool fUseFastIndex;
  77. extern unsigned int nDerivationMethodIndex;
  78. extern bool fEnforceCanonical;
  79. // Minimum disk space required - used in CheckDiskSpace()
  80. static const uint64 nMinDiskSpace = 52428800;
  81. class CReserveKey;
  82. class CTxDB;
  83. class CTxIndex;
  84. void RegisterWallet(CWallet* pwalletIn);
  85. void UnregisterWallet(CWallet* pwalletIn);
  86. void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
  87. bool ProcessBlock(CNode* pfrom, CBlock* pblock);
  88. bool CheckDiskSpace(uint64 nAdditionalBytes=0);
  89. FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
  90. FILE* AppendBlockFile(unsigned int& nFileRet);
  91. bool LoadBlockIndex(bool fAllowNew=true);
  92. void PrintBlockTree();
  93. CBlockIndex* FindBlockByHeight(int nHeight);
  94. bool ProcessMessages(CNode* pfrom);
  95. bool SendMessages(CNode* pto, bool fSendTrickle);
  96. bool LoadExternalBlockFile(FILE* fileIn);
  97. bool CheckProofOfWork(uint256 hash, unsigned int nBits);
  98. unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
  99. int64 GetProofOfWorkReward(unsigned int nHeight, uint256 hashSeed);
  100. int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly=false);
  101. unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
  102. unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
  103. int GetNumBlocksOfPeers();
  104. bool IsInitialBlockDownload();
  105. std::string GetWarnings(std::string strFor);
  106. bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
  107. uint256 WantedByOrphan(const CBlock* pblockOrphan);
  108. const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
  109. void StakeMiner(CWallet *pwallet);
  110. void ResendWalletTransactions(bool fForce = false);
  111. bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
  112. /** Position on disk for a particular transaction. */
  113. class CDiskTxPos
  114. {
  115. public:
  116. unsigned int nFile;
  117. unsigned int nBlockPos;
  118. unsigned int nTxPos;
  119. CDiskTxPos()
  120. {
  121. SetNull();
  122. }
  123. CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
  124. {
  125. nFile = nFileIn;
  126. nBlockPos = nBlockPosIn;
  127. nTxPos = nTxPosIn;
  128. }
  129. IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
  130. void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
  131. bool IsNull() const { return (nFile == (unsigned int) -1); }
  132. friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
  133. {
  134. return (a.nFile == b.nFile &&
  135. a.nBlockPos == b.nBlockPos &&
  136. a.nTxPos == b.nTxPos);
  137. }
  138. friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
  139. {
  140. return !(a == b);
  141. }
  142. std::string ToString() const
  143. {
  144. if (IsNull())
  145. return "null";
  146. else
  147. return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
  148. }
  149. void print() const
  150. {
  151. printf("%s", ToString().c_str());
  152. }
  153. };
  154. class CInPoint
  155. {
  156. public:
  157. CTransaction* ptx;
  158. unsigned int n;
  159. CInPoint() { SetNull(); }
  160. CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
  161. void SetNull() { ptx = NULL; n = (unsigned int) -1; }
  162. bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
  163. };
  164. class COutPoint
  165. {
  166. public:
  167. uint256 hash;
  168. unsigned int n;
  169. COutPoint() { SetNull(); }
  170. COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
  171. IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
  172. void SetNull() { hash = 0; n = (unsigned int) -1; }
  173. bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
  174. friend bool operator<(const COutPoint& a, const COutPoint& b)
  175. {
  176. return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
  177. }
  178. friend bool operator==(const COutPoint& a, const COutPoint& b)
  179. {
  180. return (a.hash == b.hash && a.n == b.n);
  181. }
  182. friend bool operator!=(const COutPoint& a, const COutPoint& b)
  183. {
  184. return !(a == b);
  185. }
  186. std::string ToString() const
  187. {
  188. return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
  189. }
  190. void print() const
  191. {
  192. printf("%s\n", ToString().c_str());
  193. }
  194. };
  195. class CTxIn
  196. {
  197. public:
  198. COutPoint prevout;
  199. CScript scriptSig;
  200. unsigned int nSequence;
  201. CTxIn()
  202. {
  203. nSequence = std::numeric_limits<unsigned int>::max();
  204. }
  205. explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
  206. {
  207. prevout = prevoutIn;
  208. scriptSig = scriptSigIn;
  209. nSequence = nSequenceIn;
  210. }
  211. CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
  212. {
  213. prevout = COutPoint(hashPrevTx, nOut);
  214. scriptSig = scriptSigIn;
  215. nSequence = nSequenceIn;
  216. }
  217. IMPLEMENT_SERIALIZE
  218. (
  219. READWRITE(prevout);
  220. READWRITE(scriptSig);
  221. READWRITE(nSequence);
  222. )
  223. bool IsFinal() const
  224. {
  225. return (nSequence == std::numeric_limits<unsigned int>::max());
  226. }
  227. friend bool operator==(const CTxIn& a, const CTxIn& b)
  228. {
  229. return (a.prevout == b.prevout &&
  230. a.scriptSig == b.scriptSig &&
  231. a.nSequence == b.nSequence);
  232. }
  233. friend bool operator!=(const CTxIn& a, const CTxIn& b)
  234. {
  235. return !(a == b);
  236. }
  237. std::string ToStringShort() const
  238. {
  239. return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
  240. }
  241. std::string ToString() const
  242. {
  243. std::string str;
  244. str += "CTxIn(";
  245. str += prevout.ToString();
  246. if (prevout.IsNull())
  247. str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
  248. else
  249. str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
  250. if (nSequence != std::numeric_limits<unsigned int>::max())
  251. str += strprintf(", nSequence=%u", nSequence);
  252. str += ")";
  253. return str;
  254. }
  255. void print() const
  256. {
  257. printf("%s\n", ToString().c_str());
  258. }
  259. };
  260. class CTxOut
  261. {
  262. public:
  263. int64 nValue;
  264. CScript scriptPubKey;
  265. CTxOut()
  266. {
  267. SetNull();
  268. }
  269. CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
  270. {
  271. nValue = nValueIn;
  272. scriptPubKey = scriptPubKeyIn;
  273. }
  274. IMPLEMENT_SERIALIZE
  275. (
  276. READWRITE(nValue);
  277. READWRITE(scriptPubKey);
  278. )
  279. void SetNull()
  280. {
  281. nValue = -1;
  282. scriptPubKey.clear();
  283. }
  284. bool IsNull()
  285. {
  286. return (nValue == -1);
  287. }
  288. void SetEmpty()
  289. {
  290. nValue = 0;
  291. scriptPubKey.clear();
  292. }
  293. bool IsEmpty() const
  294. {
  295. return (nValue == 0 && scriptPubKey.empty());
  296. }
  297. uint256 GetHash() const
  298. {
  299. return SerializeHash(*this);
  300. }
  301. friend bool operator==(const CTxOut& a, const CTxOut& b)
  302. {
  303. return (a.nValue == b.nValue &&
  304. a.scriptPubKey == b.scriptPubKey);
  305. }
  306. friend bool operator!=(const CTxOut& a, const CTxOut& b)
  307. {
  308. return !(a == b);
  309. }
  310. std::string ToStringShort() const
  311. {
  312. return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
  313. }
  314. std::string ToString() const
  315. {
  316. if (IsEmpty()) return "CTxOut(empty)";
  317. if (scriptPubKey.size() < 6)
  318. return "CTxOut(error)";
  319. return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
  320. }
  321. void print() const
  322. {
  323. printf("%s\n", ToString().c_str());
  324. }
  325. };
  326. enum GetMinFee_mode
  327. {
  328. GMF_BLOCK,
  329. GMF_RELAY,
  330. GMF_SEND,
  331. };
  332. typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
  333. class CTransaction
  334. {
  335. public:
  336. static const int CURRENT_VERSION=1;
  337. int nVersion;
  338. unsigned int nTime;
  339. std::vector<CTxIn> vin;
  340. std::vector<CTxOut> vout;
  341. unsigned int nLockTime;
  342. mutable int nDoS;
  343. bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
  344. CTransaction()
  345. {
  346. SetNull();
  347. }
  348. IMPLEMENT_SERIALIZE
  349. (
  350. READWRITE(this->nVersion);
  351. nVersion = this->nVersion;
  352. READWRITE(nTime);
  353. READWRITE(vin);
  354. READWRITE(vout);
  355. READWRITE(nLockTime);
  356. )
  357. void SetNull()
  358. {
  359. nVersion = CTransaction::CURRENT_VERSION;
  360. nTime = GetAdjustedTime();
  361. vin.clear();
  362. vout.clear();
  363. nLockTime = 0;
  364. nDoS = 0; // Denial-of-service prevention
  365. }
  366. bool IsNull() const
  367. {
  368. return (vin.empty() && vout.empty());
  369. }
  370. uint256 GetHash() const
  371. {
  372. return SerializeHash(*this);
  373. }
  374. bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
  375. {
  376. if (nLockTime == 0)
  377. return true;
  378. if (nBlockHeight == 0)
  379. nBlockHeight = nBestHeight;
  380. if (nBlockTime == 0)
  381. nBlockTime = GetAdjustedTime();
  382. if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
  383. return true;
  384. BOOST_FOREACH(const CTxIn& txin, vin)
  385. if (!txin.IsFinal())
  386. return false;
  387. return true;
  388. }
  389. bool IsNewerThan(const CTransaction& old) const
  390. {
  391. if (vin.size() != old.vin.size())
  392. return false;
  393. for (unsigned int i = 0; i < vin.size(); i++)
  394. if (vin[i].prevout != old.vin[i].prevout)
  395. return false;
  396. bool fNewer = false;
  397. unsigned int nLowest = std::numeric_limits<unsigned int>::max();
  398. for (unsigned int i = 0; i < vin.size(); i++)
  399. {
  400. if (vin[i].nSequence != old.vin[i].nSequence)
  401. {
  402. if (vin[i].nSequence <= nLowest)
  403. {
  404. fNewer = false;
  405. nLowest = vin[i].nSequence;
  406. }
  407. if (old.vin[i].nSequence < nLowest)
  408. {
  409. fNewer = true;
  410. nLowest = old.vin[i].nSequence;
  411. }
  412. }
  413. }
  414. return fNewer;
  415. }
  416. bool IsCoinBase() const
  417. {
  418. return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
  419. }
  420. bool IsCoinStake() const
  421. {
  422. // ecoin: the coin stake transaction is marked with the first output empty
  423. return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
  424. }
  425. bool IsStandard() const;
  426. bool AreInputsStandard(const MapPrevTx& mapInputs) const;
  427. unsigned int GetLegacySigOpCount() const;
  428. unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
  429. int64 GetValueOut() const
  430. {
  431. int64 nValueOut = 0;
  432. BOOST_FOREACH(const CTxOut& txout, vout)
  433. {
  434. nValueOut += txout.nValue;
  435. if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
  436. throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
  437. }
  438. return nValueOut;
  439. }
  440. int64 GetValueIn(const MapPrevTx& mapInputs) const;
  441. static bool AllowFree(double dPriority)
  442. {
  443. return dPriority > COIN * 720 / 250;
  444. }
  445. int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
  446. bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
  447. {
  448. CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
  449. if (!filein)
  450. return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
  451. // Read transaction
  452. if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
  453. return error("CTransaction::ReadFromDisk() : fseek failed");
  454. try {
  455. filein >> *this;
  456. }
  457. catch (std::exception &e) {
  458. return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
  459. }
  460. // Return file pointer
  461. if (pfileRet)
  462. {
  463. if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
  464. return error("CTransaction::ReadFromDisk() : second fseek failed");
  465. *pfileRet = filein.release();
  466. }
  467. return true;
  468. }
  469. friend bool operator==(const CTransaction& a, const CTransaction& b)
  470. {
  471. return (a.nVersion == b.nVersion &&
  472. a.nTime == b.nTime &&
  473. a.vin == b.vin &&
  474. a.vout == b.vout &&
  475. a.nLockTime == b.nLockTime);
  476. }
  477. friend bool operator!=(const CTransaction& a, const CTransaction& b)
  478. {
  479. return !(a == b);
  480. }
  481. std::string ToStringShort() const
  482. {
  483. std::string str;
  484. str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
  485. return str;
  486. }
  487. std::string ToString() const
  488. {
  489. std::string str;
  490. str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
  491. str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%" PRIszu", vout.size=%" PRIszu", nLockTime=%d)\n",
  492. GetHash().ToString().substr(0,10).c_str(),
  493. nTime,
  494. nVersion,
  495. vin.size(),
  496. vout.size(),
  497. nLockTime);
  498. for (unsigned int i = 0; i < vin.size(); i++)
  499. str += " " + vin[i].ToString() + "\n";
  500. for (unsigned int i = 0; i < vout.size(); i++)
  501. str += " " + vout[i].ToString() + "\n";
  502. return str;
  503. }
  504. void print() const
  505. {
  506. printf("%s", ToString().c_str());
  507. }
  508. bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
  509. bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
  510. bool ReadFromDisk(COutPoint prevout);
  511. bool DisconnectInputs(CTxDB& txdb);
  512. bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
  513. bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
  514. bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
  515. std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
  516. const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
  517. bool ClientConnectInputs();
  518. bool CheckTransaction() const;
  519. bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
  520. bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ecoin: get transaction coin age
  521. protected:
  522. const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
  523. };
  524. class CMerkleTx : public CTransaction
  525. {
  526. public:
  527. uint256 hashBlock;
  528. std::vector<uint256> vMerkleBranch;
  529. int nIndex;
  530. mutable bool fMerkleVerified;
  531. CMerkleTx()
  532. {
  533. Init();
  534. }
  535. CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
  536. {
  537. Init();
  538. }
  539. void Init()
  540. {
  541. hashBlock = 0;
  542. nIndex = -1;
  543. fMerkleVerified = false;
  544. }
  545. IMPLEMENT_SERIALIZE
  546. (
  547. nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
  548. nVersion = this->nVersion;
  549. READWRITE(hashBlock);
  550. READWRITE(vMerkleBranch);
  551. READWRITE(nIndex);
  552. )
  553. int SetMerkleBranch(const CBlock* pblock=NULL);
  554. int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
  555. int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
  556. bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
  557. int GetBlocksToMaturity() const;
  558. bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
  559. bool AcceptToMemoryPool();
  560. };
  561. class CTxIndex
  562. {
  563. public:
  564. CDiskTxPos pos;
  565. std::vector<CDiskTxPos> vSpent;
  566. CTxIndex()
  567. {
  568. SetNull();
  569. }
  570. CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
  571. {
  572. pos = posIn;
  573. vSpent.resize(nOutputs);
  574. }
  575. IMPLEMENT_SERIALIZE
  576. (
  577. if (!(nType & SER_GETHASH))
  578. READWRITE(nVersion);
  579. READWRITE(pos);
  580. READWRITE(vSpent);
  581. )
  582. void SetNull()
  583. {
  584. pos.SetNull();
  585. vSpent.clear();
  586. }
  587. bool IsNull()
  588. {
  589. return pos.IsNull();
  590. }
  591. friend bool operator==(const CTxIndex& a, const CTxIndex& b)
  592. {
  593. return (a.pos == b.pos &&
  594. a.vSpent == b.vSpent);
  595. }
  596. friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
  597. {
  598. return !(a == b);
  599. }
  600. int GetDepthInMainChain() const;
  601. };
  602. class CBlock
  603. {
  604. public:
  605. // header
  606. static const int CURRENT_VERSION=6;
  607. int nVersion;
  608. uint256 hashPrevBlock;
  609. uint256 hashMerkleRoot;
  610. unsigned int nTime;
  611. unsigned int nBits;
  612. unsigned int nNonce;
  613. // network and disk
  614. std::vector<CTransaction> vtx;
  615. // ecoin: block signature - signed by one of the coin base txout[N]'s owner
  616. std::vector<unsigned char> vchBlockSig;
  617. // memory only
  618. mutable std::vector<uint256> vMerkleTree;
  619. // Denial-of-service detection:
  620. mutable int nDoS;
  621. bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
  622. CBlock()
  623. {
  624. SetNull();
  625. }
  626. IMPLEMENT_SERIALIZE
  627. (
  628. READWRITE(this->nVersion);
  629. nVersion = this->nVersion;
  630. READWRITE(hashPrevBlock);
  631. READWRITE(hashMerkleRoot);
  632. READWRITE(nTime);
  633. READWRITE(nBits);
  634. READWRITE(nNonce);
  635. // ConnectBlock depends on vtx following header to generate CDiskTxPos
  636. if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
  637. {
  638. READWRITE(vtx);
  639. READWRITE(vchBlockSig);
  640. }
  641. else if (fRead)
  642. {
  643. const_cast<CBlock*>(this)->vtx.clear();
  644. const_cast<CBlock*>(this)->vchBlockSig.clear();
  645. }
  646. )
  647. void SetNull()
  648. {
  649. nVersion = CBlock::CURRENT_VERSION;
  650. hashPrevBlock = 0;
  651. hashMerkleRoot = 0;
  652. nTime = 0;
  653. nBits = 0;
  654. nNonce = 0;
  655. vtx.clear();
  656. vchBlockSig.clear();
  657. vMerkleTree.clear();
  658. nDoS = 0;
  659. }
  660. bool IsNull() const
  661. {
  662. return (nBits == 0);
  663. }
  664. uint256 GetHash() const
  665. {
  666. return scrypt_blockhash(CVOIDBEGIN(nVersion));
  667. }
  668. int64 GetBlockTime() const
  669. {
  670. return (int64)nTime;
  671. }
  672. void UpdateTime(const CBlockIndex* pindexPrev);
  673. // ecoin: entropy bit for stake modifier if chosen by modifier
  674. unsigned int GetStakeEntropyBit(unsigned int nTime) const
  675. {
  676. // Take last bit of block hash as entropy bit
  677. unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
  678. if (fDebug && GetBoolArg("-printstakemodifier"))
  679. printf("GetStakeEntropyBit: nTime=%u hashBlock=%s nEntropyBit=%u\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
  680. return nEntropyBit;
  681. }
  682. // ecoin: two types of block: proof-of-work or proof-of-stake
  683. bool IsProofOfStake() const
  684. {
  685. return (vtx.size() > 1 && vtx[1].IsCoinStake());
  686. }
  687. bool IsProofOfWork() const
  688. {
  689. return !IsProofOfStake();
  690. }
  691. std::pair<COutPoint, unsigned int> GetProofOfStake() const
  692. {
  693. return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
  694. }
  695. // ecoin: get max transaction timestamp
  696. int64 GetMaxTransactionTime() const
  697. {
  698. int64 maxTransactionTime = 0;
  699. BOOST_FOREACH(const CTransaction& tx, vtx)
  700. maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
  701. return maxTransactionTime;
  702. }
  703. uint256 BuildMerkleTree() const
  704. {
  705. vMerkleTree.clear();
  706. BOOST_FOREACH(const CTransaction& tx, vtx)
  707. vMerkleTree.push_back(tx.GetHash());
  708. int j = 0;
  709. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  710. {
  711. for (int i = 0; i < nSize; i += 2)
  712. {
  713. int i2 = std::min(i+1, nSize-1);
  714. vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
  715. BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
  716. }
  717. j += nSize;
  718. }
  719. return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
  720. }
  721. std::vector<uint256> GetMerkleBranch(int nIndex) const
  722. {
  723. if (vMerkleTree.empty())
  724. BuildMerkleTree();
  725. std::vector<uint256> vMerkleBranch;
  726. int j = 0;
  727. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  728. {
  729. int i = std::min(nIndex^1, nSize-1);
  730. vMerkleBranch.push_back(vMerkleTree[j+i]);
  731. nIndex >>= 1;
  732. j += nSize;
  733. }
  734. return vMerkleBranch;
  735. }
  736. static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
  737. {
  738. if (nIndex == -1)
  739. return 0;
  740. BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
  741. {
  742. if (nIndex & 1)
  743. hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
  744. else
  745. hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
  746. nIndex >>= 1;
  747. }
  748. return hash;
  749. }
  750. bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
  751. {
  752. // Open history file to append
  753. CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
  754. if (!fileout)
  755. return error("CBlock::WriteToDisk() : AppendBlockFile failed");
  756. // Write index header
  757. unsigned int nSize = fileout.GetSerializeSize(*this);
  758. fileout << FLATDATA(pchMessageStart) << nSize;
  759. // Write block
  760. long fileOutPos = ftell(fileout);
  761. if (fileOutPos < 0)
  762. return error("CBlock::WriteToDisk() : ftell failed");
  763. nBlockPosRet = fileOutPos;
  764. fileout << *this;
  765. // Flush stdio buffers and commit to disk before returning
  766. fflush(fileout);
  767. if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
  768. FileCommit(fileout);
  769. return true;
  770. }
  771. bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
  772. {
  773. SetNull();
  774. // Open history file to read
  775. CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
  776. if (!filein)
  777. return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
  778. if (!fReadTransactions)
  779. filein.nType |= SER_BLOCKHEADERONLY;
  780. // Read block
  781. try {
  782. filein >> *this;
  783. }
  784. catch (std::exception &e) {
  785. return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
  786. }
  787. // Check the header
  788. if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
  789. return error("CBlock::ReadFromDisk() : errors in block header");
  790. return true;
  791. }
  792. void print() const
  793. {
  794. printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%" PRIszu", vchBlockSig=%s)\n",
  795. GetHash().ToString().c_str(),
  796. nVersion,
  797. hashPrevBlock.ToString().c_str(),
  798. hashMerkleRoot.ToString().c_str(),
  799. nTime, nBits, nNonce,
  800. vtx.size(),
  801. HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
  802. for (unsigned int i = 0; i < vtx.size(); i++)
  803. {
  804. printf(" ");
  805. vtx[i].print();
  806. }
  807. printf(" vMerkleTree: ");
  808. for (unsigned int i = 0; i < vMerkleTree.size(); i++)
  809. printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
  810. printf("\n");
  811. }
  812. bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
  813. bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
  814. bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
  815. bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
  816. bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
  817. bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
  818. bool AcceptBlock();
  819. bool GetCoinAge(uint64& nCoinAge) const; // ecoin: calculate total coin age spent in block
  820. bool SignBlock(CWallet& keystore);
  821. bool CheckBlockSignature(bool fProofOfStake) const;
  822. private:
  823. bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
  824. };
  825. class CBlockIndex
  826. {
  827. public:
  828. const uint256* phashBlock;
  829. CBlockIndex* pprev;
  830. CBlockIndex* pnext;
  831. unsigned int nFile;
  832. unsigned int nBlockPos;
  833. uint256 nChainTrust; // ecoin: trust score of block chain
  834. int nHeight;
  835. int64 nMint;
  836. int64 nMoneySupply;
  837. unsigned int nFlags; // ecoin: block index flags
  838. enum
  839. {
  840. BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
  841. BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
  842. BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
  843. };
  844. uint64 nStakeModifier; // hash modifier for proof-of-stake
  845. unsigned int nStakeModifierChecksum; // checksum of index; in-memory only
  846. // proof-of-stake specific fields
  847. COutPoint prevoutStake;
  848. unsigned int nStakeTime;
  849. uint256 hashProofOfStake;
  850. // block header
  851. int nVersion;
  852. uint256 hashMerkleRoot;
  853. unsigned int nTime;
  854. unsigned int nBits;
  855. unsigned int nNonce;
  856. CBlockIndex()
  857. {
  858. phashBlock = NULL;
  859. pprev = NULL;
  860. pnext = NULL;
  861. nFile = 0;
  862. nBlockPos = 0;
  863. nHeight = 0;
  864. nChainTrust = 0;
  865. nMint = 0;
  866. nMoneySupply = 0;
  867. nFlags = 0;
  868. nStakeModifier = 0;
  869. nStakeModifierChecksum = 0;
  870. hashProofOfStake = 0;
  871. prevoutStake.SetNull();
  872. nStakeTime = 0;
  873. nVersion = 0;
  874. hashMerkleRoot = 0;
  875. nTime = 0;
  876. nBits = 0;
  877. nNonce = 0;
  878. }
  879. CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
  880. {
  881. phashBlock = NULL;
  882. pprev = NULL;
  883. pnext = NULL;
  884. nFile = nFileIn;
  885. nBlockPos = nBlockPosIn;
  886. nHeight = 0;
  887. nChainTrust = 0;
  888. nMint = 0;
  889. nMoneySupply = 0;
  890. nFlags = 0;
  891. nStakeModifier = 0;
  892. nStakeModifierChecksum = 0;
  893. hashProofOfStake = 0;
  894. if (block.IsProofOfStake())
  895. {
  896. SetProofOfStake();
  897. prevoutStake = block.vtx[1].vin[0].prevout;
  898. nStakeTime = block.vtx[1].nTime;
  899. }
  900. else
  901. {
  902. prevoutStake.SetNull();
  903. nStakeTime = 0;
  904. }
  905. nVersion = block.nVersion;
  906. hashMerkleRoot = block.hashMerkleRoot;
  907. nTime = block.nTime;
  908. nBits = block.nBits;
  909. nNonce = block.nNonce;
  910. }
  911. CBlock GetBlockHeader() const
  912. {
  913. CBlock block;
  914. block.nVersion = nVersion;
  915. if (pprev)
  916. block.hashPrevBlock = pprev->GetBlockHash();
  917. block.hashMerkleRoot = hashMerkleRoot;
  918. block.nTime = nTime;
  919. block.nBits = nBits;
  920. block.nNonce = nNonce;
  921. return block;
  922. }
  923. uint256 GetBlockHash() const
  924. {
  925. return *phashBlock;
  926. }
  927. int64 GetBlockTime() const
  928. {
  929. return (int64)nTime;
  930. }
  931. uint256 GetBlockTrust() const;
  932. bool IsInMainChain() const
  933. {
  934. return (pnext || this == pindexBest);
  935. }
  936. bool CheckIndex() const
  937. {
  938. return true;
  939. }
  940. enum { nMedianTimeSpan=11 };
  941. int64 GetMedianTimePast() const
  942. {
  943. int64 pmedian[nMedianTimeSpan];
  944. int64* pbegin = &pmedian[nMedianTimeSpan];
  945. int64* pend = &pmedian[nMedianTimeSpan];
  946. const CBlockIndex* pindex = this;
  947. for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
  948. *(--pbegin) = pindex->GetBlockTime();
  949. std::sort(pbegin, pend);
  950. return pbegin[(pend - pbegin)/2];
  951. }
  952. int64 GetMedianTime() const
  953. {
  954. const CBlockIndex* pindex = this;
  955. for (int i = 0; i < nMedianTimeSpan/2; i++)
  956. {
  957. if (!pindex->pnext)
  958. return GetBlockTime();
  959. pindex = pindex->pnext;
  960. }
  961. return pindex->GetMedianTimePast();
  962. }
  963. static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
  964. unsigned int nRequired, unsigned int nToCheck);
  965. bool IsProofOfWork() const
  966. {
  967. return !(nFlags & BLOCK_PROOF_OF_STAKE);
  968. }
  969. bool IsProofOfStake() const
  970. {
  971. return (nFlags & BLOCK_PROOF_OF_STAKE);
  972. }
  973. void SetProofOfStake()
  974. {
  975. nFlags |= BLOCK_PROOF_OF_STAKE;
  976. }
  977. unsigned int GetStakeEntropyBit() const
  978. {
  979. return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
  980. }
  981. bool SetStakeEntropyBit(unsigned int nEntropyBit)
  982. {
  983. if (nEntropyBit > 1)
  984. return false;
  985. nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
  986. return true;
  987. }
  988. bool GeneratedStakeModifier() const
  989. {
  990. return (nFlags & BLOCK_STAKE_MODIFIER);
  991. }
  992. void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
  993. {
  994. nStakeModifier = nModifier;
  995. if (fGeneratedStakeModifier)
  996. nFlags |= BLOCK_STAKE_MODIFIER;
  997. }
  998. std::string ToString() const
  999. {
  1000. return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016" PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
  1001. pprev, pnext, nFile, nBlockPos, nHeight,
  1002. FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
  1003. GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
  1004. nStakeModifier, nStakeModifierChecksum,
  1005. hashProofOfStake.ToString().c_str(),
  1006. prevoutStake.ToString().c_str(), nStakeTime,
  1007. hashMerkleRoot.ToString().c_str(),
  1008. GetBlockHash().ToString().c_str());
  1009. }
  1010. void print() const
  1011. {
  1012. printf("%s\n", ToString().c_str());
  1013. }
  1014. };
  1015. class CDiskBlockIndex : public CBlockIndex
  1016. {
  1017. private:
  1018. uint256 blockHash;
  1019. public:
  1020. uint256 hashPrev;
  1021. uint256 hashNext;
  1022. CDiskBlockIndex()
  1023. {
  1024. hashPrev = 0;
  1025. hashNext = 0;
  1026. blockHash = 0;
  1027. }
  1028. explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
  1029. {
  1030. hashPrev = (pprev ? pprev->GetBlockHash() : 0);
  1031. hashNext = (pnext ? pnext->GetBlockHash() : 0);
  1032. }
  1033. IMPLEMENT_SERIALIZE
  1034. (
  1035. if (!(nType & SER_GETHASH))
  1036. READWRITE(nVersion);
  1037. READWRITE(hashNext);
  1038. READWRITE(nFile);
  1039. READWRITE(nBlockPos);
  1040. READWRITE(nHeight);
  1041. READWRITE(nMint);
  1042. READWRITE(nMoneySupply);
  1043. READWRITE(nFlags);
  1044. READWRITE(nStakeModifier);
  1045. if (IsProofOfStake())
  1046. {
  1047. READWRITE(prevoutStake);
  1048. READWRITE(nStakeTime);
  1049. READWRITE(hashProofOfStake);
  1050. }
  1051. else if (fRead)
  1052. {
  1053. const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
  1054. const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
  1055. const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
  1056. }
  1057. // block header
  1058. READWRITE(this->nVersion);
  1059. READWRITE(hashPrev);
  1060. READWRITE(hashMerkleRoot);
  1061. READWRITE(nTime);
  1062. READWRITE(nBits);
  1063. READWRITE(nNonce);
  1064. READWRITE(blockHash);
  1065. )
  1066. uint256 GetBlockHash() const
  1067. {
  1068. if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
  1069. return blockHash;
  1070. CBlock block;
  1071. block.nVersion = nVersion;
  1072. block.hashPrevBlock = hashPrev;
  1073. block.hashMerkleRoot = hashMerkleRoot;
  1074. block.nTime = nTime;
  1075. block.nBits = nBits;
  1076. block.nNonce = nNonce;
  1077. const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
  1078. return blockHash;
  1079. }
  1080. std::string ToString() const
  1081. {
  1082. std::string str = "CDiskBlockIndex(";
  1083. str += CBlockIndex::ToString();
  1084. str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
  1085. GetBlockHash().ToString().c_str(),
  1086. hashPrev.ToString().c_str(),
  1087. hashNext.ToString().c_str());
  1088. return str;
  1089. }
  1090. void print() const
  1091. {
  1092. printf("%s\n", ToString().c_str());
  1093. }
  1094. };
  1095. class CBlockLocator
  1096. {
  1097. protected:
  1098. std::vector<uint256> vHave;
  1099. public:
  1100. CBlockLocator()
  1101. {
  1102. }
  1103. explicit CBlockLocator(const CBlockIndex* pindex)
  1104. {
  1105. Set(pindex);
  1106. }
  1107. explicit CBlockLocator(uint256 hashBlock)
  1108. {
  1109. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  1110. if (mi != mapBlockIndex.end())
  1111. Set((*mi).second);
  1112. }
  1113. CBlockLocator(const std::vector<uint256>& vHaveIn)
  1114. {
  1115. vHave = vHaveIn;
  1116. }
  1117. IMPLEMENT_SERIALIZE
  1118. (
  1119. if (!(nType & SER_GETHASH))
  1120. READWRITE(nVersion);
  1121. READWRITE(vHave);
  1122. )
  1123. void SetNull()
  1124. {
  1125. vHave.clear();
  1126. }
  1127. bool IsNull()
  1128. {
  1129. return vHave.empty();
  1130. }
  1131. void Set(const CBlockIndex* pindex)
  1132. {
  1133. vHave.clear();
  1134. int nStep = 1;
  1135. while (pindex)
  1136. {
  1137. vHave.push_back(pindex->GetBlockHash());
  1138. // Exponentially larger steps back
  1139. for (int i = 0; pindex && i < nStep; i++)
  1140. pindex = pindex->pprev;
  1141. if (vHave.size() > 10)
  1142. nStep *= 2;
  1143. }
  1144. vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
  1145. }
  1146. int GetDistanceBack()
  1147. {
  1148. // Retrace how far back it was in the sender's branch
  1149. int nDistance = 0;
  1150. int nStep = 1;
  1151. BOOST_FOREACH(const uint256& hash, vHave)
  1152. {
  1153. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1154. if (mi != mapBlockIndex.end())
  1155. {
  1156. CBlockIndex* pindex = (*mi).second;
  1157. if (pindex->IsInMainChain())
  1158. return nDistance;
  1159. }
  1160. nDistance += nStep;
  1161. if (nDistance > 10)
  1162. nStep *= 2;
  1163. }
  1164. return nDistance;
  1165. }
  1166. CBlockIndex* GetBlockIndex()
  1167. {
  1168. // Find the first block the caller has in the main chain
  1169. BOOST_FOREACH(const uint256& hash, vHave)
  1170. {
  1171. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1172. if (mi != mapBlockIndex.end())
  1173. {
  1174. CBlockIndex* pindex = (*mi).second;
  1175. if (pindex->IsInMainChain())
  1176. return pindex;
  1177. }
  1178. }
  1179. return pindexGenesisBlock;
  1180. }
  1181. uint256 GetBlockHash()
  1182. {
  1183. // Find the first block the caller has in the main chain
  1184. BOOST_FOREACH(const uint256& hash, vHave)
  1185. {
  1186. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1187. if (mi != mapBlockIndex.end())
  1188. {
  1189. CBlockIndex* pindex = (*mi).second;
  1190. if (pindex->IsInMainChain())
  1191. return hash;
  1192. }
  1193. }
  1194. return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
  1195. }
  1196. int GetHeight()
  1197. {
  1198. CBlockIndex* pindex = GetBlockIndex();
  1199. if (!pindex)
  1200. return 0;
  1201. return pindex->nHeight;
  1202. }
  1203. };
  1204. class CTxMemPool
  1205. {
  1206. public:
  1207. mutable CCriticalSection cs;
  1208. std::map<uint256, CTransaction> mapTx;
  1209. std::map<COutPoint, CInPoint> mapNextTx;
  1210. bool accept(CTxDB& txdb, CTransaction &tx,
  1211. bool fCheckInputs, bool* pfMissingInputs);
  1212. bool addUnchecked(const uint256& hash, CTransaction &tx);
  1213. bool remove(CTransaction &tx);
  1214. void clear();
  1215. void queryHashes(std::vector<uint256>& vtxid);
  1216. unsigned long size()
  1217. {
  1218. LOCK(cs);
  1219. return mapTx.size();
  1220. }
  1221. bool exists(uint256 hash)
  1222. {
  1223. return (mapTx.count(hash) != 0);
  1224. }
  1225. CTransaction& lookup(uint256 hash)
  1226. {
  1227. return mapTx[hash];
  1228. }
  1229. };
  1230. extern CTxMemPool mempool;
  1231. #endif