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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2012 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifndef BITCOIN_MAIN_H
  6. #define BITCOIN_MAIN_H
  7. #include "bignum.h"
  8. #include "sync.h"
  9. #include "net.h"
  10. #include "script.h"
  11. #include <list>
  12. class CWallet;
  13. class CBlock;
  14. class CBlockIndex;
  15. class CKeyItem;
  16. class CReserveKey;
  17. class CAddress;
  18. class CInv;
  19. class CRequestTracker;
  20. class CNode;
  21. static const unsigned int MAX_BLOCK_SIZE = 1000000;
  22. static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
  23. static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
  24. static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
  25. static const unsigned int MAX_INV_SZ = 50000;
  26. static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
  27. static const int64 MIN_TX_FEE = 50000;
  28. static const int64 MIN_RELAY_TX_FEE = 10000;
  29. static const int64 MAX_MONEY = 21000000 * COIN;
  30. inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
  31. static const int COINBASE_MATURITY = 100;
  32. // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
  33. static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
  34. #ifdef USE_UPNP
  35. static const int fHaveUPnP = true;
  36. #else
  37. static const int fHaveUPnP = false;
  38. #endif
  39. extern CScript COINBASE_FLAGS;
  40. extern CCriticalSection cs_main;
  41. extern std::map<uint256, CBlockIndex*> mapBlockIndex;
  42. extern uint256 hashGenesisBlock;
  43. extern CBlockIndex* pindexGenesisBlock;
  44. extern int nBestHeight;
  45. extern CBigNum bnBestChainWork;
  46. extern CBigNum bnBestInvalidWork;
  47. extern uint256 hashBestChain;
  48. extern CBlockIndex* pindexBest;
  49. extern unsigned int nTransactionsUpdated;
  50. extern uint64 nLastBlockTx;
  51. extern uint64 nLastBlockSize;
  52. extern const std::string strMessageMagic;
  53. extern double dHashesPerSec;
  54. extern int64 nHPSTimerStart;
  55. extern int64 nTimeBestReceived;
  56. extern CCriticalSection cs_setpwalletRegistered;
  57. extern std::set<CWallet*> setpwalletRegistered;
  58. extern unsigned char pchMessageStart[4];
  59. extern bool fImporting;
  60. // Settings
  61. extern int64 nTransactionFee;
  62. // Minimum disk space required - used in CheckDiskSpace()
  63. static const uint64 nMinDiskSpace = 52428800;
  64. class CReserveKey;
  65. class CTxDB;
  66. class CTxIndex;
  67. class CDiskBlockPos;
  68. void RegisterWallet(CWallet* pwalletIn);
  69. void UnregisterWallet(CWallet* pwalletIn);
  70. void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
  71. bool ProcessBlock(CNode* pfrom, CBlock* pblock);
  72. bool CheckDiskSpace(uint64 nAdditionalBytes=0);
  73. FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  74. FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
  75. bool LoadBlockIndex(bool fAllowNew=true);
  76. void PrintBlockTree();
  77. CBlockIndex* FindBlockByHeight(int nHeight);
  78. bool ProcessMessages(CNode* pfrom);
  79. bool SendMessages(CNode* pto, bool fSendTrickle);
  80. void ThreadImport(void *parg);
  81. void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
  82. CBlock* CreateNewBlock(CReserveKey& reservekey);
  83. void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
  84. void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
  85. bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
  86. bool CheckProofOfWork(uint256 hash, unsigned int nBits);
  87. unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
  88. int GetNumBlocksOfPeers();
  89. bool IsInitialBlockDownload();
  90. std::string GetWarnings(std::string strFor);
  91. bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
  92. bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
  93. class CDiskBlockPos
  94. {
  95. public:
  96. int nFile;
  97. unsigned int nPos;
  98. IMPLEMENT_SERIALIZE(
  99. READWRITE(VARINT(nFile));
  100. READWRITE(VARINT(nPos));
  101. )
  102. friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  103. return (a.nFile == b.nFile && a.nPos == b.nPos);
  104. }
  105. friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
  106. return !(a == b);
  107. }
  108. void SetNull() { nFile = -1; nPos = 0; }
  109. bool IsNull() const { return (nFile == -1); }
  110. void SetMemPool() { nFile = -2; nPos = 0; }
  111. bool IsMemPool() const { return (nFile == -2); }
  112. };
  113. /** Position on disk for a particular transaction. */
  114. class CDiskTxPos
  115. {
  116. public:
  117. CDiskBlockPos blockPos;
  118. unsigned int nTxPos;
  119. CDiskTxPos(bool fInMemPool = false)
  120. {
  121. SetNull();
  122. if (fInMemPool)
  123. blockPos.SetMemPool();
  124. }
  125. CDiskTxPos(const CDiskBlockPos &block, unsigned int nTxPosIn) : blockPos(block), nTxPos(nTxPosIn) { }
  126. IMPLEMENT_SERIALIZE(
  127. READWRITE(blockPos);
  128. READWRITE(VARINT(nTxPos));
  129. )
  130. void SetNull() { blockPos.SetNull(); nTxPos = 0; }
  131. bool IsNull() const { return (nTxPos == 0); }
  132. bool IsMemPool() const { return blockPos.IsMemPool(); }
  133. friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
  134. {
  135. return (a.blockPos == b.blockPos &&
  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 if (blockPos.IsMemPool())
  147. return "mempool";
  148. else
  149. return strprintf("\"blk%05i.dat:0x%x\"", blockPos.nFile, nTxPos);
  150. }
  151. void print() const
  152. {
  153. printf("%s", ToString().c_str());
  154. }
  155. };
  156. /** An inpoint - a combination of a transaction and an index n into its vin */
  157. class CInPoint
  158. {
  159. public:
  160. CTransaction* ptx;
  161. unsigned int n;
  162. CInPoint() { SetNull(); }
  163. CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
  164. void SetNull() { ptx = NULL; n = (unsigned int) -1; }
  165. bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
  166. };
  167. /** An outpoint - a combination of a transaction hash and an index n into its vout */
  168. class COutPoint
  169. {
  170. public:
  171. uint256 hash;
  172. unsigned int n;
  173. COutPoint() { SetNull(); }
  174. COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
  175. IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
  176. void SetNull() { hash = 0; n = (unsigned int) -1; }
  177. bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
  178. friend bool operator<(const COutPoint& a, const COutPoint& b)
  179. {
  180. return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
  181. }
  182. friend bool operator==(const COutPoint& a, const COutPoint& b)
  183. {
  184. return (a.hash == b.hash && a.n == b.n);
  185. }
  186. friend bool operator!=(const COutPoint& a, const COutPoint& b)
  187. {
  188. return !(a == b);
  189. }
  190. std::string ToString() const
  191. {
  192. return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
  193. }
  194. void print() const
  195. {
  196. printf("%s\n", ToString().c_str());
  197. }
  198. };
  199. /** An input of a transaction. It contains the location of the previous
  200. * transaction's output that it claims and a signature that matches the
  201. * output's public key.
  202. */
  203. class CTxIn
  204. {
  205. public:
  206. COutPoint prevout;
  207. CScript scriptSig;
  208. unsigned int nSequence;
  209. CTxIn()
  210. {
  211. nSequence = std::numeric_limits<unsigned int>::max();
  212. }
  213. explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
  214. {
  215. prevout = prevoutIn;
  216. scriptSig = scriptSigIn;
  217. nSequence = nSequenceIn;
  218. }
  219. CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
  220. {
  221. prevout = COutPoint(hashPrevTx, nOut);
  222. scriptSig = scriptSigIn;
  223. nSequence = nSequenceIn;
  224. }
  225. IMPLEMENT_SERIALIZE
  226. (
  227. READWRITE(prevout);
  228. READWRITE(scriptSig);
  229. READWRITE(nSequence);
  230. )
  231. bool IsFinal() const
  232. {
  233. return (nSequence == std::numeric_limits<unsigned int>::max());
  234. }
  235. friend bool operator==(const CTxIn& a, const CTxIn& b)
  236. {
  237. return (a.prevout == b.prevout &&
  238. a.scriptSig == b.scriptSig &&
  239. a.nSequence == b.nSequence);
  240. }
  241. friend bool operator!=(const CTxIn& a, const CTxIn& b)
  242. {
  243. return !(a == b);
  244. }
  245. std::string ToString() const
  246. {
  247. std::string str;
  248. str += "CTxIn(";
  249. str += prevout.ToString();
  250. if (prevout.IsNull())
  251. str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
  252. else
  253. str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
  254. if (nSequence != std::numeric_limits<unsigned int>::max())
  255. str += strprintf(", nSequence=%u", nSequence);
  256. str += ")";
  257. return str;
  258. }
  259. void print() const
  260. {
  261. printf("%s\n", ToString().c_str());
  262. }
  263. };
  264. /** An output of a transaction. It contains the public key that the next input
  265. * must be able to sign with to claim it.
  266. */
  267. class CTxOut
  268. {
  269. public:
  270. int64 nValue;
  271. CScript scriptPubKey;
  272. CTxOut()
  273. {
  274. SetNull();
  275. }
  276. CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
  277. {
  278. nValue = nValueIn;
  279. scriptPubKey = scriptPubKeyIn;
  280. }
  281. IMPLEMENT_SERIALIZE
  282. (
  283. READWRITE(nValue);
  284. READWRITE(scriptPubKey);
  285. )
  286. void SetNull()
  287. {
  288. nValue = -1;
  289. scriptPubKey.clear();
  290. }
  291. bool IsNull() const
  292. {
  293. return (nValue == -1);
  294. }
  295. uint256 GetHash() const
  296. {
  297. return SerializeHash(*this);
  298. }
  299. friend bool operator==(const CTxOut& a, const CTxOut& b)
  300. {
  301. return (a.nValue == b.nValue &&
  302. a.scriptPubKey == b.scriptPubKey);
  303. }
  304. friend bool operator!=(const CTxOut& a, const CTxOut& b)
  305. {
  306. return !(a == b);
  307. }
  308. std::string ToString() const
  309. {
  310. if (scriptPubKey.size() < 6)
  311. return "CTxOut(error)";
  312. return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
  313. }
  314. void print() const
  315. {
  316. printf("%s\n", ToString().c_str());
  317. }
  318. };
  319. enum GetMinFee_mode
  320. {
  321. GMF_BLOCK,
  322. GMF_RELAY,
  323. GMF_SEND,
  324. };
  325. typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
  326. /** The basic transaction that is broadcasted on the network and contained in
  327. * blocks. A transaction can contain multiple inputs and outputs.
  328. */
  329. class CTransaction
  330. {
  331. public:
  332. static const int CURRENT_VERSION=1;
  333. int nVersion;
  334. std::vector<CTxIn> vin;
  335. std::vector<CTxOut> vout;
  336. unsigned int nLockTime;
  337. // Denial-of-service detection:
  338. mutable int nDoS;
  339. bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
  340. CTransaction()
  341. {
  342. SetNull();
  343. }
  344. IMPLEMENT_SERIALIZE
  345. (
  346. READWRITE(this->nVersion);
  347. nVersion = this->nVersion;
  348. READWRITE(vin);
  349. READWRITE(vout);
  350. READWRITE(nLockTime);
  351. )
  352. void SetNull()
  353. {
  354. nVersion = CTransaction::CURRENT_VERSION;
  355. vin.clear();
  356. vout.clear();
  357. nLockTime = 0;
  358. nDoS = 0; // Denial-of-service prevention
  359. }
  360. bool IsNull() const
  361. {
  362. return (vin.empty() && vout.empty());
  363. }
  364. uint256 GetHash() const
  365. {
  366. return SerializeHash(*this);
  367. }
  368. bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
  369. {
  370. // Time based nLockTime implemented in 0.1.6
  371. if (nLockTime == 0)
  372. return true;
  373. if (nBlockHeight == 0)
  374. nBlockHeight = nBestHeight;
  375. if (nBlockTime == 0)
  376. nBlockTime = GetAdjustedTime();
  377. if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
  378. return true;
  379. BOOST_FOREACH(const CTxIn& txin, vin)
  380. if (!txin.IsFinal())
  381. return false;
  382. return true;
  383. }
  384. bool IsNewerThan(const CTransaction& old) const
  385. {
  386. if (vin.size() != old.vin.size())
  387. return false;
  388. for (unsigned int i = 0; i < vin.size(); i++)
  389. if (vin[i].prevout != old.vin[i].prevout)
  390. return false;
  391. bool fNewer = false;
  392. unsigned int nLowest = std::numeric_limits<unsigned int>::max();
  393. for (unsigned int i = 0; i < vin.size(); i++)
  394. {
  395. if (vin[i].nSequence != old.vin[i].nSequence)
  396. {
  397. if (vin[i].nSequence <= nLowest)
  398. {
  399. fNewer = false;
  400. nLowest = vin[i].nSequence;
  401. }
  402. if (old.vin[i].nSequence < nLowest)
  403. {
  404. fNewer = true;
  405. nLowest = old.vin[i].nSequence;
  406. }
  407. }
  408. }
  409. return fNewer;
  410. }
  411. bool IsCoinBase() const
  412. {
  413. return (vin.size() == 1 && vin[0].prevout.IsNull());
  414. }
  415. /** Check for standard transaction types
  416. @return True if all outputs (scriptPubKeys) use only standard transaction forms
  417. */
  418. bool IsStandard() const;
  419. /** Check for standard transaction types
  420. @param[in] mapInputs Map of previous transactions that have outputs we're spending
  421. @return True if all inputs (scriptSigs) use only standard transaction forms
  422. @see CTransaction::FetchInputs
  423. */
  424. bool AreInputsStandard(const MapPrevTx& mapInputs) const;
  425. /** Count ECDSA signature operations the old-fashioned (pre-0.6) way
  426. @return number of sigops this transaction's outputs will produce when spent
  427. @see CTransaction::FetchInputs
  428. */
  429. unsigned int GetLegacySigOpCount() const;
  430. /** Count ECDSA signature operations in pay-to-script-hash inputs.
  431. @param[in] mapInputs Map of previous transactions that have outputs we're spending
  432. @return maximum number of sigops required to validate this transaction's inputs
  433. @see CTransaction::FetchInputs
  434. */
  435. unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
  436. /** Amount of bitcoins spent by this transaction.
  437. @return sum of all outputs (note: does not include fees)
  438. */
  439. int64 GetValueOut() const
  440. {
  441. int64 nValueOut = 0;
  442. BOOST_FOREACH(const CTxOut& txout, vout)
  443. {
  444. nValueOut += txout.nValue;
  445. if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
  446. throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
  447. }
  448. return nValueOut;
  449. }
  450. /** Amount of bitcoins coming in to this transaction
  451. Note that lightweight clients may not know anything besides the hash of previous transactions,
  452. so may not be able to calculate this.
  453. @param[in] mapInputs Map of previous transactions that have outputs we're spending
  454. @return Sum of value of all inputs (scriptSigs)
  455. @see CTransaction::FetchInputs
  456. */
  457. int64 GetValueIn(const MapPrevTx& mapInputs) const;
  458. static bool AllowFree(double dPriority)
  459. {
  460. // Large (in bytes) low-priority (new, small-coin) transactions
  461. // need a fee.
  462. return dPriority > COIN * 144 / 250;
  463. }
  464. int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const;
  465. bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
  466. {
  467. CAutoFile filein = CAutoFile(OpenBlockFile(pos.blockPos, pfileRet==NULL), SER_DISK, CLIENT_VERSION);
  468. if (!filein)
  469. return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
  470. // Read transaction
  471. if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
  472. return error("CTransaction::ReadFromDisk() : fseek failed");
  473. try {
  474. filein >> *this;
  475. }
  476. catch (std::exception &e) {
  477. return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
  478. }
  479. // Return file pointer
  480. if (pfileRet)
  481. {
  482. if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
  483. return error("CTransaction::ReadFromDisk() : second fseek failed");
  484. *pfileRet = filein.release();
  485. }
  486. return true;
  487. }
  488. friend bool operator==(const CTransaction& a, const CTransaction& b)
  489. {
  490. return (a.nVersion == b.nVersion &&
  491. a.vin == b.vin &&
  492. a.vout == b.vout &&
  493. a.nLockTime == b.nLockTime);
  494. }
  495. friend bool operator!=(const CTransaction& a, const CTransaction& b)
  496. {
  497. return !(a == b);
  498. }
  499. std::string ToString() const
  500. {
  501. std::string str;
  502. str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
  503. GetHash().ToString().substr(0,10).c_str(),
  504. nVersion,
  505. vin.size(),
  506. vout.size(),
  507. nLockTime);
  508. for (unsigned int i = 0; i < vin.size(); i++)
  509. str += " " + vin[i].ToString() + "\n";
  510. for (unsigned int i = 0; i < vout.size(); i++)
  511. str += " " + vout[i].ToString() + "\n";
  512. return str;
  513. }
  514. void print() const
  515. {
  516. printf("%s", ToString().c_str());
  517. }
  518. bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
  519. bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
  520. bool ReadFromDisk(COutPoint prevout);
  521. bool DisconnectInputs(CTxDB& txdb);
  522. /** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
  523. @param[in] txdb Transaction database
  524. @param[in] mapTestPool List of pending changes to the transaction index database
  525. @param[in] fBlock True if being called to add a new best-block to the chain
  526. @param[in] fMiner True if being called by CreateNewBlock
  527. @param[out] inputsRet Pointers to this transaction's inputs
  528. @param[out] fInvalid returns true if transaction is invalid
  529. @return Returns true if all inputs are in txdb or mapTestPool
  530. */
  531. bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
  532. bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
  533. /** Sanity check previous transactions, then, if all checks succeed,
  534. mark them as spent by this transaction.
  535. @param[in] inputs Previous transactions (from FetchInputs)
  536. @param[out] mapTestPool Keeps track of inputs that need to be updated on disk
  537. @param[in] posThisTx Position of this transaction on disk
  538. @param[in] pindexBlock
  539. @param[in] fBlock true if called from ConnectBlock
  540. @param[in] fMiner true if called from CreateNewBlock
  541. @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
  542. @return Returns true if all checks succeed
  543. */
  544. bool ConnectInputs(MapPrevTx inputs,
  545. std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
  546. const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
  547. bool ClientConnectInputs();
  548. bool CheckTransaction() const;
  549. bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
  550. protected:
  551. const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
  552. };
  553. /** wrapper for CTxOut that provides a more compact serialization */
  554. class CTxOutCompressor
  555. {
  556. private:
  557. CTxOut &txout;
  558. public:
  559. static uint64 CompressAmount(uint64 nAmount);
  560. static uint64 DecompressAmount(uint64 nAmount);
  561. CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
  562. IMPLEMENT_SERIALIZE(({
  563. if (!fRead) {
  564. uint64 nVal = CompressAmount(txout.nValue);
  565. READWRITE(VARINT(nVal));
  566. } else {
  567. uint64 nVal = 0;
  568. READWRITE(VARINT(nVal));
  569. txout.nValue = DecompressAmount(nVal);
  570. }
  571. CScriptCompressor cscript(REF(txout.scriptPubKey));
  572. READWRITE(cscript);
  573. });)
  574. };
  575. /** Undo information for a CTxIn
  576. *
  577. * Contains the prevout's CTxOut being spent, and if this was the
  578. * last output of the affected transaction, its metadata as well
  579. * (coinbase or not, height, transaction version)
  580. */
  581. class CTxInUndo
  582. {
  583. public:
  584. CTxOut txout; // the txout data before being spent
  585. bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
  586. unsigned int nHeight; // if the outpoint was the last unspent: its height
  587. int nVersion; // if the outpoint was the last unspent: its version
  588. CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
  589. CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
  590. unsigned int GetSerializeSize(int nType, int nVersion) const {
  591. return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
  592. (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
  593. ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
  594. }
  595. template<typename Stream>
  596. void Serialize(Stream &s, int nType, int nVersion) const {
  597. ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
  598. if (nHeight > 0)
  599. ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
  600. ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
  601. }
  602. template<typename Stream>
  603. void Unserialize(Stream &s, int nType, int nVersion) {
  604. unsigned int nCode = 0;
  605. ::Unserialize(s, VARINT(nCode), nType, nVersion);
  606. nHeight = nCode / 2;
  607. fCoinBase = nCode & 1;
  608. if (nHeight > 0)
  609. ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
  610. ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
  611. }
  612. };
  613. /** Undo information for a CTransaction */
  614. class CTxUndo
  615. {
  616. public:
  617. std::vector<CTxInUndo> vprevout;
  618. IMPLEMENT_SERIALIZE(
  619. READWRITE(vprevout);
  620. )
  621. };
  622. /** Undo information for a CBlock */
  623. class CBlockUndo
  624. {
  625. public:
  626. std::vector<CTxUndo> vtxundo;
  627. IMPLEMENT_SERIALIZE(
  628. READWRITE(vtxundo);
  629. )
  630. bool WriteToDisk(CDiskBlockPos &pos)
  631. {
  632. // Open history file to append
  633. CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
  634. if (!fileout)
  635. return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
  636. // Write index header
  637. unsigned int nSize = fileout.GetSerializeSize(*this);
  638. fileout << FLATDATA(pchMessageStart) << nSize;
  639. // Write undo data
  640. long fileOutPos = ftell(fileout);
  641. if (fileOutPos < 0)
  642. return error("CBlock::WriteToDisk() : ftell failed");
  643. pos.nPos = (unsigned int)fileOutPos;
  644. fileout << *this;
  645. // Flush stdio buffers and commit to disk before returning
  646. fflush(fileout);
  647. if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
  648. FileCommit(fileout);
  649. return true;
  650. }
  651. };
  652. /** pruned version of CTransaction: only retains metadata and unspent transaction outputs
  653. *
  654. * Serialized format:
  655. * - VARINT(nVersion)
  656. * - VARINT(nCode)
  657. * - unspentness bitvector, for vout[2] and further; least significant byte first
  658. * - the non-spent CTxOuts (via CTxOutCompressor)
  659. * - VARINT(nHeight)
  660. *
  661. * The nCode value consists of:
  662. * - bit 1: IsCoinBase()
  663. * - bit 2: vout[0] is not spent
  664. * - bit 4: vout[1] is not spent
  665. * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
  666. * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
  667. * least one non-spent output).
  668. *
  669. * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
  670. * <><><--------------------------------------------><---->
  671. * | \ | /
  672. * version code vout[1] height
  673. *
  674. * - version = 1
  675. * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
  676. * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
  677. * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
  678. * * 8358: compact amount representation for 60000000000 (600 BTC)
  679. * * 00: special txout type pay-to-pubkey-hash
  680. * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
  681. * - height = 203998
  682. *
  683. *
  684. * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
  685. * <><><--><--------------------------------------------------><----------------------------------------------><---->
  686. * / \ \ | | /
  687. * version code unspentness vout[4] vout[16] height
  688. *
  689. * - version = 1
  690. * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
  691. * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
  692. * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
  693. * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
  694. * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
  695. * * 00: special txout type pay-to-pubkey-hash
  696. * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
  697. * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
  698. * * bbd123: compact amount representation for 110397 (0.001 BTC)
  699. * * 00: special txout type pay-to-pubkey-hash
  700. * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
  701. * - height = 120891
  702. */
  703. class CCoins
  704. {
  705. public:
  706. // whether transaction is a coinbase
  707. bool fCoinBase;
  708. // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
  709. std::vector<CTxOut> vout;
  710. // at which height this transaction was included in the active blockchain
  711. int nHeight;
  712. // version of the CTransaction; accesses to this value should probably check for nHeight as well,
  713. // as new tx version will probably only be introduced at certain heights
  714. int nVersion;
  715. // construct a CCoins from a CTransaction, at a given height
  716. CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { }
  717. // empty constructor
  718. CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
  719. // remove spent outputs at the end of vout
  720. void Cleanup() {
  721. while (vout.size() > 0 && vout.back().IsNull())
  722. vout.pop_back();
  723. }
  724. // equality test
  725. friend bool operator==(const CCoins &a, const CCoins &b) {
  726. return a.fCoinBase == b.fCoinBase &&
  727. a.nHeight == b.nHeight &&
  728. a.nVersion == b.nVersion &&
  729. a.vout == b.vout;
  730. }
  731. friend bool operator!=(const CCoins &a, const CCoins &b) {
  732. return !(a == b);
  733. }
  734. // calculate number of bytes for the bitmask, and its number of non-zero bytes
  735. // each bit in the bitmask represents the availability of one output, but the
  736. // availabilities of the first two outputs are encoded separately
  737. void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
  738. unsigned int nLastUsedByte = 0;
  739. for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
  740. bool fZero = true;
  741. for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
  742. if (!vout[2+b*8+i].IsNull()) {
  743. fZero = false;
  744. continue;
  745. }
  746. }
  747. if (!fZero) {
  748. nLastUsedByte = b + 1;
  749. nNonzeroBytes++;
  750. }
  751. }
  752. nBytes += nLastUsedByte;
  753. }
  754. bool IsCoinBase() const {
  755. return fCoinBase;
  756. }
  757. unsigned int GetSerializeSize(int nType, int nVersion) const {
  758. unsigned int nSize = 0;
  759. unsigned int nMaskSize = 0, nMaskCode = 0;
  760. CalcMaskSize(nMaskSize, nMaskCode);
  761. bool fFirst = vout.size() > 0 && !vout[0].IsNull();
  762. bool fSecond = vout.size() > 1 && !vout[1].IsNull();
  763. assert(fFirst || fSecond || nMaskCode);
  764. unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
  765. // version
  766. nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
  767. // size of header code
  768. nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
  769. // spentness bitmask
  770. nSize += nMaskSize;
  771. // txouts themself
  772. for (unsigned int i = 0; i < vout.size(); i++)
  773. if (!vout[i].IsNull())
  774. nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
  775. // height
  776. nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
  777. return nSize;
  778. }
  779. template<typename Stream>
  780. void Serialize(Stream &s, int nType, int nVersion) const {
  781. unsigned int nMaskSize = 0, nMaskCode = 0;
  782. CalcMaskSize(nMaskSize, nMaskCode);
  783. bool fFirst = vout.size() > 0 && !vout[0].IsNull();
  784. bool fSecond = vout.size() > 1 && !vout[1].IsNull();
  785. assert(fFirst || fSecond || nMaskCode);
  786. unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
  787. // version
  788. ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
  789. // header code
  790. ::Serialize(s, VARINT(nCode), nType, nVersion);
  791. // spentness bitmask
  792. for (unsigned int b = 0; b<nMaskSize; b++) {
  793. unsigned char chAvail = 0;
  794. for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
  795. if (!vout[2+b*8+i].IsNull())
  796. chAvail |= (1 << i);
  797. ::Serialize(s, chAvail, nType, nVersion);
  798. }
  799. // txouts themself
  800. for (unsigned int i = 0; i < vout.size(); i++) {
  801. if (!vout[i].IsNull())
  802. ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
  803. }
  804. // coinbase height
  805. ::Serialize(s, VARINT(nHeight), nType, nVersion);
  806. }
  807. template<typename Stream>
  808. void Unserialize(Stream &s, int nType, int nVersion) {
  809. unsigned int nCode = 0;
  810. // version
  811. ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
  812. // header code
  813. ::Unserialize(s, VARINT(nCode), nType, nVersion);
  814. fCoinBase = nCode & 1;
  815. std::vector<bool> vAvail(2, false);
  816. vAvail[0] = nCode & 2;
  817. vAvail[1] = nCode & 4;
  818. unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
  819. // spentness bitmask
  820. while (nMaskCode > 0) {
  821. unsigned char chAvail = 0;
  822. ::Unserialize(s, chAvail, nType, nVersion);
  823. for (unsigned int p = 0; p < 8; p++) {
  824. bool f = (chAvail & (1 << p)) != 0;
  825. vAvail.push_back(f);
  826. }
  827. if (chAvail != 0)
  828. nMaskCode--;
  829. }
  830. // txouts themself
  831. vout.assign(vAvail.size(), CTxOut());
  832. for (unsigned int i = 0; i < vAvail.size(); i++) {
  833. if (vAvail[i])
  834. ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
  835. }
  836. // coinbase height
  837. ::Unserialize(s, VARINT(nHeight), nType, nVersion);
  838. Cleanup();
  839. }
  840. // mark an outpoint spent, and construct undo information
  841. bool Spend(const COutPoint &out, CTxInUndo &undo) {
  842. if (out.n >= vout.size())
  843. return false;
  844. if (vout[out.n].IsNull())
  845. return false;
  846. undo = CTxInUndo(vout[out.n]);
  847. vout[out.n].SetNull();
  848. Cleanup();
  849. if (vout.size() == 0) {
  850. undo.nHeight = nHeight;
  851. undo.fCoinBase = fCoinBase;
  852. undo.nVersion = this->nVersion;
  853. }
  854. return true;
  855. }
  856. // mark a vout spent
  857. bool Spend(int nPos) {
  858. CTxInUndo undo;
  859. COutPoint out(0, nPos);
  860. return Spend(out, undo);
  861. }
  862. // check whether a particular output is still available
  863. bool IsAvailable(unsigned int nPos) const {
  864. return (nPos < vout.size() && !vout[nPos].IsNull());
  865. }
  866. // check whether the entire CCoins is spent
  867. // note that only !IsPruned() CCoins can be serialized
  868. bool IsPruned() const {
  869. BOOST_FOREACH(const CTxOut &out, vout)
  870. if (!out.IsNull())
  871. return false;
  872. return true;
  873. }
  874. };
  875. /** A transaction with a merkle branch linking it to the block chain. */
  876. class CMerkleTx : public CTransaction
  877. {
  878. public:
  879. uint256 hashBlock;
  880. std::vector<uint256> vMerkleBranch;
  881. int nIndex;
  882. // memory only
  883. mutable bool fMerkleVerified;
  884. CMerkleTx()
  885. {
  886. Init();
  887. }
  888. CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
  889. {
  890. Init();
  891. }
  892. void Init()
  893. {
  894. hashBlock = 0;
  895. nIndex = -1;
  896. fMerkleVerified = false;
  897. }
  898. IMPLEMENT_SERIALIZE
  899. (
  900. nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
  901. nVersion = this->nVersion;
  902. READWRITE(hashBlock);
  903. READWRITE(vMerkleBranch);
  904. READWRITE(nIndex);
  905. )
  906. int SetMerkleBranch(const CBlock* pblock=NULL);
  907. int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
  908. int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
  909. bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
  910. int GetBlocksToMaturity() const;
  911. bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
  912. bool AcceptToMemoryPool();
  913. };
  914. /** A txdb record that contains the disk location of a transaction and the
  915. * locations of transactions that spend its outputs. vSpent is really only
  916. * used as a flag, but having the location is very helpful for debugging.
  917. */
  918. class CTxIndex
  919. {
  920. public:
  921. CDiskTxPos pos;
  922. std::vector<CDiskTxPos> vSpent;
  923. CTxIndex()
  924. {
  925. SetNull();
  926. }
  927. CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
  928. {
  929. pos = posIn;
  930. vSpent.resize(nOutputs);
  931. }
  932. IMPLEMENT_SERIALIZE
  933. (
  934. if (!(nType & SER_GETHASH))
  935. READWRITE(nVersion);
  936. READWRITE(pos);
  937. READWRITE(vSpent);
  938. )
  939. void SetNull()
  940. {
  941. pos.SetNull();
  942. vSpent.clear();
  943. }
  944. bool IsNull()
  945. {
  946. return pos.IsNull();
  947. }
  948. friend bool operator==(const CTxIndex& a, const CTxIndex& b)
  949. {
  950. return (a.pos == b.pos &&
  951. a.vSpent == b.vSpent);
  952. }
  953. friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
  954. {
  955. return !(a == b);
  956. }
  957. int GetDepthInMainChain() const;
  958. };
  959. /** Nodes collect new transactions into a block, hash them into a hash tree,
  960. * and scan through nonce values to make the block's hash satisfy proof-of-work
  961. * requirements. When they solve the proof-of-work, they broadcast the block
  962. * to everyone and the block is added to the block chain. The first transaction
  963. * in the block is a special one that creates a new coin owned by the creator
  964. * of the block.
  965. *
  966. * Blocks are appended to blk0001.dat files on disk. Their location on disk
  967. * is indexed by CBlockIndex objects in memory.
  968. */
  969. class CBlock
  970. {
  971. public:
  972. // header
  973. static const int CURRENT_VERSION=2;
  974. int nVersion;
  975. uint256 hashPrevBlock;
  976. uint256 hashMerkleRoot;
  977. unsigned int nTime;
  978. unsigned int nBits;
  979. unsigned int nNonce;
  980. // network and disk
  981. std::vector<CTransaction> vtx;
  982. // memory only
  983. mutable std::vector<uint256> vMerkleTree;
  984. // Denial-of-service detection:
  985. mutable int nDoS;
  986. bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
  987. CBlock()
  988. {
  989. SetNull();
  990. }
  991. IMPLEMENT_SERIALIZE
  992. (
  993. READWRITE(this->nVersion);
  994. nVersion = this->nVersion;
  995. READWRITE(hashPrevBlock);
  996. READWRITE(hashMerkleRoot);
  997. READWRITE(nTime);
  998. READWRITE(nBits);
  999. READWRITE(nNonce);
  1000. // ConnectBlock depends on vtx being last so it can calculate offset
  1001. if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
  1002. READWRITE(vtx);
  1003. else if (fRead)
  1004. const_cast<CBlock*>(this)->vtx.clear();
  1005. )
  1006. void SetNull()
  1007. {
  1008. nVersion = CBlock::CURRENT_VERSION;
  1009. hashPrevBlock = 0;
  1010. hashMerkleRoot = 0;
  1011. nTime = 0;
  1012. nBits = 0;
  1013. nNonce = 0;
  1014. vtx.clear();
  1015. vMerkleTree.clear();
  1016. nDoS = 0;
  1017. }
  1018. bool IsNull() const
  1019. {
  1020. return (nBits == 0);
  1021. }
  1022. uint256 GetHash() const
  1023. {
  1024. return Hash(BEGIN(nVersion), END(nNonce));
  1025. }
  1026. int64 GetBlockTime() const
  1027. {
  1028. return (int64)nTime;
  1029. }
  1030. void UpdateTime(const CBlockIndex* pindexPrev);
  1031. uint256 BuildMerkleTree() const
  1032. {
  1033. vMerkleTree.clear();
  1034. BOOST_FOREACH(const CTransaction& tx, vtx)
  1035. vMerkleTree.push_back(tx.GetHash());
  1036. int j = 0;
  1037. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  1038. {
  1039. for (int i = 0; i < nSize; i += 2)
  1040. {
  1041. int i2 = std::min(i+1, nSize-1);
  1042. vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
  1043. BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
  1044. }
  1045. j += nSize;
  1046. }
  1047. return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
  1048. }
  1049. std::vector<uint256> GetMerkleBranch(int nIndex) const
  1050. {
  1051. if (vMerkleTree.empty())
  1052. BuildMerkleTree();
  1053. std::vector<uint256> vMerkleBranch;
  1054. int j = 0;
  1055. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  1056. {
  1057. int i = std::min(nIndex^1, nSize-1);
  1058. vMerkleBranch.push_back(vMerkleTree[j+i]);
  1059. nIndex >>= 1;
  1060. j += nSize;
  1061. }
  1062. return vMerkleBranch;
  1063. }
  1064. static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
  1065. {
  1066. if (nIndex == -1)
  1067. return 0;
  1068. BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
  1069. {
  1070. if (nIndex & 1)
  1071. hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
  1072. else
  1073. hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
  1074. nIndex >>= 1;
  1075. }
  1076. return hash;
  1077. }
  1078. bool WriteToDisk(CDiskBlockPos &pos)
  1079. {
  1080. // Open history file to append
  1081. CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
  1082. if (!fileout)
  1083. return error("CBlock::WriteToDisk() : OpenBlockFile failed");
  1084. // Write index header
  1085. unsigned int nSize = fileout.GetSerializeSize(*this);
  1086. fileout << FLATDATA(pchMessageStart) << nSize;
  1087. // Write block
  1088. long fileOutPos = ftell(fileout);
  1089. if (fileOutPos < 0)
  1090. return error("CBlock::WriteToDisk() : ftell failed");
  1091. pos.nPos = (unsigned int)fileOutPos;
  1092. fileout << *this;
  1093. // Flush stdio buffers and commit to disk before returning
  1094. fflush(fileout);
  1095. if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
  1096. FileCommit(fileout);
  1097. return true;
  1098. }
  1099. bool ReadFromDisk(const CDiskBlockPos &pos, bool fReadTransactions = true)
  1100. {
  1101. SetNull();
  1102. // Open history file to read
  1103. CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
  1104. if (!filein)
  1105. return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
  1106. if (!fReadTransactions)
  1107. filein.nType |= SER_BLOCKHEADERONLY;
  1108. // Read block
  1109. try {
  1110. filein >> *this;
  1111. }
  1112. catch (std::exception &e) {
  1113. return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
  1114. }
  1115. // Check the header
  1116. if (!CheckProofOfWork(GetHash(), nBits))
  1117. return error("CBlock::ReadFromDisk() : errors in block header");
  1118. return true;
  1119. }
  1120. void print() const
  1121. {
  1122. printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
  1123. GetHash().ToString().substr(0,20).c_str(),
  1124. nVersion,
  1125. hashPrevBlock.ToString().substr(0,20).c_str(),
  1126. hashMerkleRoot.ToString().substr(0,10).c_str(),
  1127. nTime, nBits, nNonce,
  1128. vtx.size());
  1129. for (unsigned int i = 0; i < vtx.size(); i++)
  1130. {
  1131. printf(" ");
  1132. vtx[i].print();
  1133. }
  1134. printf(" vMerkleTree: ");
  1135. for (unsigned int i = 0; i < vMerkleTree.size(); i++)
  1136. printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
  1137. printf("\n");
  1138. }
  1139. bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
  1140. bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
  1141. bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
  1142. bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
  1143. bool AddToBlockIndex(const CDiskBlockPos &pos);
  1144. bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
  1145. bool AcceptBlock();
  1146. private:
  1147. bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
  1148. };
  1149. class CBlockFileInfo
  1150. {
  1151. public:
  1152. unsigned int nBlocks; // number of blocks stored in file
  1153. unsigned int nSize; // number of used bytes of block file
  1154. unsigned int nUndoSize; // number of used bytes in the undo file
  1155. unsigned int nHeightFirst; // lowest height of block in file
  1156. unsigned int nHeightLast; // highest height of block in file
  1157. uint64 nTimeFirst; // earliest time of block in file
  1158. uint64 nTimeLast; // latest time of block in file
  1159. IMPLEMENT_SERIALIZE(
  1160. READWRITE(VARINT(nBlocks));
  1161. READWRITE(VARINT(nSize));
  1162. READWRITE(VARINT(nUndoSize));
  1163. READWRITE(VARINT(nHeightFirst));
  1164. READWRITE(VARINT(nHeightLast));
  1165. READWRITE(VARINT(nTimeFirst));
  1166. READWRITE(VARINT(nTimeLast));
  1167. )
  1168. void SetNull() {
  1169. nBlocks = 0;
  1170. nSize = 0;
  1171. nUndoSize = 0;
  1172. nHeightFirst = 0;
  1173. nHeightLast = 0;
  1174. nTimeFirst = 0;
  1175. nTimeLast = 0;
  1176. }
  1177. CBlockFileInfo() {
  1178. SetNull();
  1179. }
  1180. std::string ToString() const {
  1181. return strprintf("CBlockFileInfo(blocks=%u, size=%lu, heights=%u..%u, time=%s..%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str());
  1182. }
  1183. // update statistics (does not update nSize)
  1184. void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
  1185. if (nBlocks==0 || nHeightFirst > nHeightIn)
  1186. nHeightFirst = nHeightIn;
  1187. if (nBlocks==0 || nTimeFirst > nTimeIn)
  1188. nTimeFirst = nTimeIn;
  1189. nBlocks++;
  1190. if (nHeightIn > nHeightFirst)
  1191. nHeightLast = nHeightIn;
  1192. if (nTimeIn > nTimeLast)
  1193. nTimeLast = nTimeIn;
  1194. }
  1195. };
  1196. extern CCriticalSection cs_LastBlockFile;
  1197. extern CBlockFileInfo infoLastBlockFile;
  1198. extern int nLastBlockFile;
  1199. /** The block chain is a tree shaped structure starting with the
  1200. * genesis block at the root, with each block potentially having multiple
  1201. * candidates to be the next block. pprev and pnext link a path through the
  1202. * main/longest chain. A blockindex may have multiple pprev pointing back
  1203. * to it, but pnext will only point forward to the longest branch, or will
  1204. * be null if the block is not part of the longest chain.
  1205. */
  1206. class CBlockIndex
  1207. {
  1208. public:
  1209. const uint256* phashBlock;
  1210. CBlockIndex* pprev;
  1211. CBlockIndex* pnext;
  1212. int nHeight;
  1213. CDiskBlockPos pos;
  1214. unsigned int nUndoPos;
  1215. CBigNum bnChainWork;
  1216. // block header
  1217. int nVersion;
  1218. uint256 hashMerkleRoot;
  1219. unsigned int nTime;
  1220. unsigned int nBits;
  1221. unsigned int nNonce;
  1222. CBlockIndex()
  1223. {
  1224. phashBlock = NULL;
  1225. pprev = NULL;
  1226. pnext = NULL;
  1227. nHeight = 0;
  1228. pos.SetNull();
  1229. nUndoPos = (unsigned int)(-1);
  1230. bnChainWork = 0;
  1231. nVersion = 0;
  1232. hashMerkleRoot = 0;
  1233. nTime = 0;
  1234. nBits = 0;
  1235. nNonce = 0;
  1236. }
  1237. CBlockIndex(CBlock& block)
  1238. {
  1239. phashBlock = NULL;
  1240. pprev = NULL;
  1241. pnext = NULL;
  1242. nHeight = 0;
  1243. pos.SetNull();
  1244. nUndoPos = 0;
  1245. bnChainWork = 0;
  1246. nVersion = block.nVersion;
  1247. hashMerkleRoot = block.hashMerkleRoot;
  1248. nTime = block.nTime;
  1249. nBits = block.nBits;
  1250. nNonce = block.nNonce;
  1251. }
  1252. CDiskBlockPos GetBlockPos() const {
  1253. return pos;
  1254. }
  1255. CDiskBlockPos GetUndoPos() const {
  1256. CDiskBlockPos ret = pos;
  1257. if (nUndoPos == (unsigned int)(-1))
  1258. ret.SetNull();
  1259. else
  1260. ret.nPos = nUndoPos;
  1261. return ret;
  1262. }
  1263. CBlock GetBlockHeader() const
  1264. {
  1265. CBlock block;
  1266. block.nVersion = nVersion;
  1267. if (pprev)
  1268. block.hashPrevBlock = pprev->GetBlockHash();
  1269. block.hashMerkleRoot = hashMerkleRoot;
  1270. block.nTime = nTime;
  1271. block.nBits = nBits;
  1272. block.nNonce = nNonce;
  1273. return block;
  1274. }
  1275. uint256 GetBlockHash() const
  1276. {
  1277. return *phashBlock;
  1278. }
  1279. int64 GetBlockTime() const
  1280. {
  1281. return (int64)nTime;
  1282. }
  1283. CBigNum GetBlockWork() const
  1284. {
  1285. CBigNum bnTarget;
  1286. bnTarget.SetCompact(nBits);
  1287. if (bnTarget <= 0)
  1288. return 0;
  1289. return (CBigNum(1)<<256) / (bnTarget+1);
  1290. }
  1291. bool IsInMainChain() const
  1292. {
  1293. return (pnext || this == pindexBest);
  1294. }
  1295. bool CheckIndex() const
  1296. {
  1297. return CheckProofOfWork(GetBlockHash(), nBits);
  1298. }
  1299. enum { nMedianTimeSpan=11 };
  1300. int64 GetMedianTimePast() const
  1301. {
  1302. int64 pmedian[nMedianTimeSpan];
  1303. int64* pbegin = &pmedian[nMedianTimeSpan];
  1304. int64* pend = &pmedian[nMedianTimeSpan];
  1305. const CBlockIndex* pindex = this;
  1306. for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
  1307. *(--pbegin) = pindex->GetBlockTime();
  1308. std::sort(pbegin, pend);
  1309. return pbegin[(pend - pbegin)/2];
  1310. }
  1311. int64 GetMedianTime() const
  1312. {
  1313. const CBlockIndex* pindex = this;
  1314. for (int i = 0; i < nMedianTimeSpan/2; i++)
  1315. {
  1316. if (!pindex->pnext)
  1317. return GetBlockTime();
  1318. pindex = pindex->pnext;
  1319. }
  1320. return pindex->GetMedianTimePast();
  1321. }
  1322. /**
  1323. * Returns true if there are nRequired or more blocks of minVersion or above
  1324. * in the last nToCheck blocks, starting at pstart and going backwards.
  1325. */
  1326. static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
  1327. unsigned int nRequired, unsigned int nToCheck);
  1328. std::string ToString() const
  1329. {
  1330. return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
  1331. pprev, pnext, nHeight,
  1332. hashMerkleRoot.ToString().substr(0,10).c_str(),
  1333. GetBlockHash().ToString().substr(0,20).c_str());
  1334. }
  1335. void print() const
  1336. {
  1337. printf("%s\n", ToString().c_str());
  1338. }
  1339. };
  1340. /** Used to marshal pointers into hashes for db storage. */
  1341. class CDiskBlockIndex : public CBlockIndex
  1342. {
  1343. public:
  1344. uint256 hashPrev;
  1345. uint256 hashNext;
  1346. CDiskBlockIndex()
  1347. {
  1348. hashPrev = 0;
  1349. hashNext = 0;
  1350. }
  1351. explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
  1352. {
  1353. hashPrev = (pprev ? pprev->GetBlockHash() : 0);
  1354. hashNext = (pnext ? pnext->GetBlockHash() : 0);
  1355. }
  1356. IMPLEMENT_SERIALIZE
  1357. (
  1358. if (!(nType & SER_GETHASH))
  1359. READWRITE(nVersion);
  1360. READWRITE(hashNext);
  1361. READWRITE(nHeight);
  1362. READWRITE(pos);
  1363. READWRITE(nUndoPos);
  1364. // block header
  1365. READWRITE(this->nVersion);
  1366. READWRITE(hashPrev);
  1367. READWRITE(hashMerkleRoot);
  1368. READWRITE(nTime);
  1369. READWRITE(nBits);
  1370. READWRITE(nNonce);
  1371. )
  1372. uint256 GetBlockHash() const
  1373. {
  1374. CBlock block;
  1375. block.nVersion = nVersion;
  1376. block.hashPrevBlock = hashPrev;
  1377. block.hashMerkleRoot = hashMerkleRoot;
  1378. block.nTime = nTime;
  1379. block.nBits = nBits;
  1380. block.nNonce = nNonce;
  1381. return block.GetHash();
  1382. }
  1383. std::string ToString() const
  1384. {
  1385. std::string str = "CDiskBlockIndex(";
  1386. str += CBlockIndex::ToString();
  1387. str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
  1388. GetBlockHash().ToString().c_str(),
  1389. hashPrev.ToString().substr(0,20).c_str(),
  1390. hashNext.ToString().substr(0,20).c_str());
  1391. return str;
  1392. }
  1393. void print() const
  1394. {
  1395. printf("%s\n", ToString().c_str());
  1396. }
  1397. };
  1398. /** Describes a place in the block chain to another node such that if the
  1399. * other node doesn't have the same branch, it can find a recent common trunk.
  1400. * The further back it is, the further before the fork it may be.
  1401. */
  1402. class CBlockLocator
  1403. {
  1404. protected:
  1405. std::vector<uint256> vHave;
  1406. public:
  1407. CBlockLocator()
  1408. {
  1409. }
  1410. explicit CBlockLocator(const CBlockIndex* pindex)
  1411. {
  1412. Set(pindex);
  1413. }
  1414. explicit CBlockLocator(uint256 hashBlock)
  1415. {
  1416. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  1417. if (mi != mapBlockIndex.end())
  1418. Set((*mi).second);
  1419. }
  1420. CBlockLocator(const std::vector<uint256>& vHaveIn)
  1421. {
  1422. vHave = vHaveIn;
  1423. }
  1424. IMPLEMENT_SERIALIZE
  1425. (
  1426. if (!(nType & SER_GETHASH))
  1427. READWRITE(nVersion);
  1428. READWRITE(vHave);
  1429. )
  1430. void SetNull()
  1431. {
  1432. vHave.clear();
  1433. }
  1434. bool IsNull()
  1435. {
  1436. return vHave.empty();
  1437. }
  1438. void Set(const CBlockIndex* pindex)
  1439. {
  1440. vHave.clear();
  1441. int nStep = 1;
  1442. while (pindex)
  1443. {
  1444. vHave.push_back(pindex->GetBlockHash());
  1445. // Exponentially larger steps back
  1446. for (int i = 0; pindex && i < nStep; i++)
  1447. pindex = pindex->pprev;
  1448. if (vHave.size() > 10)
  1449. nStep *= 2;
  1450. }
  1451. vHave.push_back(hashGenesisBlock);
  1452. }
  1453. int GetDistanceBack()
  1454. {
  1455. // Retrace how far back it was in the sender's branch
  1456. int nDistance = 0;
  1457. int nStep = 1;
  1458. BOOST_FOREACH(const uint256& hash, vHave)
  1459. {
  1460. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1461. if (mi != mapBlockIndex.end())
  1462. {
  1463. CBlockIndex* pindex = (*mi).second;
  1464. if (pindex->IsInMainChain())
  1465. return nDistance;
  1466. }
  1467. nDistance += nStep;
  1468. if (nDistance > 10)
  1469. nStep *= 2;
  1470. }
  1471. return nDistance;
  1472. }
  1473. CBlockIndex* GetBlockIndex()
  1474. {
  1475. // Find the first block the caller has in the main chain
  1476. BOOST_FOREACH(const uint256& hash, vHave)
  1477. {
  1478. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1479. if (mi != mapBlockIndex.end())
  1480. {
  1481. CBlockIndex* pindex = (*mi).second;
  1482. if (pindex->IsInMainChain())
  1483. return pindex;
  1484. }
  1485. }
  1486. return pindexGenesisBlock;
  1487. }
  1488. uint256 GetBlockHash()
  1489. {
  1490. // Find the first block the caller has in the main chain
  1491. BOOST_FOREACH(const uint256& hash, vHave)
  1492. {
  1493. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1494. if (mi != mapBlockIndex.end())
  1495. {
  1496. CBlockIndex* pindex = (*mi).second;
  1497. if (pindex->IsInMainChain())
  1498. return hash;
  1499. }
  1500. }
  1501. return hashGenesisBlock;
  1502. }
  1503. int GetHeight()
  1504. {
  1505. CBlockIndex* pindex = GetBlockIndex();
  1506. if (!pindex)
  1507. return 0;
  1508. return pindex->nHeight;
  1509. }
  1510. };
  1511. class CTxMemPool
  1512. {
  1513. public:
  1514. mutable CCriticalSection cs;
  1515. std::map<uint256, CTransaction> mapTx;
  1516. std::map<COutPoint, CInPoint> mapNextTx;
  1517. bool accept(CTxDB& txdb, CTransaction &tx,
  1518. bool fCheckInputs, bool* pfMissingInputs);
  1519. bool addUnchecked(const uint256& hash, CTransaction &tx);
  1520. bool remove(CTransaction &tx);
  1521. void clear();
  1522. void queryHashes(std::vector<uint256>& vtxid);
  1523. unsigned long size()
  1524. {
  1525. LOCK(cs);
  1526. return mapTx.size();
  1527. }
  1528. bool exists(uint256 hash)
  1529. {
  1530. return (mapTx.count(hash) != 0);
  1531. }
  1532. CTransaction& lookup(uint256 hash)
  1533. {
  1534. return mapTx[hash];
  1535. }
  1536. };
  1537. extern CTxMemPool mempool;
  1538. #endif