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

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