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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Distributed under the MIT/X11 software license, see the accompanying
  3. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
  4. #ifndef BITCOIN_MAIN_H
  5. #define BITCOIN_MAIN_H
  6. #include "bignum.h"
  7. #include "net.h"
  8. #include "key.h"
  9. #include "db.h"
  10. #include "script.h"
  11. #include <list>
  12. class COutPoint;
  13. class CInPoint;
  14. class CDiskTxPos;
  15. class CCoinBase;
  16. class CTxIn;
  17. class CTxOut;
  18. class CTransaction;
  19. class CBlock;
  20. class CBlockIndex;
  21. class CWalletTx;
  22. class CKeyItem;
  23. static const unsigned int MAX_BLOCK_SIZE = 1000000;
  24. static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
  25. static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
  26. static const int64 COIN = 100000000;
  27. static const int64 CENT = 1000000;
  28. static const int64 MIN_TX_FEE = 50000;
  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. #ifdef USE_UPNP
  33. static const int fHaveUPnP = true;
  34. #else
  35. static const int fHaveUPnP = false;
  36. #endif
  37. extern CCriticalSection cs_main;
  38. extern std::map<uint256, CBlockIndex*> mapBlockIndex;
  39. extern uint256 hashGenesisBlock;
  40. extern CBigNum bnProofOfWorkLimit;
  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 std::map<uint256, int> mapRequestCount;
  49. extern CCriticalSection cs_mapRequestCount;
  50. extern std::map<std::string, std::string> mapAddressBook;
  51. extern CCriticalSection cs_mapAddressBook;
  52. extern std::vector<unsigned char> vchDefaultKey;
  53. extern double dHashesPerSec;
  54. extern int64 nHPSTimerStart;
  55. // Settings
  56. extern int fGenerateBitcoins;
  57. extern int64 nTransactionFee;
  58. extern CAddress addrIncoming;
  59. extern int fLimitProcessors;
  60. extern int nLimitProcessors;
  61. extern int fMinimizeToTray;
  62. extern int fMinimizeOnClose;
  63. extern int fUseUPnP;
  64. bool CheckDiskSpace(uint64 nAdditionalBytes=0);
  65. FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
  66. FILE* AppendBlockFile(unsigned int& nFileRet);
  67. bool AddKey(const CKey& key);
  68. std::vector<unsigned char> GenerateNewKey();
  69. bool AddToWallet(const CWalletTx& wtxIn);
  70. void WalletUpdateSpent(const COutPoint& prevout);
  71. int ScanForWalletTransactions(CBlockIndex* pindexStart);
  72. void ReacceptWalletTransactions();
  73. bool LoadBlockIndex(bool fAllowNew=true);
  74. void PrintBlockTree();
  75. bool ProcessMessages(CNode* pfrom);
  76. bool ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv);
  77. bool SendMessages(CNode* pto, bool fSendTrickle);
  78. int64 GetBalance();
  79. bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
  80. bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
  81. bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
  82. bool BroadcastTransaction(CWalletTx& wtxNew);
  83. std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
  84. std::string SendMoneyToBitcoinAddress(std::string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
  85. void GenerateBitcoins(bool fGenerate);
  86. void ThreadBitcoinMiner(void* parg);
  87. CBlock* CreateNewBlock(CReserveKey& reservekey);
  88. void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
  89. void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
  90. bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
  91. void BitcoinMiner();
  92. bool CheckProofOfWork(uint256 hash, unsigned int nBits);
  93. bool IsInitialBlockDownload();
  94. std::string GetWarnings(std::string strFor);
  95. class CDiskTxPos
  96. {
  97. public:
  98. unsigned int nFile;
  99. unsigned int nBlockPos;
  100. unsigned int nTxPos;
  101. CDiskTxPos()
  102. {
  103. SetNull();
  104. }
  105. CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
  106. {
  107. nFile = nFileIn;
  108. nBlockPos = nBlockPosIn;
  109. nTxPos = nTxPosIn;
  110. }
  111. IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
  112. void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
  113. bool IsNull() const { return (nFile == -1); }
  114. friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
  115. {
  116. return (a.nFile == b.nFile &&
  117. a.nBlockPos == b.nBlockPos &&
  118. a.nTxPos == b.nTxPos);
  119. }
  120. friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
  121. {
  122. return !(a == b);
  123. }
  124. std::string ToString() const
  125. {
  126. if (IsNull())
  127. return strprintf("null");
  128. else
  129. return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
  130. }
  131. void print() const
  132. {
  133. printf("%s", ToString().c_str());
  134. }
  135. };
  136. class CInPoint
  137. {
  138. public:
  139. CTransaction* ptx;
  140. unsigned int n;
  141. CInPoint() { SetNull(); }
  142. CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
  143. void SetNull() { ptx = NULL; n = -1; }
  144. bool IsNull() const { return (ptx == NULL && n == -1); }
  145. };
  146. class COutPoint
  147. {
  148. public:
  149. uint256 hash;
  150. unsigned int n;
  151. COutPoint() { SetNull(); }
  152. COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
  153. IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
  154. void SetNull() { hash = 0; n = -1; }
  155. bool IsNull() const { return (hash == 0 && n == -1); }
  156. friend bool operator<(const COutPoint& a, const COutPoint& b)
  157. {
  158. return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
  159. }
  160. friend bool operator==(const COutPoint& a, const COutPoint& b)
  161. {
  162. return (a.hash == b.hash && a.n == b.n);
  163. }
  164. friend bool operator!=(const COutPoint& a, const COutPoint& b)
  165. {
  166. return !(a == b);
  167. }
  168. std::string ToString() const
  169. {
  170. return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
  171. }
  172. void print() const
  173. {
  174. printf("%s\n", ToString().c_str());
  175. }
  176. };
  177. //
  178. // An input of a transaction. It contains the location of the previous
  179. // transaction's output that it claims and a signature that matches the
  180. // output's public key.
  181. //
  182. class CTxIn
  183. {
  184. public:
  185. COutPoint prevout;
  186. CScript scriptSig;
  187. unsigned int nSequence;
  188. CTxIn()
  189. {
  190. nSequence = UINT_MAX;
  191. }
  192. explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
  193. {
  194. prevout = prevoutIn;
  195. scriptSig = scriptSigIn;
  196. nSequence = nSequenceIn;
  197. }
  198. CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
  199. {
  200. prevout = COutPoint(hashPrevTx, nOut);
  201. scriptSig = scriptSigIn;
  202. nSequence = nSequenceIn;
  203. }
  204. IMPLEMENT_SERIALIZE
  205. (
  206. READWRITE(prevout);
  207. READWRITE(scriptSig);
  208. READWRITE(nSequence);
  209. )
  210. bool IsFinal() const
  211. {
  212. return (nSequence == UINT_MAX);
  213. }
  214. friend bool operator==(const CTxIn& a, const CTxIn& b)
  215. {
  216. return (a.prevout == b.prevout &&
  217. a.scriptSig == b.scriptSig &&
  218. a.nSequence == b.nSequence);
  219. }
  220. friend bool operator!=(const CTxIn& a, const CTxIn& b)
  221. {
  222. return !(a == b);
  223. }
  224. std::string ToString() const
  225. {
  226. std::string str;
  227. str += strprintf("CTxIn(");
  228. str += prevout.ToString();
  229. if (prevout.IsNull())
  230. str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
  231. else
  232. str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
  233. if (nSequence != UINT_MAX)
  234. str += strprintf(", nSequence=%u", nSequence);
  235. str += ")";
  236. return str;
  237. }
  238. void print() const
  239. {
  240. printf("%s\n", ToString().c_str());
  241. }
  242. bool IsMine() const;
  243. int64 GetDebit() const;
  244. };
  245. //
  246. // An output of a transaction. It contains the public key that the next input
  247. // must be able to sign with to claim it.
  248. //
  249. class CTxOut
  250. {
  251. public:
  252. int64 nValue;
  253. CScript scriptPubKey;
  254. CTxOut()
  255. {
  256. SetNull();
  257. }
  258. CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
  259. {
  260. nValue = nValueIn;
  261. scriptPubKey = scriptPubKeyIn;
  262. }
  263. IMPLEMENT_SERIALIZE
  264. (
  265. READWRITE(nValue);
  266. READWRITE(scriptPubKey);
  267. )
  268. void SetNull()
  269. {
  270. nValue = -1;
  271. scriptPubKey.clear();
  272. }
  273. bool IsNull()
  274. {
  275. return (nValue == -1);
  276. }
  277. uint256 GetHash() const
  278. {
  279. return SerializeHash(*this);
  280. }
  281. bool IsMine() const
  282. {
  283. return ::IsMine(scriptPubKey);
  284. }
  285. int64 GetCredit() const
  286. {
  287. if (!MoneyRange(nValue))
  288. throw std::runtime_error("CTxOut::GetCredit() : value out of range");
  289. return (IsMine() ? nValue : 0);
  290. }
  291. bool IsChange() const
  292. {
  293. // On a debit transaction, a txout that's mine but isn't in the address book is change
  294. std::vector<unsigned char> vchPubKey;
  295. if (ExtractPubKey(scriptPubKey, true, vchPubKey))
  296. CRITICAL_BLOCK(cs_mapAddressBook)
  297. if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
  298. return true;
  299. return false;
  300. }
  301. int64 GetChange() const
  302. {
  303. if (!MoneyRange(nValue))
  304. throw std::runtime_error("CTxOut::GetChange() : value out of range");
  305. return (IsChange() ? nValue : 0);
  306. }
  307. friend bool operator==(const CTxOut& a, const CTxOut& b)
  308. {
  309. return (a.nValue == b.nValue &&
  310. a.scriptPubKey == b.scriptPubKey);
  311. }
  312. friend bool operator!=(const CTxOut& a, const CTxOut& b)
  313. {
  314. return !(a == b);
  315. }
  316. std::string ToString() const
  317. {
  318. if (scriptPubKey.size() < 6)
  319. return "CTxOut(error)";
  320. return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
  321. }
  322. void print() const
  323. {
  324. printf("%s\n", ToString().c_str());
  325. }
  326. };
  327. //
  328. // The basic transaction that is broadcasted on the network and contained in
  329. // blocks. A transaction can contain multiple inputs and outputs.
  330. //
  331. class CTransaction
  332. {
  333. public:
  334. int nVersion;
  335. std::vector<CTxIn> vin;
  336. std::vector<CTxOut> vout;
  337. unsigned int nLockTime;
  338. CTransaction()
  339. {
  340. SetNull();
  341. }
  342. IMPLEMENT_SERIALIZE
  343. (
  344. READWRITE(this->nVersion);
  345. nVersion = this->nVersion;
  346. READWRITE(vin);
  347. READWRITE(vout);
  348. READWRITE(nLockTime);
  349. )
  350. void SetNull()
  351. {
  352. nVersion = 1;
  353. vin.clear();
  354. vout.clear();
  355. nLockTime = 0;
  356. }
  357. bool IsNull() const
  358. {
  359. return (vin.empty() && vout.empty());
  360. }
  361. uint256 GetHash() const
  362. {
  363. return SerializeHash(*this);
  364. }
  365. bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
  366. {
  367. // Time based nLockTime implemented in 0.1.6
  368. if (nLockTime == 0)
  369. return true;
  370. if (nBlockHeight == 0)
  371. nBlockHeight = nBestHeight;
  372. if (nBlockTime == 0)
  373. nBlockTime = GetAdjustedTime();
  374. if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
  375. return true;
  376. BOOST_FOREACH(const CTxIn& txin, vin)
  377. if (!txin.IsFinal())
  378. return false;
  379. return true;
  380. }
  381. bool IsNewerThan(const CTransaction& old) const
  382. {
  383. if (vin.size() != old.vin.size())
  384. return false;
  385. for (int i = 0; i < vin.size(); i++)
  386. if (vin[i].prevout != old.vin[i].prevout)
  387. return false;
  388. bool fNewer = false;
  389. unsigned int nLowest = UINT_MAX;
  390. for (int i = 0; i < vin.size(); i++)
  391. {
  392. if (vin[i].nSequence != old.vin[i].nSequence)
  393. {
  394. if (vin[i].nSequence <= nLowest)
  395. {
  396. fNewer = false;
  397. nLowest = vin[i].nSequence;
  398. }
  399. if (old.vin[i].nSequence < nLowest)
  400. {
  401. fNewer = true;
  402. nLowest = old.vin[i].nSequence;
  403. }
  404. }
  405. }
  406. return fNewer;
  407. }
  408. bool IsCoinBase() const
  409. {
  410. return (vin.size() == 1 && vin[0].prevout.IsNull());
  411. }
  412. int GetSigOpCount() const
  413. {
  414. int n = 0;
  415. BOOST_FOREACH(const CTxIn& txin, vin)
  416. n += txin.scriptSig.GetSigOpCount();
  417. BOOST_FOREACH(const CTxOut& txout, vout)
  418. n += txout.scriptPubKey.GetSigOpCount();
  419. return n;
  420. }
  421. bool IsStandard() const
  422. {
  423. BOOST_FOREACH(const CTxIn& txin, vin)
  424. if (!txin.scriptSig.IsPushOnly())
  425. return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
  426. BOOST_FOREACH(const CTxOut& txout, vout)
  427. if (!::IsStandard(txout.scriptPubKey))
  428. return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
  429. return true;
  430. }
  431. bool IsMine() const
  432. {
  433. BOOST_FOREACH(const CTxOut& txout, vout)
  434. if (txout.IsMine())
  435. return true;
  436. return false;
  437. }
  438. bool IsFromMe() const
  439. {
  440. return (GetDebit() > 0);
  441. }
  442. int64 GetDebit() const
  443. {
  444. int64 nDebit = 0;
  445. BOOST_FOREACH(const CTxIn& txin, vin)
  446. {
  447. nDebit += txin.GetDebit();
  448. if (!MoneyRange(nDebit))
  449. throw std::runtime_error("CTransaction::GetDebit() : value out of range");
  450. }
  451. return nDebit;
  452. }
  453. int64 GetCredit() const
  454. {
  455. int64 nCredit = 0;
  456. BOOST_FOREACH(const CTxOut& txout, vout)
  457. {
  458. nCredit += txout.GetCredit();
  459. if (!MoneyRange(nCredit))
  460. throw std::runtime_error("CTransaction::GetCredit() : value out of range");
  461. }
  462. return nCredit;
  463. }
  464. int64 GetChange() const
  465. {
  466. if (IsCoinBase())
  467. return 0;
  468. int64 nChange = 0;
  469. BOOST_FOREACH(const CTxOut& txout, vout)
  470. {
  471. nChange += txout.GetChange();
  472. if (!MoneyRange(nChange))
  473. throw std::runtime_error("CTransaction::GetChange() : value out of range");
  474. }
  475. return nChange;
  476. }
  477. int64 GetValueOut() const
  478. {
  479. int64 nValueOut = 0;
  480. BOOST_FOREACH(const CTxOut& txout, vout)
  481. {
  482. nValueOut += txout.nValue;
  483. if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
  484. throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
  485. }
  486. return nValueOut;
  487. }
  488. static bool AllowFree(double dPriority)
  489. {
  490. // Large (in bytes) low-priority (new, small-coin) transactions
  491. // need a fee.
  492. return dPriority > COIN * 144 / 250;
  493. }
  494. int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true) const
  495. {
  496. // Base fee is 1 cent per kilobyte
  497. unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
  498. unsigned int nNewBlockSize = nBlockSize + nBytes;
  499. int64 nMinFee = (1 + (int64)nBytes / 1000) * MIN_TX_FEE;
  500. if (fAllowFree)
  501. {
  502. if (nBlockSize == 1)
  503. {
  504. // Transactions under 10K are free
  505. // (about 4500bc if made of 50bc inputs)
  506. if (nBytes < 10000)
  507. nMinFee = 0;
  508. }
  509. else
  510. {
  511. // Free transaction area
  512. if (nNewBlockSize < 27000)
  513. nMinFee = 0;
  514. }
  515. }
  516. // To limit dust spam, require MIN_TX_FEE if any output is less than 0.01
  517. if (nMinFee < MIN_TX_FEE)
  518. BOOST_FOREACH(const CTxOut& txout, vout)
  519. if (txout.nValue < CENT)
  520. nMinFee = MIN_TX_FEE;
  521. // Raise the price as the block approaches full
  522. if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
  523. {
  524. if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
  525. return MAX_MONEY;
  526. nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
  527. }
  528. if (!MoneyRange(nMinFee))
  529. nMinFee = MAX_MONEY;
  530. return nMinFee;
  531. }
  532. bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
  533. {
  534. CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
  535. if (!filein)
  536. return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
  537. // Read transaction
  538. if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
  539. return error("CTransaction::ReadFromDisk() : fseek failed");
  540. filein >> *this;
  541. // Return file pointer
  542. if (pfileRet)
  543. {
  544. if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
  545. return error("CTransaction::ReadFromDisk() : second fseek failed");
  546. *pfileRet = filein.release();
  547. }
  548. return true;
  549. }
  550. friend bool operator==(const CTransaction& a, const CTransaction& b)
  551. {
  552. return (a.nVersion == b.nVersion &&
  553. a.vin == b.vin &&
  554. a.vout == b.vout &&
  555. a.nLockTime == b.nLockTime);
  556. }
  557. friend bool operator!=(const CTransaction& a, const CTransaction& b)
  558. {
  559. return !(a == b);
  560. }
  561. std::string ToString() const
  562. {
  563. std::string str;
  564. str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
  565. GetHash().ToString().substr(0,10).c_str(),
  566. nVersion,
  567. vin.size(),
  568. vout.size(),
  569. nLockTime);
  570. for (int i = 0; i < vin.size(); i++)
  571. str += " " + vin[i].ToString() + "\n";
  572. for (int i = 0; i < vout.size(); i++)
  573. str += " " + vout[i].ToString() + "\n";
  574. return str;
  575. }
  576. void print() const
  577. {
  578. printf("%s", ToString().c_str());
  579. }
  580. bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
  581. bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
  582. bool ReadFromDisk(COutPoint prevout);
  583. bool DisconnectInputs(CTxDB& txdb);
  584. bool ConnectInputs(CTxDB& txdb, std::map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
  585. CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
  586. bool ClientConnectInputs();
  587. bool CheckTransaction() const;
  588. bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
  589. bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
  590. {
  591. CTxDB txdb("r");
  592. return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
  593. }
  594. protected:
  595. bool AddToMemoryPoolUnchecked();
  596. public:
  597. bool RemoveFromMemoryPool();
  598. };
  599. //
  600. // A transaction with a merkle branch linking it to the block chain
  601. //
  602. class CMerkleTx : public CTransaction
  603. {
  604. public:
  605. uint256 hashBlock;
  606. std::vector<uint256> vMerkleBranch;
  607. int nIndex;
  608. // memory only
  609. mutable char fMerkleVerified;
  610. CMerkleTx()
  611. {
  612. Init();
  613. }
  614. CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
  615. {
  616. Init();
  617. }
  618. void Init()
  619. {
  620. hashBlock = 0;
  621. nIndex = -1;
  622. fMerkleVerified = false;
  623. }
  624. IMPLEMENT_SERIALIZE
  625. (
  626. nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
  627. nVersion = this->nVersion;
  628. READWRITE(hashBlock);
  629. READWRITE(vMerkleBranch);
  630. READWRITE(nIndex);
  631. )
  632. int SetMerkleBranch(const CBlock* pblock=NULL);
  633. int GetDepthInMainChain(int& nHeightRet) const;
  634. int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
  635. bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
  636. int GetBlocksToMaturity() const;
  637. bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
  638. bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
  639. };
  640. //
  641. // A transaction with a bunch of additional info that only the owner cares
  642. // about. It includes any unrecorded transactions needed to link it back
  643. // to the block chain.
  644. //
  645. class CWalletTx : public CMerkleTx
  646. {
  647. public:
  648. std::vector<CMerkleTx> vtxPrev;
  649. std::map<std::string, std::string> mapValue;
  650. std::vector<std::pair<std::string, std::string> > vOrderForm;
  651. unsigned int fTimeReceivedIsTxTime;
  652. unsigned int nTimeReceived; // time received by this node
  653. char fFromMe;
  654. std::string strFromAccount;
  655. std::vector<char> vfSpent;
  656. // memory only
  657. mutable char fDebitCached;
  658. mutable char fCreditCached;
  659. mutable char fAvailableCreditCached;
  660. mutable char fChangeCached;
  661. mutable int64 nDebitCached;
  662. mutable int64 nCreditCached;
  663. mutable int64 nAvailableCreditCached;
  664. mutable int64 nChangeCached;
  665. // memory only UI hints
  666. mutable unsigned int nTimeDisplayed;
  667. mutable int nLinesDisplayed;
  668. mutable char fConfirmedDisplayed;
  669. CWalletTx()
  670. {
  671. Init();
  672. }
  673. CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
  674. {
  675. Init();
  676. }
  677. CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
  678. {
  679. Init();
  680. }
  681. void Init()
  682. {
  683. vtxPrev.clear();
  684. mapValue.clear();
  685. vOrderForm.clear();
  686. fTimeReceivedIsTxTime = false;
  687. nTimeReceived = 0;
  688. fFromMe = false;
  689. strFromAccount.clear();
  690. vfSpent.clear();
  691. fDebitCached = false;
  692. fCreditCached = false;
  693. fAvailableCreditCached = false;
  694. fChangeCached = false;
  695. nDebitCached = 0;
  696. nCreditCached = 0;
  697. nAvailableCreditCached = 0;
  698. nChangeCached = 0;
  699. nTimeDisplayed = 0;
  700. nLinesDisplayed = 0;
  701. fConfirmedDisplayed = false;
  702. }
  703. IMPLEMENT_SERIALIZE
  704. (
  705. CWalletTx* pthis = const_cast<CWalletTx*>(this);
  706. if (fRead)
  707. pthis->Init();
  708. char fSpent = false;
  709. if (!fRead)
  710. {
  711. pthis->mapValue["fromaccount"] = pthis->strFromAccount;
  712. std::string str;
  713. BOOST_FOREACH(char f, vfSpent)
  714. {
  715. str += (f ? '1' : '0');
  716. if (f)
  717. fSpent = true;
  718. }
  719. pthis->mapValue["spent"] = str;
  720. }
  721. nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
  722. READWRITE(vtxPrev);
  723. READWRITE(mapValue);
  724. READWRITE(vOrderForm);
  725. READWRITE(fTimeReceivedIsTxTime);
  726. READWRITE(nTimeReceived);
  727. READWRITE(fFromMe);
  728. READWRITE(fSpent);
  729. if (fRead)
  730. {
  731. pthis->strFromAccount = pthis->mapValue["fromaccount"];
  732. if (mapValue.count("spent"))
  733. BOOST_FOREACH(char c, pthis->mapValue["spent"])
  734. pthis->vfSpent.push_back(c != '0');
  735. else
  736. pthis->vfSpent.assign(vout.size(), fSpent);
  737. }
  738. pthis->mapValue.erase("fromaccount");
  739. pthis->mapValue.erase("version");
  740. pthis->mapValue.erase("spent");
  741. )
  742. // marks certain txout's as spent
  743. // returns true if any update took place
  744. bool UpdateSpent(const std::vector<char>& vfNewSpent)
  745. {
  746. bool fReturn = false;
  747. for (int i=0; i < vfNewSpent.size(); i++)
  748. {
  749. if (i == vfSpent.size())
  750. break;
  751. if (vfNewSpent[i] && !vfSpent[i])
  752. {
  753. vfSpent[i] = true;
  754. fReturn = true;
  755. fAvailableCreditCached = false;
  756. }
  757. }
  758. return fReturn;
  759. }
  760. void MarkDirty()
  761. {
  762. fCreditCached = false;
  763. fAvailableCreditCached = false;
  764. fDebitCached = false;
  765. fChangeCached = false;
  766. }
  767. void MarkSpent(unsigned int nOut)
  768. {
  769. if (nOut >= vout.size())
  770. throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
  771. vfSpent.resize(vout.size());
  772. if (!vfSpent[nOut])
  773. {
  774. vfSpent[nOut] = true;
  775. fAvailableCreditCached = false;
  776. }
  777. }
  778. bool IsSpent(unsigned int nOut) const
  779. {
  780. if (nOut >= vout.size())
  781. throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
  782. if (nOut >= vfSpent.size())
  783. return false;
  784. return (!!vfSpent[nOut]);
  785. }
  786. int64 GetDebit() const
  787. {
  788. if (vin.empty())
  789. return 0;
  790. if (fDebitCached)
  791. return nDebitCached;
  792. nDebitCached = CTransaction::GetDebit();
  793. fDebitCached = true;
  794. return nDebitCached;
  795. }
  796. int64 GetCredit(bool fUseCache=true) const
  797. {
  798. // Must wait until coinbase is safely deep enough in the chain before valuing it
  799. if (IsCoinBase() && GetBlocksToMaturity() > 0)
  800. return 0;
  801. // GetBalance can assume transactions in mapWallet won't change
  802. if (fUseCache && fCreditCached)
  803. return nCreditCached;
  804. nCreditCached = CTransaction::GetCredit();
  805. fCreditCached = true;
  806. return nCreditCached;
  807. }
  808. int64 GetAvailableCredit(bool fUseCache=true) const
  809. {
  810. // Must wait until coinbase is safely deep enough in the chain before valuing it
  811. if (IsCoinBase() && GetBlocksToMaturity() > 0)
  812. return 0;
  813. if (fUseCache && fAvailableCreditCached)
  814. return nAvailableCreditCached;
  815. int64 nCredit = 0;
  816. for (int i = 0; i < vout.size(); i++)
  817. {
  818. if (!IsSpent(i))
  819. {
  820. const CTxOut &txout = vout[i];
  821. nCredit += txout.GetCredit();
  822. if (!MoneyRange(nCredit))
  823. throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
  824. }
  825. }
  826. nAvailableCreditCached = nCredit;
  827. fAvailableCreditCached = true;
  828. return nCredit;
  829. }
  830. int64 GetChange() const
  831. {
  832. if (fChangeCached)
  833. return nChangeCached;
  834. nChangeCached = CTransaction::GetChange();
  835. fChangeCached = true;
  836. return nChangeCached;
  837. }
  838. void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<std::string /* address */, int64> >& listReceived,
  839. std::list<std::pair<std::string /* address */, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
  840. void GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
  841. int64& nSent, int64& nFee) const;
  842. bool IsFromMe() const
  843. {
  844. return (GetDebit() > 0);
  845. }
  846. bool IsConfirmed() const
  847. {
  848. // Quick answer in most cases
  849. if (!IsFinal())
  850. return false;
  851. if (GetDepthInMainChain() >= 1)
  852. return true;
  853. if (!IsFromMe()) // using wtx's cached debit
  854. return false;
  855. // If no confirmations but it's from us, we can still
  856. // consider it confirmed if all dependencies are confirmed
  857. std::map<uint256, const CMerkleTx*> mapPrev;
  858. std::vector<const CMerkleTx*> vWorkQueue;
  859. vWorkQueue.reserve(vtxPrev.size()+1);
  860. vWorkQueue.push_back(this);
  861. for (int i = 0; i < vWorkQueue.size(); i++)
  862. {
  863. const CMerkleTx* ptx = vWorkQueue[i];
  864. if (!ptx->IsFinal())
  865. return false;
  866. if (ptx->GetDepthInMainChain() >= 1)
  867. continue;
  868. if (!ptx->IsFromMe())
  869. return false;
  870. if (mapPrev.empty())
  871. BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
  872. mapPrev[tx.GetHash()] = &tx;
  873. BOOST_FOREACH(const CTxIn& txin, ptx->vin)
  874. {
  875. if (!mapPrev.count(txin.prevout.hash))
  876. return false;
  877. vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
  878. }
  879. }
  880. return true;
  881. }
  882. bool WriteToDisk()
  883. {
  884. return CWalletDB().WriteTx(GetHash(), *this);
  885. }
  886. int64 GetTxTime() const;
  887. int GetRequestCount() const;
  888. void AddSupportingTransactions(CTxDB& txdb);
  889. bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
  890. bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
  891. void RelayWalletTransaction(CTxDB& txdb);
  892. void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
  893. };
  894. //
  895. // A txdb record that contains the disk location of a transaction and the
  896. // locations of transactions that spend its outputs. vSpent is really only
  897. // used as a flag, but having the location is very helpful for debugging.
  898. //
  899. class CTxIndex
  900. {
  901. public:
  902. CDiskTxPos pos;
  903. std::vector<CDiskTxPos> vSpent;
  904. CTxIndex()
  905. {
  906. SetNull();
  907. }
  908. CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
  909. {
  910. pos = posIn;
  911. vSpent.resize(nOutputs);
  912. }
  913. IMPLEMENT_SERIALIZE
  914. (
  915. if (!(nType & SER_GETHASH))
  916. READWRITE(nVersion);
  917. READWRITE(pos);
  918. READWRITE(vSpent);
  919. )
  920. void SetNull()
  921. {
  922. pos.SetNull();
  923. vSpent.clear();
  924. }
  925. bool IsNull()
  926. {
  927. return pos.IsNull();
  928. }
  929. friend bool operator==(const CTxIndex& a, const CTxIndex& b)
  930. {
  931. return (a.pos == b.pos &&
  932. a.vSpent == b.vSpent);
  933. }
  934. friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
  935. {
  936. return !(a == b);
  937. }
  938. int GetDepthInMainChain() const;
  939. };
  940. //
  941. // Nodes collect new transactions into a block, hash them into a hash tree,
  942. // and scan through nonce values to make the block's hash satisfy proof-of-work
  943. // requirements. When they solve the proof-of-work, they broadcast the block
  944. // to everyone and the block is added to the block chain. The first transaction
  945. // in the block is a special one that creates a new coin owned by the creator
  946. // of the block.
  947. //
  948. // Blocks are appended to blk0001.dat files on disk. Their location on disk
  949. // is indexed by CBlockIndex objects in memory.
  950. //
  951. class CBlock
  952. {
  953. public:
  954. // header
  955. int nVersion;
  956. uint256 hashPrevBlock;
  957. uint256 hashMerkleRoot;
  958. unsigned int nTime;
  959. unsigned int nBits;
  960. unsigned int nNonce;
  961. // network and disk
  962. std::vector<CTransaction> vtx;
  963. // memory only
  964. mutable std::vector<uint256> vMerkleTree;
  965. CBlock()
  966. {
  967. SetNull();
  968. }
  969. IMPLEMENT_SERIALIZE
  970. (
  971. READWRITE(this->nVersion);
  972. nVersion = this->nVersion;
  973. READWRITE(hashPrevBlock);
  974. READWRITE(hashMerkleRoot);
  975. READWRITE(nTime);
  976. READWRITE(nBits);
  977. READWRITE(nNonce);
  978. // ConnectBlock depends on vtx being last so it can calculate offset
  979. if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
  980. READWRITE(vtx);
  981. else if (fRead)
  982. const_cast<CBlock*>(this)->vtx.clear();
  983. )
  984. void SetNull()
  985. {
  986. nVersion = 1;
  987. hashPrevBlock = 0;
  988. hashMerkleRoot = 0;
  989. nTime = 0;
  990. nBits = 0;
  991. nNonce = 0;
  992. vtx.clear();
  993. vMerkleTree.clear();
  994. }
  995. bool IsNull() const
  996. {
  997. return (nBits == 0);
  998. }
  999. uint256 GetHash() const
  1000. {
  1001. return Hash(BEGIN(nVersion), END(nNonce));
  1002. }
  1003. int64 GetBlockTime() const
  1004. {
  1005. return (int64)nTime;
  1006. }
  1007. int GetSigOpCount() const
  1008. {
  1009. int n = 0;
  1010. BOOST_FOREACH(const CTransaction& tx, vtx)
  1011. n += tx.GetSigOpCount();
  1012. return n;
  1013. }
  1014. uint256 BuildMerkleTree() const
  1015. {
  1016. vMerkleTree.clear();
  1017. BOOST_FOREACH(const CTransaction& tx, vtx)
  1018. vMerkleTree.push_back(tx.GetHash());
  1019. int j = 0;
  1020. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  1021. {
  1022. for (int i = 0; i < nSize; i += 2)
  1023. {
  1024. int i2 = std::min(i+1, nSize-1);
  1025. vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
  1026. BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
  1027. }
  1028. j += nSize;
  1029. }
  1030. return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
  1031. }
  1032. std::vector<uint256> GetMerkleBranch(int nIndex) const
  1033. {
  1034. if (vMerkleTree.empty())
  1035. BuildMerkleTree();
  1036. std::vector<uint256> vMerkleBranch;
  1037. int j = 0;
  1038. for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
  1039. {
  1040. int i = std::min(nIndex^1, nSize-1);
  1041. vMerkleBranch.push_back(vMerkleTree[j+i]);
  1042. nIndex >>= 1;
  1043. j += nSize;
  1044. }
  1045. return vMerkleBranch;
  1046. }
  1047. static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
  1048. {
  1049. if (nIndex == -1)
  1050. return 0;
  1051. BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
  1052. {
  1053. if (nIndex & 1)
  1054. hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
  1055. else
  1056. hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
  1057. nIndex >>= 1;
  1058. }
  1059. return hash;
  1060. }
  1061. bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
  1062. {
  1063. // Open history file to append
  1064. CAutoFile fileout = AppendBlockFile(nFileRet);
  1065. if (!fileout)
  1066. return error("CBlock::WriteToDisk() : AppendBlockFile failed");
  1067. // Write index header
  1068. unsigned int nSize = fileout.GetSerializeSize(*this);
  1069. fileout << FLATDATA(pchMessageStart) << nSize;
  1070. // Write block
  1071. nBlockPosRet = ftell(fileout);
  1072. if (nBlockPosRet == -1)
  1073. return error("CBlock::WriteToDisk() : ftell failed");
  1074. fileout << *this;
  1075. // Flush stdio buffers and commit to disk before returning
  1076. fflush(fileout);
  1077. if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
  1078. {
  1079. #ifdef __WXMSW__
  1080. _commit(_fileno(fileout));
  1081. #else
  1082. fsync(fileno(fileout));
  1083. #endif
  1084. }
  1085. return true;
  1086. }
  1087. bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
  1088. {
  1089. SetNull();
  1090. // Open history file to read
  1091. CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
  1092. if (!filein)
  1093. return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
  1094. if (!fReadTransactions)
  1095. filein.nType |= SER_BLOCKHEADERONLY;
  1096. // Read block
  1097. filein >> *this;
  1098. // Check the header
  1099. if (!CheckProofOfWork(GetHash(), nBits))
  1100. return error("CBlock::ReadFromDisk() : errors in block header");
  1101. return true;
  1102. }
  1103. void print() const
  1104. {
  1105. printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
  1106. GetHash().ToString().substr(0,20).c_str(),
  1107. nVersion,
  1108. hashPrevBlock.ToString().substr(0,20).c_str(),
  1109. hashMerkleRoot.ToString().substr(0,10).c_str(),
  1110. nTime, nBits, nNonce,
  1111. vtx.size());
  1112. for (int i = 0; i < vtx.size(); i++)
  1113. {
  1114. printf(" ");
  1115. vtx[i].print();
  1116. }
  1117. printf(" vMerkleTree: ");
  1118. for (int i = 0; i < vMerkleTree.size(); i++)
  1119. printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
  1120. printf("\n");
  1121. }
  1122. bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
  1123. bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
  1124. bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
  1125. bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
  1126. bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
  1127. bool CheckBlock() const;
  1128. bool AcceptBlock();
  1129. };
  1130. //
  1131. // The block chain is a tree shaped structure starting with the
  1132. // genesis block at the root, with each block potentially having multiple
  1133. // candidates to be the next block. pprev and pnext link a path through the
  1134. // main/longest chain. A blockindex may have multiple pprev pointing back
  1135. // to it, but pnext will only point forward to the longest branch, or will
  1136. // be null if the block is not part of the longest chain.
  1137. //
  1138. class CBlockIndex
  1139. {
  1140. public:
  1141. const uint256* phashBlock;
  1142. CBlockIndex* pprev;
  1143. CBlockIndex* pnext;
  1144. unsigned int nFile;
  1145. unsigned int nBlockPos;
  1146. int nHeight;
  1147. CBigNum bnChainWork;
  1148. // block header
  1149. int nVersion;
  1150. uint256 hashMerkleRoot;
  1151. unsigned int nTime;
  1152. unsigned int nBits;
  1153. unsigned int nNonce;
  1154. CBlockIndex()
  1155. {
  1156. phashBlock = NULL;
  1157. pprev = NULL;
  1158. pnext = NULL;
  1159. nFile = 0;
  1160. nBlockPos = 0;
  1161. nHeight = 0;
  1162. bnChainWork = 0;
  1163. nVersion = 0;
  1164. hashMerkleRoot = 0;
  1165. nTime = 0;
  1166. nBits = 0;
  1167. nNonce = 0;
  1168. }
  1169. CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
  1170. {
  1171. phashBlock = NULL;
  1172. pprev = NULL;
  1173. pnext = NULL;
  1174. nFile = nFileIn;
  1175. nBlockPos = nBlockPosIn;
  1176. nHeight = 0;
  1177. bnChainWork = 0;
  1178. nVersion = block.nVersion;
  1179. hashMerkleRoot = block.hashMerkleRoot;
  1180. nTime = block.nTime;
  1181. nBits = block.nBits;
  1182. nNonce = block.nNonce;
  1183. }
  1184. CBlock GetBlockHeader() const
  1185. {
  1186. CBlock block;
  1187. block.nVersion = nVersion;
  1188. if (pprev)
  1189. block.hashPrevBlock = pprev->GetBlockHash();
  1190. block.hashMerkleRoot = hashMerkleRoot;
  1191. block.nTime = nTime;
  1192. block.nBits = nBits;
  1193. block.nNonce = nNonce;
  1194. return block;
  1195. }
  1196. uint256 GetBlockHash() const
  1197. {
  1198. return *phashBlock;
  1199. }
  1200. int64 GetBlockTime() const
  1201. {
  1202. return (int64)nTime;
  1203. }
  1204. CBigNum GetBlockWork() const
  1205. {
  1206. CBigNum bnTarget;
  1207. bnTarget.SetCompact(nBits);
  1208. if (bnTarget <= 0)
  1209. return 0;
  1210. return (CBigNum(1)<<256) / (bnTarget+1);
  1211. }
  1212. bool IsInMainChain() const
  1213. {
  1214. return (pnext || this == pindexBest);
  1215. }
  1216. bool CheckIndex() const
  1217. {
  1218. return CheckProofOfWork(GetBlockHash(), nBits);
  1219. }
  1220. bool EraseBlockFromDisk()
  1221. {
  1222. // Open history file
  1223. CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
  1224. if (!fileout)
  1225. return false;
  1226. // Overwrite with empty null block
  1227. CBlock block;
  1228. block.SetNull();
  1229. fileout << block;
  1230. return true;
  1231. }
  1232. enum { nMedianTimeSpan=11 };
  1233. int64 GetMedianTimePast() const
  1234. {
  1235. int64 pmedian[nMedianTimeSpan];
  1236. int64* pbegin = &pmedian[nMedianTimeSpan];
  1237. int64* pend = &pmedian[nMedianTimeSpan];
  1238. const CBlockIndex* pindex = this;
  1239. for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
  1240. *(--pbegin) = pindex->GetBlockTime();
  1241. std::sort(pbegin, pend);
  1242. return pbegin[(pend - pbegin)/2];
  1243. }
  1244. int64 GetMedianTime() const
  1245. {
  1246. const CBlockIndex* pindex = this;
  1247. for (int i = 0; i < nMedianTimeSpan/2; i++)
  1248. {
  1249. if (!pindex->pnext)
  1250. return GetBlockTime();
  1251. pindex = pindex->pnext;
  1252. }
  1253. return pindex->GetMedianTimePast();
  1254. }
  1255. std::string ToString() const
  1256. {
  1257. return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
  1258. pprev, pnext, nFile, nBlockPos, nHeight,
  1259. hashMerkleRoot.ToString().substr(0,10).c_str(),
  1260. GetBlockHash().ToString().substr(0,20).c_str());
  1261. }
  1262. void print() const
  1263. {
  1264. printf("%s\n", ToString().c_str());
  1265. }
  1266. };
  1267. //
  1268. // Used to marshal pointers into hashes for db storage.
  1269. //
  1270. class CDiskBlockIndex : public CBlockIndex
  1271. {
  1272. public:
  1273. uint256 hashPrev;
  1274. uint256 hashNext;
  1275. CDiskBlockIndex()
  1276. {
  1277. hashPrev = 0;
  1278. hashNext = 0;
  1279. }
  1280. explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
  1281. {
  1282. hashPrev = (pprev ? pprev->GetBlockHash() : 0);
  1283. hashNext = (pnext ? pnext->GetBlockHash() : 0);
  1284. }
  1285. IMPLEMENT_SERIALIZE
  1286. (
  1287. if (!(nType & SER_GETHASH))
  1288. READWRITE(nVersion);
  1289. READWRITE(hashNext);
  1290. READWRITE(nFile);
  1291. READWRITE(nBlockPos);
  1292. READWRITE(nHeight);
  1293. // block header
  1294. READWRITE(this->nVersion);
  1295. READWRITE(hashPrev);
  1296. READWRITE(hashMerkleRoot);
  1297. READWRITE(nTime);
  1298. READWRITE(nBits);
  1299. READWRITE(nNonce);
  1300. )
  1301. uint256 GetBlockHash() const
  1302. {
  1303. CBlock block;
  1304. block.nVersion = nVersion;
  1305. block.hashPrevBlock = hashPrev;
  1306. block.hashMerkleRoot = hashMerkleRoot;
  1307. block.nTime = nTime;
  1308. block.nBits = nBits;
  1309. block.nNonce = nNonce;
  1310. return block.GetHash();
  1311. }
  1312. std::string ToString() const
  1313. {
  1314. std::string str = "CDiskBlockIndex(";
  1315. str += CBlockIndex::ToString();
  1316. str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
  1317. GetBlockHash().ToString().c_str(),
  1318. hashPrev.ToString().substr(0,20).c_str(),
  1319. hashNext.ToString().substr(0,20).c_str());
  1320. return str;
  1321. }
  1322. void print() const
  1323. {
  1324. printf("%s\n", ToString().c_str());
  1325. }
  1326. };
  1327. //
  1328. // Describes a place in the block chain to another node such that if the
  1329. // other node doesn't have the same branch, it can find a recent common trunk.
  1330. // The further back it is, the further before the fork it may be.
  1331. //
  1332. class CBlockLocator
  1333. {
  1334. protected:
  1335. std::vector<uint256> vHave;
  1336. public:
  1337. CBlockLocator()
  1338. {
  1339. }
  1340. explicit CBlockLocator(const CBlockIndex* pindex)
  1341. {
  1342. Set(pindex);
  1343. }
  1344. explicit CBlockLocator(uint256 hashBlock)
  1345. {
  1346. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  1347. if (mi != mapBlockIndex.end())
  1348. Set((*mi).second);
  1349. }
  1350. IMPLEMENT_SERIALIZE
  1351. (
  1352. if (!(nType & SER_GETHASH))
  1353. READWRITE(nVersion);
  1354. READWRITE(vHave);
  1355. )
  1356. void SetNull()
  1357. {
  1358. vHave.clear();
  1359. }
  1360. bool IsNull()
  1361. {
  1362. return vHave.empty();
  1363. }
  1364. void Set(const CBlockIndex* pindex)
  1365. {
  1366. vHave.clear();
  1367. int nStep = 1;
  1368. while (pindex)
  1369. {
  1370. vHave.push_back(pindex->GetBlockHash());
  1371. // Exponentially larger steps back
  1372. for (int i = 0; pindex && i < nStep; i++)
  1373. pindex = pindex->pprev;
  1374. if (vHave.size() > 10)
  1375. nStep *= 2;
  1376. }
  1377. vHave.push_back(hashGenesisBlock);
  1378. }
  1379. int GetDistanceBack()
  1380. {
  1381. // Retrace how far back it was in the sender's branch
  1382. int nDistance = 0;
  1383. int nStep = 1;
  1384. BOOST_FOREACH(const uint256& hash, vHave)
  1385. {
  1386. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1387. if (mi != mapBlockIndex.end())
  1388. {
  1389. CBlockIndex* pindex = (*mi).second;
  1390. if (pindex->IsInMainChain())
  1391. return nDistance;
  1392. }
  1393. nDistance += nStep;
  1394. if (nDistance > 10)
  1395. nStep *= 2;
  1396. }
  1397. return nDistance;
  1398. }
  1399. CBlockIndex* GetBlockIndex()
  1400. {
  1401. // Find the first block the caller has in the main chain
  1402. BOOST_FOREACH(const uint256& hash, vHave)
  1403. {
  1404. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1405. if (mi != mapBlockIndex.end())
  1406. {
  1407. CBlockIndex* pindex = (*mi).second;
  1408. if (pindex->IsInMainChain())
  1409. return pindex;
  1410. }
  1411. }
  1412. return pindexGenesisBlock;
  1413. }
  1414. uint256 GetBlockHash()
  1415. {
  1416. // Find the first block the caller has in the main chain
  1417. BOOST_FOREACH(const uint256& hash, vHave)
  1418. {
  1419. std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  1420. if (mi != mapBlockIndex.end())
  1421. {
  1422. CBlockIndex* pindex = (*mi).second;
  1423. if (pindex->IsInMainChain())
  1424. return hash;
  1425. }
  1426. }
  1427. return hashGenesisBlock;
  1428. }
  1429. int GetHeight()
  1430. {
  1431. CBlockIndex* pindex = GetBlockIndex();
  1432. if (!pindex)
  1433. return 0;
  1434. return pindex->nHeight;
  1435. }
  1436. };
  1437. //
  1438. // Private key that includes an expiration date in case it never gets used.
  1439. //
  1440. class CWalletKey
  1441. {
  1442. public:
  1443. CPrivKey vchPrivKey;
  1444. int64 nTimeCreated;
  1445. int64 nTimeExpires;
  1446. std::string strComment;
  1447. //// todo: add something to note what created it (user, getnewaddress, change)
  1448. //// maybe should have a map<string, string> property map
  1449. CWalletKey(int64 nExpires=0)
  1450. {
  1451. nTimeCreated = (nExpires ? GetTime() : 0);
  1452. nTimeExpires = nExpires;
  1453. }
  1454. IMPLEMENT_SERIALIZE
  1455. (
  1456. if (!(nType & SER_GETHASH))
  1457. READWRITE(nVersion);
  1458. READWRITE(vchPrivKey);
  1459. READWRITE(nTimeCreated);
  1460. READWRITE(nTimeExpires);
  1461. READWRITE(strComment);
  1462. )
  1463. };
  1464. //
  1465. // Account information.
  1466. // Stored in wallet with key "acc"+string account name
  1467. //
  1468. class CAccount
  1469. {
  1470. public:
  1471. std::vector<unsigned char> vchPubKey;
  1472. CAccount()
  1473. {
  1474. SetNull();
  1475. }
  1476. void SetNull()
  1477. {
  1478. vchPubKey.clear();
  1479. }
  1480. IMPLEMENT_SERIALIZE
  1481. (
  1482. if (!(nType & SER_GETHASH))
  1483. READWRITE(nVersion);
  1484. READWRITE(vchPubKey);
  1485. )
  1486. };
  1487. //
  1488. // Internal transfers.
  1489. // Database key is acentry<account><counter>
  1490. //
  1491. class CAccountingEntry
  1492. {
  1493. public:
  1494. std::string strAccount;
  1495. int64 nCreditDebit;
  1496. int64 nTime;
  1497. std::string strOtherAccount;
  1498. std::string strComment;
  1499. CAccountingEntry()
  1500. {
  1501. SetNull();
  1502. }
  1503. void SetNull()
  1504. {
  1505. nCreditDebit = 0;
  1506. nTime = 0;
  1507. strAccount.clear();
  1508. strOtherAccount.clear();
  1509. strComment.clear();
  1510. }
  1511. IMPLEMENT_SERIALIZE
  1512. (
  1513. if (!(nType & SER_GETHASH))
  1514. READWRITE(nVersion);
  1515. // Note: strAccount is serialized as part of the key, not here.
  1516. READWRITE(nCreditDebit);
  1517. READWRITE(nTime);
  1518. READWRITE(strOtherAccount);
  1519. READWRITE(strComment);
  1520. )
  1521. };
  1522. //
  1523. // Alerts are for notifying old versions if they become too obsolete and
  1524. // need to upgrade. The message is displayed in the status bar.
  1525. // Alert messages are broadcast as a vector of signed data. Unserializing may
  1526. // not read the entire buffer if the alert is for a newer version, but older
  1527. // versions can still relay the original data.
  1528. //
  1529. class CUnsignedAlert
  1530. {
  1531. public:
  1532. int nVersion;
  1533. int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
  1534. int64 nExpiration;
  1535. int nID;
  1536. int nCancel;
  1537. std::set<int> setCancel;
  1538. int nMinVer; // lowest version inclusive
  1539. int nMaxVer; // highest version inclusive
  1540. std::set<std::string> setSubVer; // empty matches all
  1541. int nPriority;
  1542. // Actions
  1543. std::string strComment;
  1544. std::string strStatusBar;
  1545. std::string strReserved;
  1546. IMPLEMENT_SERIALIZE
  1547. (
  1548. READWRITE(this->nVersion);
  1549. nVersion = this->nVersion;
  1550. READWRITE(nRelayUntil);
  1551. READWRITE(nExpiration);
  1552. READWRITE(nID);
  1553. READWRITE(nCancel);
  1554. READWRITE(setCancel);
  1555. READWRITE(nMinVer);
  1556. READWRITE(nMaxVer);
  1557. READWRITE(setSubVer);
  1558. READWRITE(nPriority);
  1559. READWRITE(strComment);
  1560. READWRITE(strStatusBar);
  1561. READWRITE(strReserved);
  1562. )
  1563. void SetNull()
  1564. {
  1565. nVersion = 1;
  1566. nRelayUntil = 0;
  1567. nExpiration = 0;
  1568. nID = 0;
  1569. nCancel = 0;
  1570. setCancel.clear();
  1571. nMinVer = 0;
  1572. nMaxVer = 0;
  1573. setSubVer.clear();
  1574. nPriority = 0;
  1575. strComment.clear();
  1576. strStatusBar.clear();
  1577. strReserved.clear();
  1578. }
  1579. std::string ToString() const
  1580. {
  1581. std::string strSetCancel;
  1582. BOOST_FOREACH(int n, setCancel)
  1583. strSetCancel += strprintf("%d ", n);
  1584. std::string strSetSubVer;
  1585. BOOST_FOREACH(std::string str, setSubVer)
  1586. strSetSubVer += "\"" + str + "\" ";
  1587. return strprintf(
  1588. "CAlert(\n"
  1589. " nVersion = %d\n"
  1590. " nRelayUntil = %"PRI64d"\n"
  1591. " nExpiration = %"PRI64d"\n"
  1592. " nID = %d\n"
  1593. " nCancel = %d\n"
  1594. " setCancel = %s\n"
  1595. " nMinVer = %d\n"
  1596. " nMaxVer = %d\n"
  1597. " setSubVer = %s\n"
  1598. " nPriority = %d\n"
  1599. " strComment = \"%s\"\n"
  1600. " strStatusBar = \"%s\"\n"
  1601. ")\n",
  1602. nVersion,
  1603. nRelayUntil,
  1604. nExpiration,
  1605. nID,
  1606. nCancel,
  1607. strSetCancel.c_str(),
  1608. nMinVer,
  1609. nMaxVer,
  1610. strSetSubVer.c_str(),
  1611. nPriority,
  1612. strComment.c_str(),
  1613. strStatusBar.c_str());
  1614. }
  1615. void print() const
  1616. {
  1617. printf("%s", ToString().c_str());
  1618. }
  1619. };
  1620. class CAlert : public CUnsignedAlert
  1621. {
  1622. public:
  1623. std::vector<unsigned char> vchMsg;
  1624. std::vector<unsigned char> vchSig;
  1625. CAlert()
  1626. {
  1627. SetNull();
  1628. }
  1629. IMPLEMENT_SERIALIZE
  1630. (
  1631. READWRITE(vchMsg);
  1632. READWRITE(vchSig);
  1633. )
  1634. void SetNull()
  1635. {
  1636. CUnsignedAlert::SetNull();
  1637. vchMsg.clear();
  1638. vchSig.clear();
  1639. }
  1640. bool IsNull() const
  1641. {
  1642. return (nExpiration == 0);
  1643. }
  1644. uint256 GetHash() const
  1645. {
  1646. return SerializeHash(*this);
  1647. }
  1648. bool IsInEffect() const
  1649. {
  1650. return (GetAdjustedTime() < nExpiration);
  1651. }
  1652. bool Cancels(const CAlert& alert) const
  1653. {
  1654. if (!IsInEffect())
  1655. return false; // this was a no-op before 31403
  1656. return (alert.nID <= nCancel || setCancel.count(alert.nID));
  1657. }
  1658. bool AppliesTo(int nVersion, std::string strSubVerIn) const
  1659. {
  1660. return (IsInEffect() &&
  1661. nMinVer <= nVersion && nVersion <= nMaxVer &&
  1662. (setSubVer.empty() || setSubVer.count(strSubVerIn)));
  1663. }
  1664. bool AppliesToMe() const
  1665. {
  1666. return AppliesTo(VERSION, ::pszSubVer);
  1667. }
  1668. bool RelayTo(CNode* pnode) const
  1669. {
  1670. if (!IsInEffect())
  1671. return false;
  1672. // returns true if wasn't already contained in the set
  1673. if (pnode->setKnown.insert(GetHash()).second)
  1674. {
  1675. if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
  1676. AppliesToMe() ||
  1677. GetAdjustedTime() < nRelayUntil)
  1678. {
  1679. pnode->PushMessage("alert", *this);
  1680. return true;
  1681. }
  1682. }
  1683. return false;
  1684. }
  1685. bool CheckSignature()
  1686. {
  1687. CKey key;
  1688. if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
  1689. return error("CAlert::CheckSignature() : SetPubKey failed");
  1690. if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
  1691. return error("CAlert::CheckSignature() : verify signature failed");
  1692. // Now unserialize the data
  1693. CDataStream sMsg(vchMsg);
  1694. sMsg >> *(CUnsignedAlert*)this;
  1695. return true;
  1696. }
  1697. bool ProcessAlert();
  1698. };
  1699. extern std::map<uint256, CTransaction> mapTransactions;
  1700. extern std::map<uint256, CWalletTx> mapWallet;
  1701. extern std::vector<uint256> vWalletUpdated;
  1702. extern CCriticalSection cs_mapWallet;
  1703. extern std::map<std::vector<unsigned char>, CPrivKey> mapKeys;
  1704. extern std::map<uint160, std::vector<unsigned char> > mapPubKeys;
  1705. extern CCriticalSection cs_mapKeys;
  1706. extern CKey keyUser;
  1707. #endif