PageRenderTime 57ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main.cpp

https://gitlab.com/intersango/bitcoind
C++ | 3112 lines | 2247 code | 518 blank | 347 comment | 631 complexity | 4e1b29ec025e8891647bb4485e5fb2cf MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  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. #include "headers.h"
  5. #include "db.h"
  6. #include "net.h"
  7. #include "init.h"
  8. #include "cryptopp/sha.h"
  9. #include <boost/filesystem.hpp>
  10. #include <boost/filesystem/fstream.hpp>
  11. using namespace std;
  12. using namespace boost;
  13. //
  14. // Global state
  15. //
  16. CCriticalSection cs_setpwalletRegistered;
  17. set<CWallet*> setpwalletRegistered;
  18. CCriticalSection cs_main;
  19. CCriticalSection cs_mapPubKeys;
  20. map<uint160, vector<unsigned char> > mapPubKeys;
  21. map<uint256, CTransaction> mapTransactions;
  22. CCriticalSection cs_mapTransactions;
  23. unsigned int nTransactionsUpdated = 0;
  24. map<COutPoint, CInPoint> mapNextTx;
  25. map<uint256, CBlockIndex*> mapBlockIndex;
  26. uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
  27. CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
  28. const int nTotalBlocksEstimate = 134444; // Conservative estimate of total nr of blocks on main chain
  29. const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
  30. CBlockIndex* pindexGenesisBlock = NULL;
  31. int nBestHeight = -1;
  32. CBigNum bnBestChainWork = 0;
  33. CBigNum bnBestInvalidWork = 0;
  34. uint256 hashBestChain = 0;
  35. CBlockIndex* pindexBest = NULL;
  36. int64 nTimeBestReceived = 0;
  37. map<uint256, CBlock*> mapOrphanBlocks;
  38. multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
  39. map<uint256, CDataStream*> mapOrphanTransactions;
  40. multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
  41. double dHashesPerSec;
  42. int64 nHPSTimerStart;
  43. // Settings
  44. int fGenerateBitcoins = false;
  45. int64 nTransactionFee = 0;
  46. CAddress addrIncoming;
  47. int fLimitProcessors = false;
  48. int nLimitProcessors = 1;
  49. int fMinimizeToTray = true;
  50. int fMinimizeOnClose = true;
  51. //////////////////////////////////////////////////////////////////////////////
  52. //
  53. // dispatching functions
  54. //
  55. void RegisterWallet(CWallet* pwalletIn)
  56. {
  57. CRITICAL_BLOCK(cs_setpwalletRegistered)
  58. {
  59. setpwalletRegistered.insert(pwalletIn);
  60. }
  61. }
  62. void UnregisterWallet(CWallet* pwalletIn)
  63. {
  64. CRITICAL_BLOCK(cs_setpwalletRegistered)
  65. {
  66. setpwalletRegistered.erase(pwalletIn);
  67. }
  68. }
  69. bool static IsFromMe(CTransaction& tx)
  70. {
  71. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  72. if (pwallet->IsFromMe(tx))
  73. return true;
  74. return false;
  75. }
  76. bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
  77. {
  78. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  79. if (pwallet->GetTransaction(hashTx,wtx))
  80. return true;
  81. return false;
  82. }
  83. void static EraseFromWallets(uint256 hash)
  84. {
  85. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  86. pwallet->EraseFromWallet(hash);
  87. }
  88. void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false)
  89. {
  90. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  91. pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
  92. }
  93. void static SetBestChain(const CBlockLocator& loc)
  94. {
  95. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  96. pwallet->SetBestChain(loc);
  97. }
  98. void static UpdatedTransaction(const uint256& hashTx)
  99. {
  100. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  101. pwallet->UpdatedTransaction(hashTx);
  102. }
  103. void static PrintWallets(const CBlock& block)
  104. {
  105. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  106. pwallet->PrintWallet(block);
  107. }
  108. void static Inventory(const uint256& hash)
  109. {
  110. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  111. pwallet->Inventory(hash);
  112. }
  113. void static ResendWalletTransactions()
  114. {
  115. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  116. pwallet->ResendWalletTransactions();
  117. }
  118. //////////////////////////////////////////////////////////////////////////////
  119. //
  120. // mapOrphanTransactions
  121. //
  122. void static AddOrphanTx(const CDataStream& vMsg)
  123. {
  124. CTransaction tx;
  125. CDataStream(vMsg) >> tx;
  126. uint256 hash = tx.GetHash();
  127. if (mapOrphanTransactions.count(hash))
  128. return;
  129. CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
  130. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  131. mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
  132. }
  133. void static EraseOrphanTx(uint256 hash)
  134. {
  135. if (!mapOrphanTransactions.count(hash))
  136. return;
  137. const CDataStream* pvMsg = mapOrphanTransactions[hash];
  138. CTransaction tx;
  139. CDataStream(*pvMsg) >> tx;
  140. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  141. {
  142. for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
  143. mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
  144. {
  145. if ((*mi).second == pvMsg)
  146. mapOrphanTransactionsByPrev.erase(mi++);
  147. else
  148. mi++;
  149. }
  150. }
  151. delete pvMsg;
  152. mapOrphanTransactions.erase(hash);
  153. }
  154. //////////////////////////////////////////////////////////////////////////////
  155. //
  156. // CTransaction and CTxIndex
  157. //
  158. bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
  159. {
  160. SetNull();
  161. if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
  162. return false;
  163. if (!ReadFromDisk(txindexRet.pos))
  164. return false;
  165. if (prevout.n >= vout.size())
  166. {
  167. SetNull();
  168. return false;
  169. }
  170. return true;
  171. }
  172. bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
  173. {
  174. CTxIndex txindex;
  175. return ReadFromDisk(txdb, prevout, txindex);
  176. }
  177. bool CTransaction::ReadFromDisk(COutPoint prevout)
  178. {
  179. CTxDB txdb("r");
  180. CTxIndex txindex;
  181. return ReadFromDisk(txdb, prevout, txindex);
  182. }
  183. int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
  184. {
  185. if (fClient)
  186. {
  187. if (hashBlock == 0)
  188. return 0;
  189. }
  190. else
  191. {
  192. CBlock blockTmp;
  193. if (pblock == NULL)
  194. {
  195. // Load the block this tx is in
  196. CTxIndex txindex;
  197. if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
  198. return 0;
  199. if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
  200. return 0;
  201. pblock = &blockTmp;
  202. }
  203. // Update the tx's hashBlock
  204. hashBlock = pblock->GetHash();
  205. // Locate the transaction
  206. for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
  207. if (pblock->vtx[nIndex] == *(CTransaction*)this)
  208. break;
  209. if (nIndex == pblock->vtx.size())
  210. {
  211. vMerkleBranch.clear();
  212. nIndex = -1;
  213. printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
  214. return 0;
  215. }
  216. // Fill in merkle branch
  217. vMerkleBranch = pblock->GetMerkleBranch(nIndex);
  218. }
  219. // Is the tx in a block that's in the main chain
  220. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  221. if (mi == mapBlockIndex.end())
  222. return 0;
  223. CBlockIndex* pindex = (*mi).second;
  224. if (!pindex || !pindex->IsInMainChain())
  225. return 0;
  226. return pindexBest->nHeight - pindex->nHeight + 1;
  227. }
  228. bool CTransaction::CheckTransaction() const
  229. {
  230. // Basic checks that don't depend on any context
  231. if (vin.empty() || vout.empty())
  232. return error("CTransaction::CheckTransaction() : vin or vout empty");
  233. // Size limits
  234. if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
  235. return error("CTransaction::CheckTransaction() : size limits failed");
  236. // Check for negative or overflow output values
  237. int64 nValueOut = 0;
  238. BOOST_FOREACH(const CTxOut& txout, vout)
  239. {
  240. if (txout.nValue < 0)
  241. return error("CTransaction::CheckTransaction() : txout.nValue negative");
  242. if (txout.nValue > MAX_MONEY)
  243. return error("CTransaction::CheckTransaction() : txout.nValue too high");
  244. nValueOut += txout.nValue;
  245. if (!MoneyRange(nValueOut))
  246. return error("CTransaction::CheckTransaction() : txout total out of range");
  247. }
  248. if (IsCoinBase())
  249. {
  250. if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
  251. return error("CTransaction::CheckTransaction() : coinbase script size");
  252. }
  253. else
  254. {
  255. BOOST_FOREACH(const CTxIn& txin, vin)
  256. if (txin.prevout.IsNull())
  257. return error("CTransaction::CheckTransaction() : prevout is null");
  258. }
  259. return true;
  260. }
  261. bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
  262. {
  263. if (pfMissingInputs)
  264. *pfMissingInputs = false;
  265. if (!CheckTransaction())
  266. return error("AcceptToMemoryPool() : CheckTransaction failed");
  267. // Coinbase is only valid in a block, not as a loose transaction
  268. if (IsCoinBase())
  269. return error("AcceptToMemoryPool() : coinbase as individual tx");
  270. // To help v0.1.5 clients who would see it as a negative number
  271. if ((int64)nLockTime > INT_MAX)
  272. return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
  273. // Safety limits
  274. unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
  275. // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
  276. // attacks disallow transactions with more than one SigOp per 34 bytes.
  277. // 34 bytes because a TxOut is:
  278. // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
  279. if (GetSigOpCount() > nSize / 34 || nSize < 100)
  280. return error("AcceptToMemoryPool() : nonstandard transaction");
  281. // Rather not work on nonstandard transactions (unless -testnet)
  282. if (!fTestNet && !IsStandard())
  283. return error("AcceptToMemoryPool() : nonstandard transaction type");
  284. // Do we already have it?
  285. uint256 hash = GetHash();
  286. CRITICAL_BLOCK(cs_mapTransactions)
  287. if (mapTransactions.count(hash))
  288. return false;
  289. if (fCheckInputs)
  290. if (txdb.ContainsTx(hash))
  291. return false;
  292. // Check for conflicts with in-memory transactions
  293. CTransaction* ptxOld = NULL;
  294. for (int i = 0; i < vin.size(); i++)
  295. {
  296. COutPoint outpoint = vin[i].prevout;
  297. if (mapNextTx.count(outpoint))
  298. {
  299. // Disable replacement feature for now
  300. return false;
  301. // Allow replacing with a newer version of the same transaction
  302. if (i != 0)
  303. return false;
  304. ptxOld = mapNextTx[outpoint].ptx;
  305. if (ptxOld->IsFinal())
  306. return false;
  307. if (!IsNewerThan(*ptxOld))
  308. return false;
  309. for (int i = 0; i < vin.size(); i++)
  310. {
  311. COutPoint outpoint = vin[i].prevout;
  312. if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
  313. return false;
  314. }
  315. break;
  316. }
  317. }
  318. if (fCheckInputs)
  319. {
  320. // Check against previous transactions
  321. map<uint256, CTxIndex> mapUnused;
  322. int64 nFees = 0;
  323. if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
  324. {
  325. if (pfMissingInputs)
  326. *pfMissingInputs = true;
  327. return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
  328. }
  329. // Don't accept it if it can't get into a block
  330. if (nFees < GetMinFee(1000, true, true))
  331. return error("AcceptToMemoryPool() : not enough fees");
  332. // Continuously rate-limit free transactions
  333. // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
  334. // be annoying or make other's transactions take longer to confirm.
  335. if (nFees < MIN_RELAY_TX_FEE)
  336. {
  337. static CCriticalSection cs;
  338. static double dFreeCount;
  339. static int64 nLastTime;
  340. int64 nNow = GetTime();
  341. CRITICAL_BLOCK(cs)
  342. {
  343. // Use an exponentially decaying ~10-minute window:
  344. dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
  345. nLastTime = nNow;
  346. // -limitfreerelay unit is thousand-bytes-per-minute
  347. // At default rate it would take over a month to fill 1GB
  348. if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
  349. return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
  350. if (fDebug)
  351. printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
  352. dFreeCount += nSize;
  353. }
  354. }
  355. }
  356. // Store transaction in memory
  357. CRITICAL_BLOCK(cs_mapTransactions)
  358. {
  359. if (ptxOld)
  360. {
  361. printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
  362. ptxOld->RemoveFromMemoryPool();
  363. }
  364. AddToMemoryPoolUnchecked();
  365. }
  366. ///// are we sure this is ok when loading transactions or restoring block txes
  367. // If updated, erase old tx from wallet
  368. if (ptxOld)
  369. EraseFromWallets(ptxOld->GetHash());
  370. printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
  371. return true;
  372. }
  373. bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
  374. {
  375. CTxDB txdb("r");
  376. return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
  377. }
  378. bool CTransaction::AddToMemoryPoolUnchecked()
  379. {
  380. // Add to memory pool without checking anything. Don't call this directly,
  381. // call AcceptToMemoryPool to properly check the transaction first.
  382. CRITICAL_BLOCK(cs_mapTransactions)
  383. {
  384. uint256 hash = GetHash();
  385. mapTransactions[hash] = *this;
  386. for (int i = 0; i < vin.size(); i++)
  387. mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
  388. nTransactionsUpdated++;
  389. }
  390. return true;
  391. }
  392. bool CTransaction::RemoveFromMemoryPool()
  393. {
  394. // Remove transaction from memory pool
  395. CRITICAL_BLOCK(cs_mapTransactions)
  396. {
  397. BOOST_FOREACH(const CTxIn& txin, vin)
  398. mapNextTx.erase(txin.prevout);
  399. mapTransactions.erase(GetHash());
  400. nTransactionsUpdated++;
  401. }
  402. return true;
  403. }
  404. int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
  405. {
  406. if (hashBlock == 0 || nIndex == -1)
  407. return 0;
  408. // Find the block it claims to be in
  409. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  410. if (mi == mapBlockIndex.end())
  411. return 0;
  412. CBlockIndex* pindex = (*mi).second;
  413. if (!pindex || !pindex->IsInMainChain())
  414. return 0;
  415. // Make sure the merkle branch connects to this block
  416. if (!fMerkleVerified)
  417. {
  418. if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
  419. return 0;
  420. fMerkleVerified = true;
  421. }
  422. nHeightRet = pindex->nHeight;
  423. return pindexBest->nHeight - pindex->nHeight + 1;
  424. }
  425. int CMerkleTx::GetBlocksToMaturity() const
  426. {
  427. if (!IsCoinBase())
  428. return 0;
  429. return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
  430. }
  431. bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
  432. {
  433. if (fClient)
  434. {
  435. if (!IsInMainChain() && !ClientConnectInputs())
  436. return false;
  437. return CTransaction::AcceptToMemoryPool(txdb, false);
  438. }
  439. else
  440. {
  441. return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
  442. }
  443. }
  444. bool CMerkleTx::AcceptToMemoryPool()
  445. {
  446. CTxDB txdb("r");
  447. return AcceptToMemoryPool(txdb);
  448. }
  449. bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
  450. {
  451. CRITICAL_BLOCK(cs_mapTransactions)
  452. {
  453. // Add previous supporting transactions first
  454. BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
  455. {
  456. if (!tx.IsCoinBase())
  457. {
  458. uint256 hash = tx.GetHash();
  459. if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
  460. tx.AcceptToMemoryPool(txdb, fCheckInputs);
  461. }
  462. }
  463. return AcceptToMemoryPool(txdb, fCheckInputs);
  464. }
  465. return false;
  466. }
  467. bool CWalletTx::AcceptWalletTransaction()
  468. {
  469. CTxDB txdb("r");
  470. return AcceptWalletTransaction(txdb);
  471. }
  472. int CTxIndex::GetDepthInMainChain() const
  473. {
  474. // Read block header
  475. CBlock block;
  476. if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
  477. return 0;
  478. // Find the block in the index
  479. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
  480. if (mi == mapBlockIndex.end())
  481. return 0;
  482. CBlockIndex* pindex = (*mi).second;
  483. if (!pindex || !pindex->IsInMainChain())
  484. return 0;
  485. return 1 + nBestHeight - pindex->nHeight;
  486. }
  487. //////////////////////////////////////////////////////////////////////////////
  488. //
  489. // CBlock and CBlockIndex
  490. //
  491. bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
  492. {
  493. if (!fReadTransactions)
  494. {
  495. *this = pindex->GetBlockHeader();
  496. return true;
  497. }
  498. if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
  499. return false;
  500. if (GetHash() != pindex->GetBlockHash())
  501. return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
  502. return true;
  503. }
  504. uint256 static GetOrphanRoot(const CBlock* pblock)
  505. {
  506. // Work back to the first block in the orphan chain
  507. while (mapOrphanBlocks.count(pblock->hashPrevBlock))
  508. pblock = mapOrphanBlocks[pblock->hashPrevBlock];
  509. return pblock->GetHash();
  510. }
  511. int64 static GetBlockValue(int nHeight, int64 nFees)
  512. {
  513. int64 nSubsidy = 50 * COIN;
  514. // Subsidy is cut in half every 4 years
  515. nSubsidy >>= (nHeight / 210000);
  516. return nSubsidy + nFees;
  517. }
  518. unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast)
  519. {
  520. const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
  521. const int64 nTargetSpacing = 10 * 60;
  522. const int64 nInterval = nTargetTimespan / nTargetSpacing;
  523. // Genesis block
  524. if (pindexLast == NULL)
  525. return bnProofOfWorkLimit.GetCompact();
  526. // Only change once per interval
  527. if ((pindexLast->nHeight+1) % nInterval != 0)
  528. return pindexLast->nBits;
  529. // Go back by what we want to be 14 days worth of blocks
  530. const CBlockIndex* pindexFirst = pindexLast;
  531. for (int i = 0; pindexFirst && i < nInterval-1; i++)
  532. pindexFirst = pindexFirst->pprev;
  533. assert(pindexFirst);
  534. // Limit adjustment step
  535. int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
  536. printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
  537. if (nActualTimespan < nTargetTimespan/4)
  538. nActualTimespan = nTargetTimespan/4;
  539. if (nActualTimespan > nTargetTimespan*4)
  540. nActualTimespan = nTargetTimespan*4;
  541. // Retarget
  542. CBigNum bnNew;
  543. bnNew.SetCompact(pindexLast->nBits);
  544. bnNew *= nActualTimespan;
  545. bnNew /= nTargetTimespan;
  546. if (bnNew > bnProofOfWorkLimit)
  547. bnNew = bnProofOfWorkLimit;
  548. /// debug print
  549. printf("GetNextWorkRequired RETARGET\n");
  550. printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
  551. printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
  552. printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
  553. return bnNew.GetCompact();
  554. }
  555. bool CheckProofOfWork(uint256 hash, unsigned int nBits)
  556. {
  557. CBigNum bnTarget;
  558. bnTarget.SetCompact(nBits);
  559. // Check range
  560. if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
  561. return error("CheckProofOfWork() : nBits below minimum work");
  562. // Check proof of work matches claimed amount
  563. if (hash > bnTarget.getuint256())
  564. return error("CheckProofOfWork() : hash doesn't match nBits");
  565. return true;
  566. }
  567. // Return conservative estimate of total number of blocks, 0 if unknown
  568. int GetTotalBlocksEstimate()
  569. {
  570. if(fTestNet)
  571. {
  572. return 0;
  573. }
  574. else
  575. {
  576. return nTotalBlocksEstimate;
  577. }
  578. }
  579. bool IsInitialBlockDownload()
  580. {
  581. if (pindexBest == NULL || nBestHeight < (GetTotalBlocksEstimate()-nInitialBlockThreshold))
  582. return true;
  583. static int64 nLastUpdate;
  584. static CBlockIndex* pindexLastBest;
  585. if (pindexBest != pindexLastBest)
  586. {
  587. pindexLastBest = pindexBest;
  588. nLastUpdate = GetTime();
  589. }
  590. return (GetTime() - nLastUpdate < 10 &&
  591. pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
  592. }
  593. void static InvalidChainFound(CBlockIndex* pindexNew)
  594. {
  595. if (pindexNew->bnChainWork > bnBestInvalidWork)
  596. {
  597. bnBestInvalidWork = pindexNew->bnChainWork;
  598. CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
  599. MainFrameRepaint();
  600. }
  601. printf("InvalidChainFound: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
  602. printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
  603. if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
  604. printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
  605. }
  606. bool CTransaction::DisconnectInputs(CTxDB& txdb)
  607. {
  608. // Relinquish previous transactions' spent pointers
  609. if (!IsCoinBase())
  610. {
  611. BOOST_FOREACH(const CTxIn& txin, vin)
  612. {
  613. COutPoint prevout = txin.prevout;
  614. // Get prev txindex from disk
  615. CTxIndex txindex;
  616. if (!txdb.ReadTxIndex(prevout.hash, txindex))
  617. return error("DisconnectInputs() : ReadTxIndex failed");
  618. if (prevout.n >= txindex.vSpent.size())
  619. return error("DisconnectInputs() : prevout.n out of range");
  620. // Mark outpoint as not spent
  621. txindex.vSpent[prevout.n].SetNull();
  622. // Write back
  623. if (!txdb.UpdateTxIndex(prevout.hash, txindex))
  624. return error("DisconnectInputs() : UpdateTxIndex failed");
  625. }
  626. }
  627. // Remove transaction from index
  628. if (!txdb.EraseTxIndex(*this))
  629. return error("DisconnectInputs() : EraseTxPos failed");
  630. return true;
  631. }
  632. bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
  633. CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
  634. {
  635. // Take over previous transactions' spent pointers
  636. if (!IsCoinBase())
  637. {
  638. int64 nValueIn = 0;
  639. for (int i = 0; i < vin.size(); i++)
  640. {
  641. COutPoint prevout = vin[i].prevout;
  642. // Read txindex
  643. CTxIndex txindex;
  644. bool fFound = true;
  645. if (fMiner && mapTestPool.count(prevout.hash))
  646. {
  647. // Get txindex from current proposed changes
  648. txindex = mapTestPool[prevout.hash];
  649. }
  650. else
  651. {
  652. // Read txindex from txdb
  653. fFound = txdb.ReadTxIndex(prevout.hash, txindex);
  654. }
  655. if (!fFound && (fBlock || fMiner))
  656. return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
  657. // Read txPrev
  658. CTransaction txPrev;
  659. if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
  660. {
  661. // Get prev tx from single transactions in memory
  662. CRITICAL_BLOCK(cs_mapTransactions)
  663. {
  664. if (!mapTransactions.count(prevout.hash))
  665. return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
  666. txPrev = mapTransactions[prevout.hash];
  667. }
  668. if (!fFound)
  669. txindex.vSpent.resize(txPrev.vout.size());
  670. }
  671. else
  672. {
  673. // Get prev tx from disk
  674. if (!txPrev.ReadFromDisk(txindex.pos))
  675. return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
  676. }
  677. if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
  678. return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str());
  679. // If prev is coinbase, check that it's matured
  680. if (txPrev.IsCoinBase())
  681. for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
  682. if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
  683. return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
  684. // Verify signature
  685. if (!VerifySignature(txPrev, *this, i))
  686. return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
  687. // Check for conflicts
  688. if (!txindex.vSpent[prevout.n].IsNull())
  689. return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
  690. // Check for negative or overflow input values
  691. nValueIn += txPrev.vout[prevout.n].nValue;
  692. if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
  693. return error("ConnectInputs() : txin values out of range");
  694. // Mark outpoints as spent
  695. txindex.vSpent[prevout.n] = posThisTx;
  696. // Write back
  697. if (fBlock)
  698. {
  699. if (!txdb.UpdateTxIndex(prevout.hash, txindex))
  700. return error("ConnectInputs() : UpdateTxIndex failed");
  701. }
  702. else if (fMiner)
  703. {
  704. mapTestPool[prevout.hash] = txindex;
  705. }
  706. }
  707. if (nValueIn < GetValueOut())
  708. return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
  709. // Tally transaction fees
  710. int64 nTxFee = nValueIn - GetValueOut();
  711. if (nTxFee < 0)
  712. return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
  713. if (nTxFee < nMinFee)
  714. return false;
  715. nFees += nTxFee;
  716. if (!MoneyRange(nFees))
  717. return error("ConnectInputs() : nFees out of range");
  718. }
  719. if (fBlock)
  720. {
  721. // Add transaction to disk index
  722. if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
  723. return error("ConnectInputs() : AddTxPos failed");
  724. }
  725. else if (fMiner)
  726. {
  727. // Add transaction to test pool
  728. mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
  729. }
  730. return true;
  731. }
  732. bool CTransaction::ClientConnectInputs()
  733. {
  734. if (IsCoinBase())
  735. return false;
  736. // Take over previous transactions' spent pointers
  737. CRITICAL_BLOCK(cs_mapTransactions)
  738. {
  739. int64 nValueIn = 0;
  740. for (int i = 0; i < vin.size(); i++)
  741. {
  742. // Get prev tx from single transactions in memory
  743. COutPoint prevout = vin[i].prevout;
  744. if (!mapTransactions.count(prevout.hash))
  745. return false;
  746. CTransaction& txPrev = mapTransactions[prevout.hash];
  747. if (prevout.n >= txPrev.vout.size())
  748. return false;
  749. // Verify signature
  750. if (!VerifySignature(txPrev, *this, i))
  751. return error("ConnectInputs() : VerifySignature failed");
  752. ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
  753. ///// this has to go away now that posNext is gone
  754. // // Check for conflicts
  755. // if (!txPrev.vout[prevout.n].posNext.IsNull())
  756. // return error("ConnectInputs() : prev tx already used");
  757. //
  758. // // Flag outpoints as used
  759. // txPrev.vout[prevout.n].posNext = posThisTx;
  760. nValueIn += txPrev.vout[prevout.n].nValue;
  761. if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
  762. return error("ClientConnectInputs() : txin values out of range");
  763. }
  764. if (GetValueOut() > nValueIn)
  765. return false;
  766. }
  767. return true;
  768. }
  769. bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
  770. {
  771. // Disconnect in reverse order
  772. for (int i = vtx.size()-1; i >= 0; i--)
  773. if (!vtx[i].DisconnectInputs(txdb))
  774. return false;
  775. // Update block index on disk without changing it in memory.
  776. // The memory index structure will be changed after the db commits.
  777. if (pindex->pprev)
  778. {
  779. CDiskBlockIndex blockindexPrev(pindex->pprev);
  780. blockindexPrev.hashNext = 0;
  781. if (!txdb.WriteBlockIndex(blockindexPrev))
  782. return error("DisconnectBlock() : WriteBlockIndex failed");
  783. }
  784. return true;
  785. }
  786. bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
  787. {
  788. // Check it again in case a previous version let a bad block in
  789. if (!CheckBlock())
  790. return false;
  791. //// issue here: it doesn't know the version
  792. unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
  793. map<uint256, CTxIndex> mapUnused;
  794. int64 nFees = 0;
  795. BOOST_FOREACH(CTransaction& tx, vtx)
  796. {
  797. CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
  798. nTxPos += ::GetSerializeSize(tx, SER_DISK);
  799. if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
  800. return false;
  801. }
  802. if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
  803. return false;
  804. // Update block index on disk without changing it in memory.
  805. // The memory index structure will be changed after the db commits.
  806. if (pindex->pprev)
  807. {
  808. CDiskBlockIndex blockindexPrev(pindex->pprev);
  809. blockindexPrev.hashNext = pindex->GetBlockHash();
  810. if (!txdb.WriteBlockIndex(blockindexPrev))
  811. return error("ConnectBlock() : WriteBlockIndex failed");
  812. }
  813. // Watch for transactions paying to me
  814. BOOST_FOREACH(CTransaction& tx, vtx)
  815. SyncWithWallets(tx, this, true);
  816. return true;
  817. }
  818. bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
  819. {
  820. printf("REORGANIZE\n");
  821. // Find the fork
  822. CBlockIndex* pfork = pindexBest;
  823. CBlockIndex* plonger = pindexNew;
  824. while (pfork != plonger)
  825. {
  826. while (plonger->nHeight > pfork->nHeight)
  827. if (!(plonger = plonger->pprev))
  828. return error("Reorganize() : plonger->pprev is null");
  829. if (pfork == plonger)
  830. break;
  831. if (!(pfork = pfork->pprev))
  832. return error("Reorganize() : pfork->pprev is null");
  833. }
  834. // List of what to disconnect
  835. vector<CBlockIndex*> vDisconnect;
  836. for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
  837. vDisconnect.push_back(pindex);
  838. // List of what to connect
  839. vector<CBlockIndex*> vConnect;
  840. for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
  841. vConnect.push_back(pindex);
  842. reverse(vConnect.begin(), vConnect.end());
  843. // Disconnect shorter branch
  844. vector<CTransaction> vResurrect;
  845. BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
  846. {
  847. CBlock block;
  848. if (!block.ReadFromDisk(pindex))
  849. return error("Reorganize() : ReadFromDisk for disconnect failed");
  850. if (!block.DisconnectBlock(txdb, pindex))
  851. return error("Reorganize() : DisconnectBlock failed");
  852. // Queue memory transactions to resurrect
  853. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  854. if (!tx.IsCoinBase())
  855. vResurrect.push_back(tx);
  856. }
  857. // Connect longer branch
  858. vector<CTransaction> vDelete;
  859. for (int i = 0; i < vConnect.size(); i++)
  860. {
  861. CBlockIndex* pindex = vConnect[i];
  862. CBlock block;
  863. if (!block.ReadFromDisk(pindex))
  864. return error("Reorganize() : ReadFromDisk for connect failed");
  865. if (!block.ConnectBlock(txdb, pindex))
  866. {
  867. // Invalid block
  868. txdb.TxnAbort();
  869. return error("Reorganize() : ConnectBlock failed");
  870. }
  871. // Queue memory transactions to delete
  872. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  873. vDelete.push_back(tx);
  874. }
  875. if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
  876. return error("Reorganize() : WriteHashBestChain failed");
  877. // Make sure it's successfully written to disk before changing memory structure
  878. if (!txdb.TxnCommit())
  879. return error("Reorganize() : TxnCommit failed");
  880. // Disconnect shorter branch
  881. BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
  882. if (pindex->pprev)
  883. pindex->pprev->pnext = NULL;
  884. // Connect longer branch
  885. BOOST_FOREACH(CBlockIndex* pindex, vConnect)
  886. if (pindex->pprev)
  887. pindex->pprev->pnext = pindex;
  888. // Resurrect memory transactions that were in the disconnected branch
  889. BOOST_FOREACH(CTransaction& tx, vResurrect)
  890. tx.AcceptToMemoryPool(txdb, false);
  891. // Delete redundant memory transactions that are in the connected branch
  892. BOOST_FOREACH(CTransaction& tx, vDelete)
  893. tx.RemoveFromMemoryPool();
  894. return true;
  895. }
  896. bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
  897. {
  898. uint256 hash = GetHash();
  899. txdb.TxnBegin();
  900. if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
  901. {
  902. txdb.WriteHashBestChain(hash);
  903. if (!txdb.TxnCommit())
  904. return error("SetBestChain() : TxnCommit failed");
  905. pindexGenesisBlock = pindexNew;
  906. }
  907. else if (hashPrevBlock == hashBestChain)
  908. {
  909. // Adding to current best branch
  910. if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
  911. {
  912. txdb.TxnAbort();
  913. InvalidChainFound(pindexNew);
  914. return error("SetBestChain() : ConnectBlock failed");
  915. }
  916. if (!txdb.TxnCommit())
  917. return error("SetBestChain() : TxnCommit failed");
  918. // Add to current best branch
  919. pindexNew->pprev->pnext = pindexNew;
  920. // Delete redundant memory transactions
  921. BOOST_FOREACH(CTransaction& tx, vtx)
  922. tx.RemoveFromMemoryPool();
  923. }
  924. else
  925. {
  926. // New best branch
  927. if (!Reorganize(txdb, pindexNew))
  928. {
  929. txdb.TxnAbort();
  930. InvalidChainFound(pindexNew);
  931. return error("SetBestChain() : Reorganize failed");
  932. }
  933. }
  934. // Update best block in wallet (so we can detect restored wallets)
  935. if (!IsInitialBlockDownload())
  936. {
  937. const CBlockLocator locator(pindexNew);
  938. ::SetBestChain(locator);
  939. }
  940. // New best block
  941. hashBestChain = hash;
  942. pindexBest = pindexNew;
  943. nBestHeight = pindexBest->nHeight;
  944. bnBestChainWork = pindexNew->bnChainWork;
  945. nTimeBestReceived = GetTime();
  946. nTransactionsUpdated++;
  947. printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
  948. return true;
  949. }
  950. bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
  951. {
  952. // Check for duplicate
  953. uint256 hash = GetHash();
  954. if (mapBlockIndex.count(hash))
  955. return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
  956. // Construct new block index object
  957. CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
  958. if (!pindexNew)
  959. return error("AddToBlockIndex() : new CBlockIndex failed");
  960. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  961. pindexNew->phashBlock = &((*mi).first);
  962. map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
  963. if (miPrev != mapBlockIndex.end())
  964. {
  965. pindexNew->pprev = (*miPrev).second;
  966. pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
  967. }
  968. pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
  969. CTxDB txdb;
  970. txdb.TxnBegin();
  971. txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
  972. if (!txdb.TxnCommit())
  973. return false;
  974. // New best
  975. if (pindexNew->bnChainWork > bnBestChainWork)
  976. if (!SetBestChain(txdb, pindexNew))
  977. return false;
  978. txdb.Close();
  979. if (pindexNew == pindexBest)
  980. {
  981. // Notify UI to display prev block's coinbase if it was ours
  982. static uint256 hashPrevBestCoinBase;
  983. UpdatedTransaction(hashPrevBestCoinBase);
  984. hashPrevBestCoinBase = vtx[0].GetHash();
  985. }
  986. MainFrameRepaint();
  987. return true;
  988. }
  989. bool CBlock::CheckBlock() const
  990. {
  991. // These are checks that are independent of context
  992. // that can be verified before saving an orphan block.
  993. // Size limits
  994. if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
  995. return error("CheckBlock() : size limits failed");
  996. // Check proof of work matches claimed amount
  997. if (!CheckProofOfWork(GetHash(), nBits))
  998. return error("CheckBlock() : proof of work failed");
  999. // Check timestamp
  1000. if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
  1001. return error("CheckBlock() : block timestamp too far in the future");
  1002. // First transaction must be coinbase, the rest must not be
  1003. if (vtx.empty() || !vtx[0].IsCoinBase())
  1004. return error("CheckBlock() : first tx is not coinbase");
  1005. for (int i = 1; i < vtx.size(); i++)
  1006. if (vtx[i].IsCoinBase())
  1007. return error("CheckBlock() : more than one coinbase");
  1008. // Check transactions
  1009. BOOST_FOREACH(const CTransaction& tx, vtx)
  1010. if (!tx.CheckTransaction())
  1011. return error("CheckBlock() : CheckTransaction failed");
  1012. // Check that it's not full of nonstandard transactions
  1013. if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
  1014. return error("CheckBlock() : too many nonstandard transactions");
  1015. // Check merkleroot
  1016. if (hashMerkleRoot != BuildMerkleTree())
  1017. return error("CheckBlock() : hashMerkleRoot mismatch");
  1018. return true;
  1019. }
  1020. bool CBlock::AcceptBlock()
  1021. {
  1022. // Check for duplicate
  1023. uint256 hash = GetHash();
  1024. if (mapBlockIndex.count(hash))
  1025. return error("AcceptBlock() : block already in mapBlockIndex");
  1026. // Get prev block index
  1027. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
  1028. if (mi == mapBlockIndex.end())
  1029. return error("AcceptBlock() : prev block not found");
  1030. CBlockIndex* pindexPrev = (*mi).second;
  1031. int nHeight = pindexPrev->nHeight+1;
  1032. // Check proof of work
  1033. if (nBits != GetNextWorkRequired(pindexPrev))
  1034. return error("AcceptBlock() : incorrect proof of work");
  1035. // Check timestamp against prev
  1036. if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
  1037. return error("AcceptBlock() : block's timestamp is too early");
  1038. // Check that all transactions are finalized
  1039. BOOST_FOREACH(const CTransaction& tx, vtx)
  1040. if (!tx.IsFinal(nHeight, GetBlockTime()))
  1041. return error("AcceptBlock() : contains a non-final transaction");
  1042. // Check that the block chain matches the known block chain up to a checkpoint
  1043. if (!fTestNet)
  1044. if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
  1045. (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
  1046. (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
  1047. (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
  1048. (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) ||
  1049. (nHeight == 105000 && hash != uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) ||
  1050. (nHeight == 118000 && hash != uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553")) ||
  1051. (nHeight == 134444 && hash != uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")))
  1052. return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
  1053. // Write block to history file
  1054. if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
  1055. return error("AcceptBlock() : out of disk space");
  1056. unsigned int nFile = -1;
  1057. unsigned int nBlockPos = 0;
  1058. if (!WriteToDisk(nFile, nBlockPos))
  1059. return error("AcceptBlock() : WriteToDisk failed");
  1060. if (!AddToBlockIndex(nFile, nBlockPos))
  1061. return error("AcceptBlock() : AddToBlockIndex failed");
  1062. // Relay inventory, but don't relay old inventory during initial block download
  1063. if (hashBestChain == hash)
  1064. CRITICAL_BLOCK(cs_vNodes)
  1065. BOOST_FOREACH(CNode* pnode, vNodes)
  1066. if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 134444))
  1067. pnode->PushInventory(CInv(MSG_BLOCK, hash));
  1068. return true;
  1069. }
  1070. bool static ProcessBlock(CNode* pfrom, CBlock* pblock)
  1071. {
  1072. // Check for duplicate
  1073. uint256 hash = pblock->GetHash();
  1074. if (mapBlockIndex.count(hash))
  1075. return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
  1076. if (mapOrphanBlocks.count(hash))
  1077. return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
  1078. // Preliminary checks
  1079. if (!pblock->CheckBlock())
  1080. return error("ProcessBlock() : CheckBlock FAILED");
  1081. // If don't already have its previous block, shunt it off to holding area until we get it
  1082. if (!mapBlockIndex.count(pblock->hashPrevBlock))
  1083. {
  1084. printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
  1085. CBlock* pblock2 = new CBlock(*pblock);
  1086. mapOrphanBlocks.insert(make_pair(hash, pblock2));
  1087. mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
  1088. // Ask this guy to fill in what we're missing
  1089. if (pfrom)
  1090. pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
  1091. return true;
  1092. }
  1093. // Store to disk
  1094. if (!pblock->AcceptBlock())
  1095. return error("ProcessBlock() : AcceptBlock FAILED");
  1096. // Recursively process any orphan blocks that depended on this one
  1097. vector<uint256> vWorkQueue;
  1098. vWorkQueue.push_back(hash);
  1099. for (int i = 0; i < vWorkQueue.size(); i++)
  1100. {
  1101. uint256 hashPrev = vWorkQueue[i];
  1102. for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
  1103. mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
  1104. ++mi)
  1105. {
  1106. CBlock* pblockOrphan = (*mi).second;
  1107. if (pblockOrphan->AcceptBlock())
  1108. vWorkQueue.push_back(pblockOrphan->GetHash());
  1109. mapOrphanBlocks.erase(pblockOrphan->GetHash());
  1110. delete pblockOrphan;
  1111. }
  1112. mapOrphanBlocksByPrev.erase(hashPrev);
  1113. }
  1114. printf("ProcessBlock: ACCEPTED\n");
  1115. return true;
  1116. }
  1117. template<typename Stream>
  1118. bool static ScanMessageStart(Stream& s)
  1119. {
  1120. // Scan ahead to the next pchMessageStart, which should normally be immediately
  1121. // at the file pointer. Leaves file pointer at end of pchMessageStart.
  1122. s.clear(0);
  1123. short prevmask = s.exceptions(0);
  1124. const char* p = BEGIN(pchMessageStart);
  1125. try
  1126. {
  1127. loop
  1128. {
  1129. char c;
  1130. s.read(&c, 1);
  1131. if (s.fail())
  1132. {
  1133. s.clear(0);
  1134. s.exceptions(prevmask);
  1135. return false;
  1136. }
  1137. if (*p != c)
  1138. p = BEGIN(pchMessageStart);
  1139. if (*p == c)
  1140. {
  1141. if (++p == END(pchMessageStart))
  1142. {
  1143. s.clear(0);
  1144. s.exceptions(prevmask);
  1145. return true;
  1146. }
  1147. }
  1148. }
  1149. }
  1150. catch (...)
  1151. {
  1152. s.clear(0);
  1153. s.exceptions(prevmask);
  1154. return false;
  1155. }
  1156. }
  1157. bool CheckDiskSpace(uint64 nAdditionalBytes)
  1158. {
  1159. uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
  1160. // Check for 15MB because database could create another 10MB log file at any time
  1161. if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
  1162. {
  1163. fShutdown = true;
  1164. string strMessage = _("Warning: Disk space is low ");
  1165. strMiscWarning = strMessage;
  1166. printf("*** %s\n", strMessage.c_str());
  1167. ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
  1168. CreateThread(Shutdown, NULL);
  1169. return false;
  1170. }
  1171. return true;
  1172. }
  1173. FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
  1174. {
  1175. if (nFile == -1)
  1176. return NULL;
  1177. FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
  1178. if (!file)
  1179. return NULL;
  1180. if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
  1181. {
  1182. if (fseek(file, nBlockPos, SEEK_SET) != 0)
  1183. {
  1184. fclose(file);
  1185. return NULL;
  1186. }
  1187. }
  1188. return file;
  1189. }
  1190. static unsigned int nCurrentBlockFile = 1;
  1191. FILE* AppendBlockFile(unsigned int& nFileRet)
  1192. {
  1193. nFileRet = 0;
  1194. loop
  1195. {
  1196. FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
  1197. if (!file)
  1198. return NULL;
  1199. if (fseek(file, 0, SEEK_END) != 0)
  1200. return NULL;
  1201. // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
  1202. if (ftell(file) < 0x7F000000 - MAX_SIZE)
  1203. {
  1204. nFileRet = nCurrentBlockFile;
  1205. return file;
  1206. }
  1207. fclose(file);
  1208. nCurrentBlockFile++;
  1209. }
  1210. }
  1211. bool LoadBlockIndex(bool fAllowNew)
  1212. {
  1213. if (fTestNet)
  1214. {
  1215. hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
  1216. bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
  1217. pchMessageStart[0] = 0xfa;
  1218. pchMessageStart[1] = 0xbf;
  1219. pchMessageStart[2] = 0xb5;
  1220. pchMessageStart[3] = 0xda;
  1221. }
  1222. //
  1223. // Load block index
  1224. //
  1225. CTxDB txdb("cr");
  1226. if (!txdb.LoadBlockIndex())
  1227. return false;
  1228. txdb.Close();
  1229. //
  1230. // Init with genesis block
  1231. //
  1232. if (mapBlockIndex.empty())
  1233. {
  1234. if (!fAllowNew)
  1235. return false;
  1236. // Genesis Block:
  1237. // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
  1238. // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
  1239. // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
  1240. // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
  1241. // vMerkleTree: 4a5e1e
  1242. // Genesis block
  1243. const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
  1244. CTransaction txNew;
  1245. txNew.vin.resize(1);
  1246. txNew.vout.resize(1);
  1247. txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
  1248. txNew.vout[0].nValue = 50 * COIN;
  1249. txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
  1250. CBlock block;
  1251. block.vtx.push_back(txNew);
  1252. block.hashPrevBlock = 0;
  1253. block.hashMerkleRoot = block.BuildMerkleTree();
  1254. block.nVersion = 1;
  1255. block.nTime = 1231006505;
  1256. block.nBits = 0x1d00ffff;
  1257. block.nNonce = 2083236893;
  1258. if (fTestNet)
  1259. {
  1260. block.nTime = 1296688602;
  1261. block.nBits = 0x1d07fff8;
  1262. block.nNonce = 384568319;
  1263. }
  1264. //// debug print
  1265. printf("%s\n", block.GetHash().ToString().c_str());
  1266. printf("%s\n", hashGenesisBlock.ToString().c_str());
  1267. printf("%s\n", block.hashMerkleRoot.ToString().c_str());
  1268. assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
  1269. block.print();
  1270. assert(block.GetHash() == hashGenesisBlock);
  1271. // Start new block file
  1272. unsigned int nFile;
  1273. unsigned int nBlockPos;
  1274. if (!block.WriteToDisk(nFile, nBlockPos))
  1275. return error("LoadBlockIndex() : writ…

Large files files are truncated, but you can click here to view the full file