You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.h 42KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2011 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
  5. #ifndef BITCOIN_MAIN_H
  6. #define BITCOIN_MAIN_H
  7. #include "bignum.h"
  8. #include "net.h"
  9. #include "key.h"
  10. #include "script.h"
  11. #include "db.h"
  12. #include <list>
  13. class CBlock;
  14. class CBlockIndex;
  15. class CWalletTx;
  16. class CWallet;
  17. class CKeyItem;
  18. class CReserveKey;
  19. class CWalletDB;
  20. class CAddress;
  21. class CInv;
  22. class CRequestTracker;
  23. class CNode;
  24. static const int CLIENT_VERSION = 59900;
  25. static const bool VERSION_IS_BETA = true;
  26. extern const std::string CLIENT_NAME;
  27. static const unsigned int MAX_BLOCK_SIZE = 1000000;
  28. static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
  29. static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
  30. static const int64 COIN = 100000000;
  31. static const int64 CENT = 1000000;
  32. static const int64 MIN_TX_FEE = 50000;
  33. static const int64 MIN_RELAY_TX_FEE = 10000;
  34. static const int64 MAX_MONEY = 21000000 * COIN;
  35. inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
  36. static const int COINBASE_MATURITY = 100;
  37. // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
  38. static const int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
  39. #ifdef USE_UPNP
  40. static const int fHaveUPnP = true;
  41. #else
  42. static const int fHaveUPnP = false;
  43. #endif
  44. extern CCriticalSection cs_main;
  45. extern std::map<uint256, CBlockIndex*> mapBlockIndex;
  46. extern uint256 hashGenesisBlock;
  47. extern CBlockIndex* pindexGenesisBlock;
  48. extern int nBestHeight;
  49. extern CBigNum bnBestChainWork;
  50. extern CBigNum bnBestInvalidWork;
  51. extern uint256 hashBestChain;
  52. extern CBlockIndex* pindexBest;
  53. extern uint64 nPooledTx;
  54. extern unsigned int nTransactionsUpdated;
  55. extern uint64 nLastBlockTx;
  56. extern uint64 nLastBlockSize;
  57. extern double dHashesPerSec;
  58. extern int64 nHPSTimerStart;
  59. extern int64 nTimeBestReceived;
  60. extern CCriticalSection cs_setpwalletRegistered;
  61. extern std::set<CWallet*> setpwalletRegistered;
  62. // Settings
  63. extern int fGenerateBitcoins;
  64. extern int64 nTransactionFee;
  65. extern int fLimitProcessors;
  66. extern int nLimitProcessors;
  67. extern int fMinimizeToTray;
  68. extern int fMinimizeOnClose;
  69. extern int fUseUPnP;
  70. class CReserveKey;
  71. class CTxDB;
  72. class CTxIndex;
  73. void RegisterWallet(CWallet* pwalletIn);
  74. void UnregisterWallet(CWallet* pwalletIn);
  75. bool ProcessBlock(CNode* pfrom, CBlock* pblock);
  76. bool CheckDiskSpace(uint64 nAdditionalBytes=0);
  77. FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
  78. FILE* AppendBlockFile(unsigned int& nFileRet);
  79. bool LoadBlockIndex(bool fAllowNew=true);
  80. void PrintBlockTree();
  81. bool ProcessMessages(CNode* pfrom);
  82. bool SendMessages(CNode* pto, bool fSendTrickle);
  83. void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
  84. CBlock* CreateNewBlock(CReserveKey& reservekey);
  85. void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
  86. void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
  87. bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
  88. bool CheckProofOfWork(uint256 hash, unsigned int nBits);
  89. unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
  90. int GetNumBlocksOfPeers();
  91. bool IsInitialBlockDownload();
  92. std::string GetWarnings(std::string strFor);
  93. bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
  94. template<typename T>
  95. bool WriteSetting(const std::string& strKey, const T& value)
  96. {
  97. bool fOk = false;
  98. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  99. {
  100. std::string strWalletFile;
  101. if (!GetWalletFile(pwallet, strWalletFile))
  102. continue;
  103. fOk |= CWalletDB(strWalletFile).WriteSetting(strKey, value);
  104. }
  105. return fOk;
  106. }
  107. class CDiskTxPos
  108. {
  109. public:
  110. unsigned int nFile;
  111. unsigned int nBlockPos;
  112. unsigned int nTxPos;
  113. CDiskTxPos()
  114. {
  115. SetNull();
  116. }
  117. CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
  118. {
  119. nFile = nFileIn;
  120. nBlockPos = nBlockPosIn;
  121. nTxPos = nTxPosIn;
  122. }
  123. IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
  124. void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
  125. bool IsNull() const { return (nFile == -1); }
  126. friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
  127. {
  128. return (a.nFile == b.nFile &&
  129. a.nBlockPos == b.nBlockPos &&
  130. a.nTxPos == b.nTxPos);
  131. }
  132. friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
  133. {
  134. return !(a == b);
  135. }
  136. std::string ToString() const
  137. {
  138. if (IsNull())
  139. return strprintf("null");
  140. else
  141. return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
  142. }
  143. void print() const
  144. {
  145. printf("%s", ToString().c_str());
  146. }
  147. };
  148. class CInPoint
  149. {
  150. public:
  151. CTransaction* ptx;
  152. unsigned int n;
  153. CInPoint() { SetNull(); }
  154. CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
  155. void SetNull() { ptx = NULL; n = -1; }
  156. bool IsNull() const { return (ptx == NULL && n == -1); }
  157. };
  158. class COutPoint
  159. {
  160. public:
  161. uint256 hash;
  162. unsigned int n;
  163. COutPoint() { SetNull(); }
  164. COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
  165. IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
  166. void SetNull() { hash = 0; n = -1; }
  167. bool IsNull() const { return (hash == 0 && n == -1); }
  168. friend bool operator<(const COutPoint& a, const COutPoint& b)
  169. {
  170. return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
  171. }
  172. friend bool operator==(const COutPoint& a, const COutPoint& b)
  173. {
  174. return (a.hash == b.hash && a.n == b.n);
  175. }
  176. friend bool operator!=(const COutPoint& a, const COutPoint& b)
  177. {
  178. return !(a == b);
  179. }
  180. std::string ToString() const
  181. {
  182. return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
  183. }
  184. void print() const
  185. {
  186. printf("%s\n", ToString().c_str());
  187. }
  188. };
  189. //
  190. // An input of a transaction. It contains the location of the previous
  191. // transaction's output that it claims and a signature that matches the
  192. // output's public key.
  193. //
  194. class CTxIn
  195. {
  196. public:
  197. COutPoint prevout;
  198. CScript scriptSig;
  199. unsigned int nSequence;
  200. CTxIn()
  201. {
  202. nSequence = std::numeric_limits<unsigned int>::max();
  203. }
  204. explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
  205. {
  206. prevout = prevoutIn;
  207. scriptSig = scriptSigIn;
  208. nSequence = nSequenceIn;
  209. }
  210. CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
  211. {
  212. prevout = COutPoint(hashPrevTx, nOut);
  213. scriptSig = scriptSigIn;
  214. nSequence = nSequenceIn;
  215. }
  216. IMPLEMENT_SERIALIZE
  217. (
  218. READWRITE(prevout);
  219. READWRITE(scriptSig);
  220. READWRITE(nSequence);
  221. )
  222. bool IsFinal() const
  223. {
  224. return (nSequence == std::numeric_limits<unsigned int>::max());
  225. }
  226. friend bool operator==(const CTxIn& a, const CTxIn& b)
  227. {
  228. return (a.prevout == b.prevout &&
  229. a.scriptSig == b.scriptSig &&
  230. a.nSequence == b.nSequence);
  231. }
  232. friend bool operator!=(const CTxIn& a, const CTxIn& b)
  233. {
  234. return !(a == b);
  235. }
  236. std::string ToString() const
  237. {
  238. std::string str;
  239. str += strprintf("CTxIn(");
  240. str += prevout.ToString();
  241. if (prevout.IsNull())
  242. str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
  243. else
  244. str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
  245. if (nSequence != std::numeric_limits<unsigned int>::max())
  246. str += strprintf(", nSequence=%u", nSequence);
  247. str += ")";
  248. return str;
  249. }
  250. void print() const
  251. {
  252. printf("%s\n", ToString().c_str());
  253. }
  254. };
  255. //
  256. // An output of a transaction. It contains the public key that the next input
  257. // must be able to sign with to claim it.
  258. //
  259. class CTxOut
  260. {
  261. public:
  262. int64 nValue;
  263. CScript scriptPubKey;
  264. CTxOut()
  265. {
  266. SetNull();
  267. }
  268. CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
  269. {
  270. nValue = nValueIn;
  271. scriptPubKey = scriptPubKeyIn;
  272. }
  273. IMPLEMENT_SERIALIZE
  274. (
  275. READWRITE(nValue);
  276. READWRITE(scriptPubKey);
  277. )
  278. void SetNull()
  279. {
  280. nValue = -1;
  281. scriptPubKey.clear();
  282. }
  283. bool IsNull()
  284. {
  285. return (nValue == -1);
  286. }
  287. uint256 GetHash() const
  288. {
  289. return SerializeHash(*this);
  290. }
  291. friend bool operator==(const CTxOut& a, const CTxOut& b)
  292. {
  293. return (a.nValue == b.nValue &&
  294. a.scriptPubKey == b.scriptPubKey);
  295. }
  296. friend bool operator!=(const CTxOut& a, const CTxOut& b)
  297. {
  298. return !(a == b);
  299. }
  300. std::string ToString() const
  301. {
  302. if (scriptPubKey.size() < 6)
  303. return "CTxOut(error)";
  304. return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
  305. }
  306. void print() const
  307. {
  308. printf("%s\n", ToString().c_str());
  309. }
  310. };
  311. enum GetMinFee_mode
  312. {
  313. GMF_BLOCK,
  314. GMF_RELAY,
  315. GMF_SEND,
  316. };
  317. typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
  318. //
  319. // The basic transaction that is broadcasted on the network and contained in
  320. // blocks. A transaction can contain multiple inputs and outputs.
  321. //
  322. class CTransaction
  323. {
  324. public:
  325. int nVersion;
  326. std::vector<CTxIn> vin;
  327. std::vector<CTxOut> vout;
  328. unsigned int nLockTime;
  329. // Denial-of-service detection:
  330. mutable int nDoS;
  331. bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
  332. CTransaction()
  333. {
  334. SetNull();
  335. }
  336. IMPLEMENT_SERIALIZE
  337. (
  338. READWRITE(this->nVersion);
  339. nVersion = this->nVersion;
  340. READWRITE(vin);
  341. READWRITE(vout);
  342. READWRITE(nLockTime);
  343. )
  344. void SetNull()
  345. {
  346. nVersion = 1;
  347. vin.clear();
  348. vout.clear();
  349. nLockTime = 0;
  350. nDoS = 0; // Denial-of-service prevention
  351. }
  352. bool IsNull() const
  353. {
  354. return (vin.empty() && vout.empty());
  355. }
  356. uint256 GetHash() const
  357. {
  358. return SerializeHash(*this);
  359. }
  360. bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
  361. {
  362. // Time based nLockTime implemented in 0.1.6
  363. if (nLockTime == 0)
  364. return true;
  365. if (nBlockHeight == 0)
  366. nBlockHeight = nBestHeight;
  367. if (nBlockTime == 0)
  368. nBlockTime = GetAdjustedTime();
  369. if ((int64)nLockTime < (nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
  370. return true;
  371. BOOST_FOREACH(const CTxIn& txin, vin)
  372. if (!txin.IsFinal())
  373. return false;
  374. return true;
  375. }
  376. bool IsNewerThan(const CTransaction& old) const
  377. {
  378. if (vin.size() != old.vin.size())
  379. return false;
  380. for (int i = 0; i < vin.size(); i++)
  381. if (vin[i].prevout != old.vin[i].prevout)
  382. return false;
  383. bool fNewer = false;
  384. unsigned int nLowest = std::numeric_limits<unsigned int>::max();
  385. for (int i = 0; i < vin.size(); i++)
  386. {
  387. if (vin[i].nSequence != old.vin[i].nSequence)
  388. {
  389. if (vin[i].nSequence <= nLowest)
  390. {
  391. fNewer = false;
  392. nLowest = vin[i].nSequence;
  393. }
  394. if (old.vin[i].nSequence < nLowest)
  395. {
  396. fNewer = true;
  397. nLowest = old.vin[i].nSequence;
  398. }
  399. }
  400. }
  401. return fNewer;
  402. }
  403. bool IsCoinBase() const
  404. {
  405. return (vin.size() == 1 && vin[0].prevout.IsNull());
  406. }
  407. /** Check for standard transaction types
  408. @return True if all outputs (scriptPubKeys) use only standard transaction forms
  409. */
  410. bool IsStandard() const;
  411. /** Check for standard transaction types
  412. @param[in] mapInputs Map of previous transactions that have outputs we're spending
  413. @return True if all inputs (scriptSigs) use only standard transaction forms
  414. @see CTransaction::FetchInputs
  415. */
  416. bool AreInputsStandard(const MapPrevTx& mapInputs) const;
  417. /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
  418. @return number of sigops this transaction's outputs will produce when spent
  419. @see CTransaction::FetchInputs
  420. */
  421. int GetLegacySigOpCount() const;
  422. /** Count ECDSA signature operations the new (0.6-and-later) way
  423. This is a better measure of how expensive it is to process this transaction.
  424. @param[in] mapInputs Map of previous transactions that have outputs we're spending
  425. @return maximum number of sigops required to validate this transaction's inputs
  426. @see CTransaction::FetchInputs
  427. */
  428. int GetSigOpCount(const MapPrevTx& mapInputs) const;
  429. /** Amount of bitcoins spent by this transaction.
  430. @return sum of all outputs (note: does not include fees)
  431. */
  432. int64 GetValueOut() const
  433. {
  434. int64 nValueOut = 0;
  435. BOOST_FOREACH(const CTxOut& txout, vout)
  436. {
  437. nValueOut += txout.nValue;
  438. if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
  439. throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
  440. }
  441. return nValueOut;
  442. }
  443. /** Amount of bitcoins coming in to this transaction
  444. Note that lightweight clients may not know anything besides the hash of previous transactions,
  445. so may not be able to calculate this.
  446. @param[in] mapInputs Map of previous transactions that have outputs we're spending
  447. @return Sum of value of all inputs (scriptSigs)
  448. @see CTransaction::FetchInputs
  449. */
  450. int64 GetValueIn(const MapPrevTx& mapInputs) const;
  451. static bool AllowFree(double dPriority)
  452. {
  453. // Large (in bytes) low-priority (new, small-coin) transactions
  454. // need a fee.
  455. return dPriority > COIN * 144 / 250;
  456. }
  457. int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const
  458. {
  459. // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
  460. int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
  461. unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
  462. unsigned int nNewBlockSize = nBlockSize + nBytes;
  463. int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
  464. if (fAllowFree)
  465. {
  466. if (nBlockSize == 1)
  467. {
  468. // Transactions under 10K are free
  469. // (about 4500bc if made of 50bc inputs)
  470. if (nBytes < 10000)
  471. nMinFee = 0;
  472. }
  473. else
  474. {
  475. // Free transaction area
  476. if (nNewBlockSize < 27000)
  477. nMinFee = 0;
  478. }
  479. }
  480. // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
  481. if (nMinFee < nBaseFee)
  482. BOOST_FOREACH(const CTxOut& txout, vout)
  483. if (txout.nValue < CENT)
  484. nMinFee = nBaseFee;
  485. // Raise the price as the block approaches full
  486. if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
  487. {
  488. if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
  489. return MAX_MONEY;
  490. nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
  491. }
  492. if (!MoneyRange(nMinFee))
  493. nMinFee = MAX_MONEY;
  494. return nMinFee;
  495. }
  496. bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
  497. {
  498. CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
  499. if (!filein)
  500. return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
  501. // Read transaction
  502. if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
  503. return error("CTransaction::ReadFromDisk() : fseek failed");
  504. filein >> *this;
  505. // Return file pointer
  506. if (pfileRet)
  507. {
  508. if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
  509. return error("CTransaction::ReadFromDisk() : second fseek failed");
  510. *pfileRet = filein.release();
  511. }
  512. return true;
  513. }
  514. friend bool operator==(const CTransaction& a, const CTransaction& b)
  515. {
  516. return (a.nVersion == b.nVersion &&
  517. a.vin == b.vin &&
  518. a.vout == b.vout &&
  519. a.nLockTime == b.nLockTime);
  520. }
  521. friend bool operator!=(const CTransaction& a, const CTransaction& b)
  522. {
  523. return !(a == b);
  524. }
  525. std::string ToString() const
  526. {
  527. std::string str;
  528. str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
  529. GetHash().ToString().substr(0,10).c_str(),
  530. nVersion,
  531. vin.size(),
  532. vout.size(),
  533. nLockTime);
  534. for (int i = 0; i < vin.size(); i++)
  535. str += " " + vin[i].ToString() + "\n";
  536. for (int i = 0; i < vout.size(); i++)
  537. str += " " + vout[i].ToString() + "\n";
  538. return str;
  539. }
  540. void print() const
  541. {
  542. printf("%s", ToString().c_str());
  543. }
  544. bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
  545. bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
  546. bool ReadFromDisk(COutPoint prevout);
  547. bool DisconnectInputs(CTxDB& txdb);
  548. /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
  549. @param[in] txdb Transaction database
  550. @param[in] mapTestPool List of pending changes to the transaction index database
  551. @param[in] fBlock True if being called to add a new best-block to the chain
  552. @param[in] fMiner True if being called by CreateNewBlock
  553. @param[out] inputsRet Pointers to this transaction's inputs
  554. @return Returns true if all inputs are in txdb or mapTestPool
  555. */
  556. bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
  557. bool fBlock, bool fMiner, MapPrevTx& inputsRet);
  558. /** Sanity check previous transactions, then, if all checks succeed,
  559. mark them as spent by this transaction.
  560. @param[in] inputs Previous transactions (from FetchInputs)
  561. @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
  562. @param[in] posThisTx Position of this transaction on disk
  563. @param[in] pindexBlock
  564. @param[in] fBlock true if called from ConnectBlock
  565. @param[in] fMiner true if called from CreateNewBlock
  566. @return Returns true if all checks succeed
  567. */
  568. bool ConnectInputs(MapPrevTx inputs,
  569. std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
  570. const CBlockIndex* pindexBlock, bool fBlock, bool fMiner);
  571. bool ClientConnectInputs();
  572. bool CheckTransaction() const;
  573. bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
  574. bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL);
  575. protected:
  576. const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
  577. bool AddToMemoryPoolUnchecked();
  578. public:
  579. bool RemoveFromMemoryPool();
  580. };
  581. //
  582. // A transaction with a merkle branch linking it to the block chain
  583. //
  584. class CMerkleTx : public CTransaction
  585. {
  586. public:
  587. uint256 hashBlock;
  588. std::vector<uint256> vMerkleBranch;
  589. int nIndex;
  590. // memory only
  591. mutable char fMerkleVerified;
  592. CMerkleTx()
  593. {
  594. Init();
  595. }
  596. CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
  597. {
  598. Init();
  599. }
  600. void Init()
  601. {
  602. hashBlock = 0;
  603. nIndex = -1;
  604. fMerkleVerified = false;
  605. }
  606. IMPLEMENT_SERIALIZE
  607. (
  608. nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
  609. nVersion = this->nVersion;
  610. READWRITE(hashBlock);
  611. READWRITE(vMerkleBranch);
  612. READWRITE(nIndex);
  613. )
  614. int SetMerkleBranch(const CBlock* pblock=NULL);
  615. int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
  616. int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
  617. bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
  618. int GetBlocksToMaturity() const;
  619. bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
  620. bool AcceptToMemoryPool();
  621. };
  622. //
  623. // A txdb record that contains the disk location of a transaction and the
  624. // locations of transactions that spend its outputs. vSpent is really only
  625. // used as a flag, but having the location is very helpful for debugging.
  626. //
  627. class CTxIndex
  628. {
  629. public:
  630. CDiskTxPos pos;
  631. std::vector<CDiskTxPos> vSpent;
  632. CTxIndex()
  633. {
  634. SetNull();
  635. }
  636. CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
  637. {
  638. pos = posIn;
  639. vSpent.resize(nOutputs);
  640. }
  641. IMPLEMENT_SERIALIZE
  642. (
  643. if (!(nType & SER_GETHASH))
  644. READWRITE(nVersion);
  645. READWRITE(pos);
  646. READWRITE(vSpent);
  647. )
  648. void SetNull()
  649. {
  650. pos.SetNull();
  651. vSpent.clear();
  652. }
  653. bool IsNull()
  654. {
  655. return pos.IsNull();
  656. }
  657. friend bool operator==(const CTxIndex& a, const CTxIndex& b)
  658. {
  659. return (a.pos == b.pos &&
  660. a.vSpent == b.vSpent);
  661. }
  662. friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
  663. {
  664. return !(a == b);
  665. }
  666. int GetDepthInMainChain() const;
  667. };
  668. //
  669. // Nodes collect new transactions into a block, hash them into a hash tree,
  670. // and scan through nonce values to make the block's hash satisfy proof-of-work
  671. // requirements. When they solve the proof-of-work, they broadcast the block
  672. // to everyone and the block is added to the block chain. The first transaction
  673. // in the block is a special one that creates a new coin owned by the creator
  674. // of the block.
  675. //
  676. // Blocks are appended to blk0001.dat files on disk. Their location on disk
  677. // is indexed by CBlockIndex objects in memory.
  678. //
  679. class CBlock
  680. {
  681. public:
  682. // header
  683. int nVersion;
  684. uint256 hashPrevBlock;
  685. uint256 hashMerkleRoot;
  686. unsigned int nTime;
  687. unsigned int nBits;
  688. unsigned int nNonce;
  689. // network and disk
  690. std::vector<CTransaction> vtx;
  691. // memory only
  692. mutable std::vector<uint256> vMerkleTree;
  693. // Denial-of-service detection:
  694. mutable int nDoS;
  695. bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
  696. CBlock()
  697. {
  698. SetNull();
  699. }
  700. IMPLEMENT_SERIALIZE
  701. (
  702. READWRITE(this->nVersion);
  703. nVersion = this->nVersion;
  704. READWRITE(hashPrevBlock);
  705. READWRITE(hashMerkleRoot);
  706. READWRITE(nTime);
  707. READWRITE(nBits);
  708. READWRITE(nNonce);
  709. // ConnectBlock depends on vtx being last so it can calculate offset
  710. if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
  711. READWRITE(vtx);
  712. else if (fRead)
  713. const_cast<CBlock*>(this)->vtx.clear();
  714. )
  715. void SetNull()
  716. {
  717. nVersion = 1;
  718. hashPrevBlock = 0;
  719. hashMerkleRoot = 0;
  720. nTime = 0;
  721. nBits = 0;
  722. nNonce = 0;
  723. vtx.clear();
  724. vMerkleTree.clear();
  725. nDoS = 0;
  726. }
  727. bool IsNull() const
  728. {
  729. return (nBits == 0);
  730. }
  731. uint256 GetHash() const
  732. {
  733. return Hash(BEGIN(nVersion), END(nNonce));
  734. }
  735. int64 GetBlockTime() const
  736. {
  737. return (int64)nTime;
  738. }
  739. uint256 BuildMerkleTree() const
  740. {
  741. vMerkleTree.clear();
  742. BOOST_FOREACH(const CTransaction& tx, vtx)
  743. vMerkleTree.push_back(tx.GetHash());
  744. int j = 0;
  745. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  746. {
  747. for (int i = 0; i < nSize; i += 2)
  748. {
  749. int i2 = std::min(i+1, nSize-1);
  750. vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
  751. BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
  752. }
  753. j += nSize;
  754. }
  755. return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
  756. }
  757. std::vector<uint256> GetMerkleBranch(int nIndex) const
  758. {
  759. if (vMerkleTree.empty())
  760. BuildMerkleTree();
  761. std::vector<uint256> vMerkleBranch;
  762. int j = 0;
  763. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  764. {
  765. int i = std::min(nIndex^1, nSize-1);
  766. vMerkleBranch.push_back(vMerkleTree[j+i]);
  767. nIndex >>= 1;
  768. j += nSize;
  769. }
  770. return vMerkleBranch;
  771. }
  772. static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
  773. {
  774. if (nIndex == -1)
  775. return 0;
  776. BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
  777. {
  778. if (nIndex & 1)
  779. hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
  780. else
  781. hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
  782. nIndex >>= 1;
  783. }
  784. return hash;
  785. }
  786. bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
  787. {
  788. // Open history file to append
  789. CAutoFile fileout = AppendBlockFile(nFileRet);
  790. if (!fileout)
  791. return error("CBlock::WriteToDisk() : AppendBlockFile failed");
  792. // Write index header
  793. unsigned int nSize = fileout.GetSerializeSize(*this);
  794. fileout << FLATDATA(pchMessageStart) << nSize;
  795. // Write block
  796. nBlockPosRet = ftell(fileout);
  797. if (nBlockPosRet == -1)
  798. return error("CBlock::WriteToDisk() : ftell failed");
  799. fileout << *this;
  800. // Flush stdio buffers and commit to disk before returning
  801. fflush(fileout);
  802. if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
  803. {
  804. #ifdef WIN32
  805. _commit(_fileno(fileout));
  806. #else
  807. fsync(fileno(fileout));
  808. #endif
  809. }
  810. return true;
  811. }
  812. bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
  813. {
  814. SetNull();
  815. // Open history file to read
  816. CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
  817. if (!filein)
  818. return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
  819. if (!fReadTransactions)
  820. filein.nType |= SER_BLOCKHEADERONLY;
  821. // Read block
  822. filein >> *this;
  823. // Check the header
  824. if (!CheckProofOfWork(GetHash(), nBits))
  825. return error("CBlock::ReadFromDisk() : errors in block header");
  826. return true;
  827. }
  828. void print() const
  829. {
  830. printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
  831. GetHash().ToString().substr(0,20).c_str(),
  832. nVersion,
  833. hashPrevBlock.ToString().substr(0,20).c_str(),
  834. hashMerkleRoot.ToString().substr(0,10).c_str(),
  835. nTime, nBits, nNonce,
  836. vtx.size());
  837. for (int i = 0; i < vtx.size(); i++)
  838. {
  839. printf(" ");
  840. vtx[i].print();
  841. }
  842. printf(" vMerkleTree: ");
  843. for (int i = 0; i < vMerkleTree.size(); i++)
  844. printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
  845. printf("\n");
  846. }
  847. bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
  848. bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
  849. bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
  850. bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
  851. bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
  852. bool CheckBlock() const;
  853. bool AcceptBlock();
  854. };
  855. //
  856. // The block chain is a tree shaped structure starting with the
  857. // genesis block at the root, with each block potentially having multiple
  858. // candidates to be the next block. pprev and pnext link a path through the
  859. // main/longest chain. A blockindex may have multiple pprev pointing back
  860. // to it, but pnext will only point forward to the longest branch, or will
  861. // be null if the block is not part of the longest chain.
  862. //
  863. class CBlockIndex
  864. {
  865. public:
  866. const uint256* phashBlock;
  867. CBlockIndex* pprev;
  868. CBlockIndex* pnext;
  869. unsigned int nFile;
  870. unsigned int nBlockPos;
  871. int nHeight;
  872. CBigNum bnChainWork;
  873. // block header
  874. int nVersion;
  875. uint256 hashMerkleRoot;
  876. unsigned int nTime;
  877. unsigned int nBits;
  878. unsigned int nNonce;
  879. CBlockIndex()
  880. {
  881. phashBlock = NULL;
  882. pprev = NULL;
  883. pnext = NULL;
  884. nFile = 0;
  885. nBlockPos = 0;
  886. nHeight = 0;
  887. bnChainWork = 0;
  888. nVersion = 0;
  889. hashMerkleRoot = 0;
  890. nTime = 0;
  891. nBits = 0;
  892. nNonce = 0;
  893. }
  894. CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
  895. {
  896. phashBlock = NULL;
  897. pprev = NULL;
  898. pnext = NULL;
  899. nFile = nFileIn;
  900. nBlockPos = nBlockPosIn;
  901. nHeight = 0;
  902. bnChainWork = 0;
  903. nVersion = block.nVersion;
  904. hashMerkleRoot = block.hashMerkleRoot;
  905. nTime = block.nTime;
  906. nBits = block.nBits;
  907. nNonce = block.nNonce;
  908. }
  909. CBlock GetBlockHeader() const
  910. {
  911. CBlock block;
  912. block.nVersion = nVersion;
  913. if (pprev)
  914. block.hashPrevBlock = pprev->GetBlockHash();
  915. block.hashMerkleRoot = hashMerkleRoot;
  916. block.nTime = nTime;
  917. block.nBits = nBits;
  918. block.nNonce = nNonce;
  919. return block;
  920. }
  921. uint256 GetBlockHash() const
  922. {
  923. return *phashBlock;
  924. }
  925. int64 GetBlockTime() const
  926. {
  927. return (int64)nTime;
  928. }
  929. CBigNum GetBlockWork() const
  930. {
  931. CBigNum bnTarget;
  932. bnTarget.SetCompact(nBits);
  933. if (bnTarget <= 0)
  934. return 0;
  935. return (CBigNum(1)<<256) / (bnTarget+1);
  936. }
  937. bool IsInMainChain() const
  938. {
  939. return (pnext || this == pindexBest);
  940. }
  941. bool CheckIndex() const
  942. {
  943. return CheckProofOfWork(GetBlockHash(), nBits);
  944. }
  945. bool EraseBlockFromDisk()
  946. {
  947. // Open history file
  948. CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
  949. if (!fileout)
  950. return false;
  951. // Overwrite with empty null block
  952. CBlock block;
  953. block.SetNull();
  954. fileout << block;
  955. return true;
  956. }
  957. enum { nMedianTimeSpan=11 };
  958. int64 GetMedianTimePast() const
  959. {
  960. int64 pmedian[nMedianTimeSpan];
  961. int64* pbegin = &pmedian[nMedianTimeSpan];
  962. int64* pend = &pmedian[nMedianTimeSpan];
  963. const CBlockIndex* pindex = this;
  964. for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
  965. *(--pbegin) = pindex->GetBlockTime();
  966. std::sort(pbegin, pend);
  967. return pbegin[(pend - pbegin)/2];
  968. }
  969. int64 GetMedianTime() const
  970. {
  971. const CBlockIndex* pindex = this;
  972. for (int i = 0; i < nMedianTimeSpan/2; i++)
  973. {
  974. if (!pindex->pnext)
  975. return GetBlockTime();
  976. pindex = pindex->pnext;
  977. }
  978. return pindex->GetMedianTimePast();
  979. }
  980. std::string ToString() const
  981. {
  982. return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
  983. pprev, pnext, nFile, nBlockPos, nHeight,
  984. hashMerkleRoot.ToString().substr(0,10).c_str(),
  985. GetBlockHash().ToString().substr(0,20).c_str());
  986. }
  987. void print() const
  988. {
  989. printf("%s\n", ToString().c_str());
  990. }
  991. };
  992. //
  993. // Used to marshal pointers into hashes for db storage.
  994. //
  995. class CDiskBlockIndex : public CBlockIndex
  996. {
  997. public:
  998. uint256 hashPrev;
  999. uint256 hashNext;
  1000. CDiskBlockIndex()
  1001. {
  1002. hashPrev = 0;
  1003. hashNext = 0;
  1004. }
  1005. explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
  1006. {
  1007. hashPrev = (pprev ? pprev->GetBlockHash() : 0);
  1008. hashNext = (pnext ? pnext->GetBlockHash() : 0);
  1009. }
  1010. IMPLEMENT_SERIALIZE
  1011. (
  1012. if (!(nType & SER_GETHASH))
  1013. READWRITE(nVersion);
  1014. READWRITE(hashNext);
  1015. READWRITE(nFile);
  1016. READWRITE(nBlockPos);
  1017. READWRITE(nHeight);
  1018. // block header
  1019. READWRITE(this->nVersion);
  1020. READWRITE(hashPrev);
  1021. READWRITE(hashMerkleRoot);
  1022. READWRITE(nTime);
  1023. READWRITE(nBits);
  1024. READWRITE(nNonce);
  1025. )
  1026. uint256 GetBlockHash() const
  1027. {
  1028. CBlock block;
  1029. block.nVersion = nVersion;
  1030. block.hashPrevBlock = hashPrev;
  1031. block.hashMerkleRoot = hashMerkleRoot;
  1032. block.nTime = nTime;
  1033. block.nBits = nBits;
  1034. block.nNonce = nNonce;
  1035. return block.GetHash();
  1036. }
  1037. std::string ToString() const
  1038. {
  1039. std::string str = "CDiskBlockIndex(";
  1040. str += CBlockIndex::ToString();
  1041. str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
  1042. GetBlockHash().ToString().c_str(),
  1043. hashPrev.ToString().substr(0,20).c_str(),
  1044. hashNext.ToString().substr(0,20).c_str());
  1045. return str;
  1046. }
  1047. void print() const
  1048. {
  1049. printf("%s\n", ToString().c_str());
  1050. }
  1051. };
  1052. //
  1053. // Describes a place in the block chain to another node such that if the
  1054. // other node doesn't have the same branch, it can find a recent common trunk.
  1055. // The further back it is, the further before the fork it may be.
  1056. //
  1057. class CBlockLocator
  1058. {
  1059. protected:
  1060. std::vector<uint256> vHave;
  1061. public:
  1062. CBlockLocator()
  1063. {
  1064. }
  1065. explicit CBlockLocator(const CBlockIndex* pindex)
  1066. {
  1067. Set(pindex);
  1068. }
  1069. explicit CBlockLocator(uint256 hashBlock)
  1070. {
  1071. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  1072. if (mi != mapBlockIndex.end())
  1073. Set((*mi).second);
  1074. }
  1075. CBlockLocator(const std::vector<uint256>& vHaveIn)
  1076. {
  1077. vHave = vHaveIn;
  1078. }
  1079. IMPLEMENT_SERIALIZE
  1080. (
  1081. if (!(nType & SER_GETHASH))
  1082. READWRITE(nVersion);
  1083. READWRITE(vHave);
  1084. )
  1085. void SetNull()
  1086. {
  1087. vHave.clear();
  1088. }
  1089. bool IsNull()
  1090. {
  1091. return vHave.empty();
  1092. }
  1093. void Set(const CBlockIndex* pindex)
  1094. {
  1095. vHave.clear();
  1096. int nStep = 1;
  1097. while (pindex)
  1098. {
  1099. vHave.push_back(pindex->GetBlockHash());
  1100. // Exponentially larger steps back
  1101. for (int i = 0; pindex && i < nStep; i++)
  1102. pindex = pindex->pprev;
  1103. if (vHave.size() > 10)
  1104. nStep *= 2;
  1105. }
  1106. vHave.push_back(hashGenesisBlock);
  1107. }
  1108. int GetDistanceBack()
  1109. {
  1110. // Retrace how far back it was in the sender's branch
  1111. int nDistance = 0;
  1112. int nStep = 1;
  1113. BOOST_FOREACH(const uint256& hash, vHave)
  1114. {
  1115. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1116. if (mi != mapBlockIndex.end())
  1117. {
  1118. CBlockIndex* pindex = (*mi).second;
  1119. if (pindex->IsInMainChain())
  1120. return nDistance;
  1121. }
  1122. nDistance += nStep;
  1123. if (nDistance > 10)
  1124. nStep *= 2;
  1125. }
  1126. return nDistance;
  1127. }
  1128. CBlockIndex* GetBlockIndex()
  1129. {
  1130. // Find the first block the caller has in the main chain
  1131. BOOST_FOREACH(const uint256& hash, vHave)
  1132. {
  1133. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1134. if (mi != mapBlockIndex.end())
  1135. {
  1136. CBlockIndex* pindex = (*mi).second;
  1137. if (pindex->IsInMainChain())
  1138. return pindex;
  1139. }
  1140. }
  1141. return pindexGenesisBlock;
  1142. }
  1143. uint256 GetBlockHash()
  1144. {
  1145. // Find the first block the caller has in the main chain
  1146. BOOST_FOREACH(const uint256& hash, vHave)
  1147. {
  1148. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1149. if (mi != mapBlockIndex.end())
  1150. {
  1151. CBlockIndex* pindex = (*mi).second;
  1152. if (pindex->IsInMainChain())
  1153. return hash;
  1154. }
  1155. }
  1156. return hashGenesisBlock;
  1157. }
  1158. int GetHeight()
  1159. {
  1160. CBlockIndex* pindex = GetBlockIndex();
  1161. if (!pindex)
  1162. return 0;
  1163. return pindex->nHeight;
  1164. }
  1165. };
  1166. //
  1167. // Alerts are for notifying old versions if they become too obsolete and
  1168. // need to upgrade. The message is displayed in the status bar.
  1169. // Alert messages are broadcast as a vector of signed data. Unserializing may
  1170. // not read the entire buffer if the alert is for a newer version, but older
  1171. // versions can still relay the original data.
  1172. //
  1173. class CUnsignedAlert
  1174. {
  1175. public:
  1176. int nVersion;
  1177. int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
  1178. int64 nExpiration;
  1179. int nID;
  1180. int nCancel;
  1181. std::set<int> setCancel;
  1182. int nMinVer; // lowest version inclusive
  1183. int nMaxVer; // highest version inclusive
  1184. std::set<std::string> setSubVer; // empty matches all
  1185. int nPriority;
  1186. // Actions
  1187. std::string strComment;
  1188. std::string strStatusBar;
  1189. std::string strReserved;
  1190. IMPLEMENT_SERIALIZE
  1191. (
  1192. READWRITE(this->nVersion);
  1193. nVersion = this->nVersion;
  1194. READWRITE(nRelayUntil);
  1195. READWRITE(nExpiration);
  1196. READWRITE(nID);
  1197. READWRITE(nCancel);
  1198. READWRITE(setCancel);
  1199. READWRITE(nMinVer);
  1200. READWRITE(nMaxVer);
  1201. READWRITE(setSubVer);
  1202. READWRITE(nPriority);
  1203. READWRITE(strComment);
  1204. READWRITE(strStatusBar);
  1205. READWRITE(strReserved);
  1206. )
  1207. void SetNull()
  1208. {
  1209. nVersion = 1;
  1210. nRelayUntil = 0;
  1211. nExpiration = 0;
  1212. nID = 0;
  1213. nCancel = 0;
  1214. setCancel.clear();
  1215. nMinVer = 0;
  1216. nMaxVer = 0;
  1217. setSubVer.clear();
  1218. nPriority = 0;
  1219. strComment.clear();
  1220. strStatusBar.clear();
  1221. strReserved.clear();
  1222. }
  1223. std::string ToString() const
  1224. {
  1225. std::string strSetCancel;
  1226. BOOST_FOREACH(int n, setCancel)
  1227. strSetCancel += strprintf("%d ", n);
  1228. std::string strSetSubVer;
  1229. BOOST_FOREACH(std::string str, setSubVer)
  1230. strSetSubVer += "\"" + str + "\" ";
  1231. return strprintf(
  1232. "CAlert(\n"
  1233. " nVersion = %d\n"
  1234. " nRelayUntil = %"PRI64d"\n"
  1235. " nExpiration = %"PRI64d"\n"
  1236. " nID = %d\n"
  1237. " nCancel = %d\n"
  1238. " setCancel = %s\n"
  1239. " nMinVer = %d\n"
  1240. " nMaxVer = %d\n"
  1241. " setSubVer = %s\n"
  1242. " nPriority = %d\n"
  1243. " strComment = \"%s\"\n"
  1244. " strStatusBar = \"%s\"\n"
  1245. ")\n",
  1246. nVersion,
  1247. nRelayUntil,
  1248. nExpiration,
  1249. nID,
  1250. nCancel,
  1251. strSetCancel.c_str(),
  1252. nMinVer,
  1253. nMaxVer,
  1254. strSetSubVer.c_str(),
  1255. nPriority,
  1256. strComment.c_str(),
  1257. strStatusBar.c_str());
  1258. }
  1259. void print() const
  1260. {
  1261. printf("%s", ToString().c_str());
  1262. }
  1263. };
  1264. class CAlert : public CUnsignedAlert
  1265. {
  1266. public:
  1267. std::vector<unsigned char> vchMsg;
  1268. std::vector<unsigned char> vchSig;
  1269. CAlert()
  1270. {
  1271. SetNull();
  1272. }
  1273. IMPLEMENT_SERIALIZE
  1274. (
  1275. READWRITE(vchMsg);
  1276. READWRITE(vchSig);
  1277. )
  1278. void SetNull()
  1279. {
  1280. CUnsignedAlert::SetNull();
  1281. vchMsg.clear();
  1282. vchSig.clear();
  1283. }
  1284. bool IsNull() const
  1285. {
  1286. return (nExpiration == 0);
  1287. }
  1288. uint256 GetHash() const
  1289. {
  1290. return SerializeHash(*this);
  1291. }
  1292. bool IsInEffect() const
  1293. {
  1294. return (GetAdjustedTime() < nExpiration);
  1295. }
  1296. bool Cancels(const CAlert& alert) const
  1297. {
  1298. if (!IsInEffect())
  1299. return false; // this was a no-op before 31403
  1300. return (alert.nID <= nCancel || setCancel.count(alert.nID));
  1301. }
  1302. bool AppliesTo(int nVersion, std::string strSubVerIn) const
  1303. {
  1304. // TODO: rework for client-version-embedded-in-strSubVer ?
  1305. return (IsInEffect() &&
  1306. nMinVer <= nVersion && nVersion <= nMaxVer &&
  1307. (setSubVer.empty() || setSubVer.count(strSubVerIn)));
  1308. }
  1309. bool AppliesToMe() const
  1310. {
  1311. return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
  1312. }
  1313. bool RelayTo(CNode* pnode) const
  1314. {
  1315. if (!IsInEffect())
  1316. return false;
  1317. // returns true if wasn't already contained in the set
  1318. if (pnode->setKnown.insert(GetHash()).second)
  1319. {
  1320. if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
  1321. AppliesToMe() ||
  1322. GetAdjustedTime() < nRelayUntil)
  1323. {
  1324. pnode->PushMessage("alert", *this);
  1325. return true;
  1326. }
  1327. }
  1328. return false;
  1329. }
  1330. bool CheckSignature()
  1331. {
  1332. CKey key;
  1333. if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
  1334. return error("CAlert::CheckSignature() : SetPubKey failed");
  1335. if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
  1336. return error("CAlert::CheckSignature() : verify signature failed");
  1337. // Now unserialize the data
  1338. CDataStream sMsg(vchMsg);
  1339. sMsg >> *(CUnsignedAlert*)this;
  1340. return true;
  1341. }
  1342. bool ProcessAlert();
  1343. };
  1344. #endif