PageRenderTime 76ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/src/main.cpp

https://gitlab.com/intersango/bitcoind
C++ | 3112 lines | 2247 code | 518 blank | 347 comment | 631 complexity | 4e1b29ec025e8891647bb4485e5fb2cf MD5 | raw 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() : writing genesis block to disk failed");
  1276. if (!block.AddToBlockIndex(nFile, nBlockPos))
  1277. return error("LoadBlockIndex() : genesis block not accepted");
  1278. }
  1279. return true;
  1280. }
  1281. void PrintBlockTree()
  1282. {
  1283. // precompute tree structure
  1284. map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
  1285. for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
  1286. {
  1287. CBlockIndex* pindex = (*mi).second;
  1288. mapNext[pindex->pprev].push_back(pindex);
  1289. // test
  1290. //while (rand() % 3 == 0)
  1291. // mapNext[pindex->pprev].push_back(pindex);
  1292. }
  1293. vector<pair<int, CBlockIndex*> > vStack;
  1294. vStack.push_back(make_pair(0, pindexGenesisBlock));
  1295. int nPrevCol = 0;
  1296. while (!vStack.empty())
  1297. {
  1298. int nCol = vStack.back().first;
  1299. CBlockIndex* pindex = vStack.back().second;
  1300. vStack.pop_back();
  1301. // print split or gap
  1302. if (nCol > nPrevCol)
  1303. {
  1304. for (int i = 0; i < nCol-1; i++)
  1305. printf("| ");
  1306. printf("|\\\n");
  1307. }
  1308. else if (nCol < nPrevCol)
  1309. {
  1310. for (int i = 0; i < nCol; i++)
  1311. printf("| ");
  1312. printf("|\n");
  1313. }
  1314. nPrevCol = nCol;
  1315. // print columns
  1316. for (int i = 0; i < nCol; i++)
  1317. printf("| ");
  1318. // print item
  1319. CBlock block;
  1320. block.ReadFromDisk(pindex);
  1321. printf("%d (%u,%u) %s %s tx %d",
  1322. pindex->nHeight,
  1323. pindex->nFile,
  1324. pindex->nBlockPos,
  1325. block.GetHash().ToString().substr(0,20).c_str(),
  1326. DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
  1327. block.vtx.size());
  1328. PrintWallets(block);
  1329. // put the main timechain first
  1330. vector<CBlockIndex*>& vNext = mapNext[pindex];
  1331. for (int i = 0; i < vNext.size(); i++)
  1332. {
  1333. if (vNext[i]->pnext)
  1334. {
  1335. swap(vNext[0], vNext[i]);
  1336. break;
  1337. }
  1338. }
  1339. // iterate children
  1340. for (int i = 0; i < vNext.size(); i++)
  1341. vStack.push_back(make_pair(nCol+i, vNext[i]));
  1342. }
  1343. }
  1344. //////////////////////////////////////////////////////////////////////////////
  1345. //
  1346. // CAlert
  1347. //
  1348. map<uint256, CAlert> mapAlerts;
  1349. CCriticalSection cs_mapAlerts;
  1350. string GetWarnings(string strFor)
  1351. {
  1352. int nPriority = 0;
  1353. string strStatusBar;
  1354. string strRPC;
  1355. if (GetBoolArg("-testsafemode"))
  1356. strRPC = "test";
  1357. // Misc warnings like out of disk space and clock is wrong
  1358. if (strMiscWarning != "")
  1359. {
  1360. nPriority = 1000;
  1361. strStatusBar = strMiscWarning;
  1362. }
  1363. // Longer invalid proof-of-work chain
  1364. if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
  1365. {
  1366. nPriority = 2000;
  1367. strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
  1368. }
  1369. // Alerts
  1370. CRITICAL_BLOCK(cs_mapAlerts)
  1371. {
  1372. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  1373. {
  1374. const CAlert& alert = item.second;
  1375. if (alert.AppliesToMe() && alert.nPriority > nPriority)
  1376. {
  1377. nPriority = alert.nPriority;
  1378. strStatusBar = alert.strStatusBar;
  1379. }
  1380. }
  1381. }
  1382. if (strFor == "statusbar")
  1383. return strStatusBar;
  1384. else if (strFor == "rpc")
  1385. return strRPC;
  1386. assert(("GetWarnings() : invalid parameter", false));
  1387. return "error";
  1388. }
  1389. bool CAlert::ProcessAlert()
  1390. {
  1391. if (!CheckSignature())
  1392. return false;
  1393. if (!IsInEffect())
  1394. return false;
  1395. CRITICAL_BLOCK(cs_mapAlerts)
  1396. {
  1397. // Cancel previous alerts
  1398. for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
  1399. {
  1400. const CAlert& alert = (*mi).second;
  1401. if (Cancels(alert))
  1402. {
  1403. printf("cancelling alert %d\n", alert.nID);
  1404. mapAlerts.erase(mi++);
  1405. }
  1406. else if (!alert.IsInEffect())
  1407. {
  1408. printf("expiring alert %d\n", alert.nID);
  1409. mapAlerts.erase(mi++);
  1410. }
  1411. else
  1412. mi++;
  1413. }
  1414. // Check if this alert has been cancelled
  1415. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  1416. {
  1417. const CAlert& alert = item.second;
  1418. if (alert.Cancels(*this))
  1419. {
  1420. printf("alert already cancelled by %d\n", alert.nID);
  1421. return false;
  1422. }
  1423. }
  1424. // Add to mapAlerts
  1425. mapAlerts.insert(make_pair(GetHash(), *this));
  1426. }
  1427. printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
  1428. MainFrameRepaint();
  1429. return true;
  1430. }
  1431. //////////////////////////////////////////////////////////////////////////////
  1432. //
  1433. // Messages
  1434. //
  1435. bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
  1436. {
  1437. switch (inv.type)
  1438. {
  1439. case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
  1440. case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
  1441. }
  1442. // Don't know what it is, just say we already got one
  1443. return true;
  1444. }
  1445. // The message start string is designed to be unlikely to occur in normal data.
  1446. // The characters are rarely used upper ascii, not valid as UTF-8, and produce
  1447. // a large 4-byte int at any alignment.
  1448. char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
  1449. bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
  1450. {
  1451. static map<unsigned int, vector<unsigned char> > mapReuseKey;
  1452. RandAddSeedPerfmon();
  1453. if (fDebug)
  1454. printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
  1455. printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
  1456. if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
  1457. {
  1458. printf("dropmessagestest DROPPING RECV MESSAGE\n");
  1459. return true;
  1460. }
  1461. if (strCommand == "version")
  1462. {
  1463. // Each connection can only send one version message
  1464. if (pfrom->nVersion != 0)
  1465. return false;
  1466. int64 nTime;
  1467. CAddress addrMe;
  1468. CAddress addrFrom;
  1469. uint64 nNonce = 1;
  1470. vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
  1471. if (pfrom->nVersion == 10300)
  1472. pfrom->nVersion = 300;
  1473. if (pfrom->nVersion >= 106 && !vRecv.empty())
  1474. vRecv >> addrFrom >> nNonce;
  1475. if (pfrom->nVersion >= 106 && !vRecv.empty())
  1476. vRecv >> pfrom->strSubVer;
  1477. if (pfrom->nVersion >= 209 && !vRecv.empty())
  1478. vRecv >> pfrom->nStartingHeight;
  1479. if (pfrom->nVersion == 0)
  1480. return false;
  1481. // Disconnect if we connected to ourself
  1482. if (nNonce == nLocalHostNonce && nNonce > 1)
  1483. {
  1484. printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
  1485. pfrom->fDisconnect = true;
  1486. return true;
  1487. }
  1488. // Be shy and don't send version until we hear
  1489. if (pfrom->fInbound)
  1490. pfrom->PushVersion();
  1491. pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
  1492. AddTimeData(pfrom->addr.ip, nTime);
  1493. // Change version
  1494. if (pfrom->nVersion >= 209)
  1495. pfrom->PushMessage("verack");
  1496. pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
  1497. if (pfrom->nVersion < 209)
  1498. pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
  1499. if (!pfrom->fInbound)
  1500. {
  1501. // Advertise our address
  1502. if (addrLocalHost.IsRoutable() && !fUseProxy)
  1503. {
  1504. CAddress addr(addrLocalHost);
  1505. addr.nTime = GetAdjustedTime();
  1506. pfrom->PushAddress(addr);
  1507. }
  1508. // Get recent addresses
  1509. if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
  1510. {
  1511. pfrom->PushMessage("getaddr");
  1512. pfrom->fGetAddr = true;
  1513. }
  1514. }
  1515. // Ask the first connected node for block updates
  1516. static int nAskedForBlocks;
  1517. if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
  1518. {
  1519. nAskedForBlocks++;
  1520. pfrom->PushGetBlocks(pindexBest, uint256(0));
  1521. }
  1522. // Relay alerts
  1523. CRITICAL_BLOCK(cs_mapAlerts)
  1524. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  1525. item.second.RelayTo(pfrom);
  1526. pfrom->fSuccessfullyConnected = true;
  1527. printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
  1528. }
  1529. else if (pfrom->nVersion == 0)
  1530. {
  1531. // Must have a version message before anything else
  1532. return false;
  1533. }
  1534. else if (strCommand == "verack")
  1535. {
  1536. pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
  1537. }
  1538. else if (strCommand == "addr")
  1539. {
  1540. vector<CAddress> vAddr;
  1541. vRecv >> vAddr;
  1542. // Don't want addr from older versions unless seeding
  1543. if (pfrom->nVersion < 209)
  1544. return true;
  1545. if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
  1546. return true;
  1547. if (vAddr.size() > 1000)
  1548. return error("message addr size() = %d", vAddr.size());
  1549. // Store the new addresses
  1550. int64 nNow = GetAdjustedTime();
  1551. int64 nSince = nNow - 10 * 60;
  1552. BOOST_FOREACH(CAddress& addr, vAddr)
  1553. {
  1554. if (fShutdown)
  1555. return true;
  1556. // ignore IPv6 for now, since it isn't implemented anyway
  1557. if (!addr.IsIPv4())
  1558. continue;
  1559. if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
  1560. addr.nTime = nNow - 5 * 24 * 60 * 60;
  1561. AddAddress(addr, 2 * 60 * 60);
  1562. pfrom->AddAddressKnown(addr);
  1563. if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
  1564. {
  1565. // Relay to a limited number of other nodes
  1566. CRITICAL_BLOCK(cs_vNodes)
  1567. {
  1568. // Use deterministic randomness to send to the same nodes for 24 hours
  1569. // at a time so the setAddrKnowns of the chosen nodes prevent repeats
  1570. static uint256 hashSalt;
  1571. if (hashSalt == 0)
  1572. RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
  1573. uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
  1574. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  1575. multimap<uint256, CNode*> mapMix;
  1576. BOOST_FOREACH(CNode* pnode, vNodes)
  1577. {
  1578. if (pnode->nVersion < 31402)
  1579. continue;
  1580. unsigned int nPointer;
  1581. memcpy(&nPointer, &pnode, sizeof(nPointer));
  1582. uint256 hashKey = hashRand ^ nPointer;
  1583. hashKey = Hash(BEGIN(hashKey), END(hashKey));
  1584. mapMix.insert(make_pair(hashKey, pnode));
  1585. }
  1586. int nRelayNodes = 2;
  1587. for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
  1588. ((*mi).second)->PushAddress(addr);
  1589. }
  1590. }
  1591. }
  1592. if (vAddr.size() < 1000)
  1593. pfrom->fGetAddr = false;
  1594. }
  1595. else if (strCommand == "inv")
  1596. {
  1597. vector<CInv> vInv;
  1598. vRecv >> vInv;
  1599. if (vInv.size() > 50000)
  1600. return error("message inv size() = %d", vInv.size());
  1601. CTxDB txdb("r");
  1602. BOOST_FOREACH(const CInv& inv, vInv)
  1603. {
  1604. if (fShutdown)
  1605. return true;
  1606. pfrom->AddInventoryKnown(inv);
  1607. bool fAlreadyHave = AlreadyHave(txdb, inv);
  1608. printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
  1609. if (!fAlreadyHave)
  1610. pfrom->AskFor(inv);
  1611. else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
  1612. pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
  1613. // Track requests for our stuff
  1614. Inventory(inv.hash);
  1615. }
  1616. }
  1617. else if (strCommand == "getdata")
  1618. {
  1619. vector<CInv> vInv;
  1620. vRecv >> vInv;
  1621. if (vInv.size() > 50000)
  1622. return error("message getdata size() = %d", vInv.size());
  1623. BOOST_FOREACH(const CInv& inv, vInv)
  1624. {
  1625. if (fShutdown)
  1626. return true;
  1627. printf("received getdata for: %s\n", inv.ToString().c_str());
  1628. if (inv.type == MSG_BLOCK)
  1629. {
  1630. // Send block from disk
  1631. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
  1632. if (mi != mapBlockIndex.end())
  1633. {
  1634. CBlock block;
  1635. block.ReadFromDisk((*mi).second);
  1636. pfrom->PushMessage("block", block);
  1637. // Trigger them to send a getblocks request for the next batch of inventory
  1638. if (inv.hash == pfrom->hashContinue)
  1639. {
  1640. // Bypass PushInventory, this must send even if redundant,
  1641. // and we want it right after the last block so they don't
  1642. // wait for other stuff first.
  1643. vector<CInv> vInv;
  1644. vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
  1645. pfrom->PushMessage("inv", vInv);
  1646. pfrom->hashContinue = 0;
  1647. }
  1648. }
  1649. }
  1650. else if (inv.IsKnownType())
  1651. {
  1652. // Send stream from relay memory
  1653. CRITICAL_BLOCK(cs_mapRelay)
  1654. {
  1655. map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
  1656. if (mi != mapRelay.end())
  1657. pfrom->PushMessage(inv.GetCommand(), (*mi).second);
  1658. }
  1659. }
  1660. // Track requests for our stuff
  1661. Inventory(inv.hash);
  1662. }
  1663. }
  1664. else if (strCommand == "getblocks")
  1665. {
  1666. CBlockLocator locator;
  1667. uint256 hashStop;
  1668. vRecv >> locator >> hashStop;
  1669. // Find the last block the caller has in the main chain
  1670. CBlockIndex* pindex = locator.GetBlockIndex();
  1671. // Send the rest of the chain
  1672. if (pindex)
  1673. pindex = pindex->pnext;
  1674. int nLimit = 500 + locator.GetDistanceBack();
  1675. unsigned int nBytes = 0;
  1676. printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
  1677. for (; pindex; pindex = pindex->pnext)
  1678. {
  1679. if (pindex->GetBlockHash() == hashStop)
  1680. {
  1681. printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
  1682. break;
  1683. }
  1684. pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
  1685. CBlock block;
  1686. block.ReadFromDisk(pindex, true);
  1687. nBytes += block.GetSerializeSize(SER_NETWORK);
  1688. if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
  1689. {
  1690. // When this block is requested, we'll send an inv that'll make them
  1691. // getblocks the next batch of inventory.
  1692. printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
  1693. pfrom->hashContinue = pindex->GetBlockHash();
  1694. break;
  1695. }
  1696. }
  1697. }
  1698. else if (strCommand == "getheaders")
  1699. {
  1700. CBlockLocator locator;
  1701. uint256 hashStop;
  1702. vRecv >> locator >> hashStop;
  1703. CBlockIndex* pindex = NULL;
  1704. if (locator.IsNull())
  1705. {
  1706. // If locator is null, return the hashStop block
  1707. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
  1708. if (mi == mapBlockIndex.end())
  1709. return true;
  1710. pindex = (*mi).second;
  1711. }
  1712. else
  1713. {
  1714. // Find the last block the caller has in the main chain
  1715. pindex = locator.GetBlockIndex();
  1716. if (pindex)
  1717. pindex = pindex->pnext;
  1718. }
  1719. vector<CBlock> vHeaders;
  1720. int nLimit = 2000 + locator.GetDistanceBack();
  1721. printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
  1722. for (; pindex; pindex = pindex->pnext)
  1723. {
  1724. vHeaders.push_back(pindex->GetBlockHeader());
  1725. if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
  1726. break;
  1727. }
  1728. pfrom->PushMessage("headers", vHeaders);
  1729. }
  1730. else if (strCommand == "tx")
  1731. {
  1732. vector<uint256> vWorkQueue;
  1733. CDataStream vMsg(vRecv);
  1734. CTransaction tx;
  1735. vRecv >> tx;
  1736. CInv inv(MSG_TX, tx.GetHash());
  1737. pfrom->AddInventoryKnown(inv);
  1738. bool fMissingInputs = false;
  1739. if (tx.AcceptToMemoryPool(true, &fMissingInputs))
  1740. {
  1741. SyncWithWallets(tx, NULL, true);
  1742. RelayMessage(inv, vMsg);
  1743. mapAlreadyAskedFor.erase(inv);
  1744. vWorkQueue.push_back(inv.hash);
  1745. // Recursively process any orphan transactions that depended on this one
  1746. for (int i = 0; i < vWorkQueue.size(); i++)
  1747. {
  1748. uint256 hashPrev = vWorkQueue[i];
  1749. for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
  1750. mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
  1751. ++mi)
  1752. {
  1753. const CDataStream& vMsg = *((*mi).second);
  1754. CTransaction tx;
  1755. CDataStream(vMsg) >> tx;
  1756. CInv inv(MSG_TX, tx.GetHash());
  1757. if (tx.AcceptToMemoryPool(true))
  1758. {
  1759. printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
  1760. SyncWithWallets(tx, NULL, true);
  1761. RelayMessage(inv, vMsg);
  1762. mapAlreadyAskedFor.erase(inv);
  1763. vWorkQueue.push_back(inv.hash);
  1764. }
  1765. }
  1766. }
  1767. BOOST_FOREACH(uint256 hash, vWorkQueue)
  1768. EraseOrphanTx(hash);
  1769. }
  1770. else if (fMissingInputs)
  1771. {
  1772. printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
  1773. AddOrphanTx(vMsg);
  1774. }
  1775. }
  1776. else if (strCommand == "block")
  1777. {
  1778. CBlock block;
  1779. vRecv >> block;
  1780. printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
  1781. // block.print();
  1782. CInv inv(MSG_BLOCK, block.GetHash());
  1783. pfrom->AddInventoryKnown(inv);
  1784. if (ProcessBlock(pfrom, &block))
  1785. mapAlreadyAskedFor.erase(inv);
  1786. }
  1787. else if (strCommand == "getaddr")
  1788. {
  1789. // Nodes rebroadcast an addr every 24 hours
  1790. pfrom->vAddrToSend.clear();
  1791. int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
  1792. CRITICAL_BLOCK(cs_mapAddresses)
  1793. {
  1794. unsigned int nCount = 0;
  1795. BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
  1796. {
  1797. const CAddress& addr = item.second;
  1798. if (addr.nTime > nSince)
  1799. nCount++;
  1800. }
  1801. BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
  1802. {
  1803. const CAddress& addr = item.second;
  1804. if (addr.nTime > nSince && GetRand(nCount) < 2500)
  1805. pfrom->PushAddress(addr);
  1806. }
  1807. }
  1808. }
  1809. else if (strCommand == "checkorder")
  1810. {
  1811. uint256 hashReply;
  1812. vRecv >> hashReply;
  1813. if (!GetBoolArg("-allowreceivebyip"))
  1814. {
  1815. pfrom->PushMessage("reply", hashReply, (int)2, string(""));
  1816. return true;
  1817. }
  1818. CWalletTx order;
  1819. vRecv >> order;
  1820. /// we have a chance to check the order here
  1821. // Keep giving the same key to the same ip until they use it
  1822. if (!mapReuseKey.count(pfrom->addr.ip))
  1823. mapReuseKey[pfrom->addr.ip] = pwalletMain->GetKeyFromKeyPool();
  1824. // Send back approval of order and pubkey to use
  1825. CScript scriptPubKey;
  1826. scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
  1827. pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
  1828. }
  1829. else if (strCommand == "reply")
  1830. {
  1831. uint256 hashReply;
  1832. vRecv >> hashReply;
  1833. CRequestTracker tracker;
  1834. CRITICAL_BLOCK(pfrom->cs_mapRequests)
  1835. {
  1836. map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
  1837. if (mi != pfrom->mapRequests.end())
  1838. {
  1839. tracker = (*mi).second;
  1840. pfrom->mapRequests.erase(mi);
  1841. }
  1842. }
  1843. if (!tracker.IsNull())
  1844. tracker.fn(tracker.param1, vRecv);
  1845. }
  1846. else if (strCommand == "ping")
  1847. {
  1848. }
  1849. else if (strCommand == "alert")
  1850. {
  1851. CAlert alert;
  1852. vRecv >> alert;
  1853. if (alert.ProcessAlert())
  1854. {
  1855. // Relay
  1856. pfrom->setKnown.insert(alert.GetHash());
  1857. CRITICAL_BLOCK(cs_vNodes)
  1858. BOOST_FOREACH(CNode* pnode, vNodes)
  1859. alert.RelayTo(pnode);
  1860. }
  1861. }
  1862. else
  1863. {
  1864. // Ignore unknown commands for extensibility
  1865. }
  1866. // Update the last seen time for this node's address
  1867. if (pfrom->fNetworkNode)
  1868. if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
  1869. AddressCurrentlyConnected(pfrom->addr);
  1870. return true;
  1871. }
  1872. bool ProcessMessages(CNode* pfrom)
  1873. {
  1874. CDataStream& vRecv = pfrom->vRecv;
  1875. if (vRecv.empty())
  1876. return true;
  1877. //if (fDebug)
  1878. // printf("ProcessMessages(%u bytes)\n", vRecv.size());
  1879. //
  1880. // Message format
  1881. // (4) message start
  1882. // (12) command
  1883. // (4) size
  1884. // (4) checksum
  1885. // (x) data
  1886. //
  1887. loop
  1888. {
  1889. // Scan for message start
  1890. CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
  1891. int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
  1892. if (vRecv.end() - pstart < nHeaderSize)
  1893. {
  1894. if (vRecv.size() > nHeaderSize)
  1895. {
  1896. printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
  1897. vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
  1898. }
  1899. break;
  1900. }
  1901. if (pstart - vRecv.begin() > 0)
  1902. printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
  1903. vRecv.erase(vRecv.begin(), pstart);
  1904. // Read header
  1905. vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
  1906. CMessageHeader hdr;
  1907. vRecv >> hdr;
  1908. if (!hdr.IsValid())
  1909. {
  1910. printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
  1911. continue;
  1912. }
  1913. string strCommand = hdr.GetCommand();
  1914. // Message size
  1915. unsigned int nMessageSize = hdr.nMessageSize;
  1916. if (nMessageSize > MAX_SIZE)
  1917. {
  1918. printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
  1919. continue;
  1920. }
  1921. if (nMessageSize > vRecv.size())
  1922. {
  1923. // Rewind and wait for rest of message
  1924. vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
  1925. break;
  1926. }
  1927. // Checksum
  1928. if (vRecv.GetVersion() >= 209)
  1929. {
  1930. uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
  1931. unsigned int nChecksum = 0;
  1932. memcpy(&nChecksum, &hash, sizeof(nChecksum));
  1933. if (nChecksum != hdr.nChecksum)
  1934. {
  1935. printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
  1936. strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
  1937. continue;
  1938. }
  1939. }
  1940. // Copy message to its own buffer
  1941. CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
  1942. vRecv.ignore(nMessageSize);
  1943. // Process message
  1944. bool fRet = false;
  1945. try
  1946. {
  1947. CRITICAL_BLOCK(cs_main)
  1948. fRet = ProcessMessage(pfrom, strCommand, vMsg);
  1949. if (fShutdown)
  1950. return true;
  1951. }
  1952. catch (std::ios_base::failure& e)
  1953. {
  1954. if (strstr(e.what(), "end of data"))
  1955. {
  1956. // Allow exceptions from underlength message on vRecv
  1957. printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
  1958. }
  1959. else if (strstr(e.what(), "size too large"))
  1960. {
  1961. // Allow exceptions from overlong size
  1962. printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
  1963. }
  1964. else
  1965. {
  1966. PrintExceptionContinue(&e, "ProcessMessage()");
  1967. }
  1968. }
  1969. catch (std::exception& e) {
  1970. PrintExceptionContinue(&e, "ProcessMessage()");
  1971. } catch (...) {
  1972. PrintExceptionContinue(NULL, "ProcessMessage()");
  1973. }
  1974. if (!fRet)
  1975. printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
  1976. }
  1977. vRecv.Compact();
  1978. return true;
  1979. }
  1980. bool SendMessages(CNode* pto, bool fSendTrickle)
  1981. {
  1982. CRITICAL_BLOCK(cs_main)
  1983. {
  1984. // Don't send anything until we get their version message
  1985. if (pto->nVersion == 0)
  1986. return true;
  1987. // Keep-alive ping
  1988. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
  1989. pto->PushMessage("ping");
  1990. // Resend wallet transactions that haven't gotten in a block yet
  1991. ResendWalletTransactions();
  1992. // Address refresh broadcast
  1993. static int64 nLastRebroadcast;
  1994. if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
  1995. {
  1996. nLastRebroadcast = GetTime();
  1997. CRITICAL_BLOCK(cs_vNodes)
  1998. {
  1999. BOOST_FOREACH(CNode* pnode, vNodes)
  2000. {
  2001. // Periodically clear setAddrKnown to allow refresh broadcasts
  2002. pnode->setAddrKnown.clear();
  2003. // Rebroadcast our address
  2004. if (addrLocalHost.IsRoutable() && !fUseProxy)
  2005. {
  2006. CAddress addr(addrLocalHost);
  2007. addr.nTime = GetAdjustedTime();
  2008. pnode->PushAddress(addr);
  2009. }
  2010. }
  2011. }
  2012. }
  2013. // Clear out old addresses periodically so it's not too much work at once
  2014. static int64 nLastClear;
  2015. if (nLastClear == 0)
  2016. nLastClear = GetTime();
  2017. if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
  2018. {
  2019. nLastClear = GetTime();
  2020. CRITICAL_BLOCK(cs_mapAddresses)
  2021. {
  2022. CAddrDB addrdb;
  2023. int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
  2024. for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
  2025. mi != mapAddresses.end();)
  2026. {
  2027. const CAddress& addr = (*mi).second;
  2028. if (addr.nTime < nSince)
  2029. {
  2030. if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
  2031. break;
  2032. addrdb.EraseAddress(addr);
  2033. mapAddresses.erase(mi++);
  2034. }
  2035. else
  2036. mi++;
  2037. }
  2038. }
  2039. }
  2040. //
  2041. // Message: addr
  2042. //
  2043. if (fSendTrickle)
  2044. {
  2045. vector<CAddress> vAddr;
  2046. vAddr.reserve(pto->vAddrToSend.size());
  2047. BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
  2048. {
  2049. // returns true if wasn't already contained in the set
  2050. if (pto->setAddrKnown.insert(addr).second)
  2051. {
  2052. vAddr.push_back(addr);
  2053. // receiver rejects addr messages larger than 1000
  2054. if (vAddr.size() >= 1000)
  2055. {
  2056. pto->PushMessage("addr", vAddr);
  2057. vAddr.clear();
  2058. }
  2059. }
  2060. }
  2061. pto->vAddrToSend.clear();
  2062. if (!vAddr.empty())
  2063. pto->PushMessage("addr", vAddr);
  2064. }
  2065. //
  2066. // Message: inventory
  2067. //
  2068. vector<CInv> vInv;
  2069. vector<CInv> vInvWait;
  2070. CRITICAL_BLOCK(pto->cs_inventory)
  2071. {
  2072. vInv.reserve(pto->vInventoryToSend.size());
  2073. vInvWait.reserve(pto->vInventoryToSend.size());
  2074. BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
  2075. {
  2076. if (pto->setInventoryKnown.count(inv))
  2077. continue;
  2078. // trickle out tx inv to protect privacy
  2079. if (inv.type == MSG_TX && !fSendTrickle)
  2080. {
  2081. // 1/4 of tx invs blast to all immediately
  2082. static uint256 hashSalt;
  2083. if (hashSalt == 0)
  2084. RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
  2085. uint256 hashRand = inv.hash ^ hashSalt;
  2086. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  2087. bool fTrickleWait = ((hashRand & 3) != 0);
  2088. // always trickle our own transactions
  2089. if (!fTrickleWait)
  2090. {
  2091. CWalletTx wtx;
  2092. if (GetTransaction(inv.hash, wtx))
  2093. if (wtx.fFromMe)
  2094. fTrickleWait = true;
  2095. }
  2096. if (fTrickleWait)
  2097. {
  2098. vInvWait.push_back(inv);
  2099. continue;
  2100. }
  2101. }
  2102. // returns true if wasn't already contained in the set
  2103. if (pto->setInventoryKnown.insert(inv).second)
  2104. {
  2105. vInv.push_back(inv);
  2106. if (vInv.size() >= 1000)
  2107. {
  2108. pto->PushMessage("inv", vInv);
  2109. vInv.clear();
  2110. }
  2111. }
  2112. }
  2113. pto->vInventoryToSend = vInvWait;
  2114. }
  2115. if (!vInv.empty())
  2116. pto->PushMessage("inv", vInv);
  2117. //
  2118. // Message: getdata
  2119. //
  2120. vector<CInv> vGetData;
  2121. int64 nNow = GetTime() * 1000000;
  2122. CTxDB txdb("r");
  2123. while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
  2124. {
  2125. const CInv& inv = (*pto->mapAskFor.begin()).second;
  2126. if (!AlreadyHave(txdb, inv))
  2127. {
  2128. printf("sending getdata: %s\n", inv.ToString().c_str());
  2129. vGetData.push_back(inv);
  2130. if (vGetData.size() >= 1000)
  2131. {
  2132. pto->PushMessage("getdata", vGetData);
  2133. vGetData.clear();
  2134. }
  2135. }
  2136. pto->mapAskFor.erase(pto->mapAskFor.begin());
  2137. }
  2138. if (!vGetData.empty())
  2139. pto->PushMessage("getdata", vGetData);
  2140. }
  2141. return true;
  2142. }
  2143. //////////////////////////////////////////////////////////////////////////////
  2144. //
  2145. // BitcoinMiner
  2146. //
  2147. int static FormatHashBlocks(void* pbuffer, unsigned int len)
  2148. {
  2149. unsigned char* pdata = (unsigned char*)pbuffer;
  2150. unsigned int blocks = 1 + ((len + 8) / 64);
  2151. unsigned char* pend = pdata + 64 * blocks;
  2152. memset(pdata + len, 0, 64 * blocks - len);
  2153. pdata[len] = 0x80;
  2154. unsigned int bits = len * 8;
  2155. pend[-1] = (bits >> 0) & 0xff;
  2156. pend[-2] = (bits >> 8) & 0xff;
  2157. pend[-3] = (bits >> 16) & 0xff;
  2158. pend[-4] = (bits >> 24) & 0xff;
  2159. return blocks;
  2160. }
  2161. using CryptoPP::ByteReverse;
  2162. static const unsigned int pSHA256InitState[8] =
  2163. {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
  2164. inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
  2165. {
  2166. memcpy(pstate, pinit, 32);
  2167. CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
  2168. }
  2169. //
  2170. // ScanHash scans nonces looking for a hash with at least some zero bits.
  2171. // It operates on big endian data. Caller does the byte reversing.
  2172. // All input buffers are 16-byte aligned. nNonce is usually preserved
  2173. // between calls, but periodically or if nNonce is 0xffff0000 or above,
  2174. // the block is rebuilt and nNonce starts over at zero.
  2175. //
  2176. unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
  2177. {
  2178. unsigned int& nNonce = *(unsigned int*)(pdata + 12);
  2179. for (;;)
  2180. {
  2181. // Crypto++ SHA-256
  2182. // Hash pdata using pmidstate as the starting state into
  2183. // preformatted buffer phash1, then hash phash1 into phash
  2184. nNonce++;
  2185. SHA256Transform(phash1, pdata, pmidstate);
  2186. SHA256Transform(phash, phash1, pSHA256InitState);
  2187. // Return the nonce if the hash has at least some zero bits,
  2188. // caller will check if it has enough to reach the target
  2189. if (((unsigned short*)phash)[14] == 0)
  2190. return nNonce;
  2191. // If nothing found after trying for a while, return -1
  2192. if ((nNonce & 0xffff) == 0)
  2193. {
  2194. nHashesDone = 0xffff+1;
  2195. return -1;
  2196. }
  2197. }
  2198. }
  2199. class COrphan
  2200. {
  2201. public:
  2202. CTransaction* ptx;
  2203. set<uint256> setDependsOn;
  2204. double dPriority;
  2205. COrphan(CTransaction* ptxIn)
  2206. {
  2207. ptx = ptxIn;
  2208. dPriority = 0;
  2209. }
  2210. void print() const
  2211. {
  2212. printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
  2213. BOOST_FOREACH(uint256 hash, setDependsOn)
  2214. printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
  2215. }
  2216. };
  2217. CBlock* CreateNewBlock(CReserveKey& reservekey)
  2218. {
  2219. CBlockIndex* pindexPrev = pindexBest;
  2220. // Create new block
  2221. auto_ptr<CBlock> pblock(new CBlock());
  2222. if (!pblock.get())
  2223. return NULL;
  2224. // Create coinbase tx
  2225. CTransaction txNew;
  2226. txNew.vin.resize(1);
  2227. txNew.vin[0].prevout.SetNull();
  2228. txNew.vout.resize(1);
  2229. txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
  2230. // Add our coinbase tx as first transaction
  2231. pblock->vtx.push_back(txNew);
  2232. // Collect memory pool transactions into the block
  2233. int64 nFees = 0;
  2234. CRITICAL_BLOCK(cs_main)
  2235. CRITICAL_BLOCK(cs_mapTransactions)
  2236. {
  2237. CTxDB txdb("r");
  2238. // Priority order to process transactions
  2239. list<COrphan> vOrphan; // list memory doesn't move
  2240. map<uint256, vector<COrphan*> > mapDependers;
  2241. multimap<double, CTransaction*> mapPriority;
  2242. for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
  2243. {
  2244. CTransaction& tx = (*mi).second;
  2245. if (tx.IsCoinBase() || !tx.IsFinal())
  2246. continue;
  2247. COrphan* porphan = NULL;
  2248. double dPriority = 0;
  2249. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  2250. {
  2251. // Read prev transaction
  2252. CTransaction txPrev;
  2253. CTxIndex txindex;
  2254. if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
  2255. {
  2256. // Has to wait for dependencies
  2257. if (!porphan)
  2258. {
  2259. // Use list for automatic deletion
  2260. vOrphan.push_back(COrphan(&tx));
  2261. porphan = &vOrphan.back();
  2262. }
  2263. mapDependers[txin.prevout.hash].push_back(porphan);
  2264. porphan->setDependsOn.insert(txin.prevout.hash);
  2265. continue;
  2266. }
  2267. int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
  2268. // Read block header
  2269. int nConf = txindex.GetDepthInMainChain();
  2270. dPriority += (double)nValueIn * nConf;
  2271. if (fDebug && GetBoolArg("-printpriority"))
  2272. printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
  2273. }
  2274. // Priority is sum(valuein * age) / txsize
  2275. dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
  2276. if (porphan)
  2277. porphan->dPriority = dPriority;
  2278. else
  2279. mapPriority.insert(make_pair(-dPriority, &(*mi).second));
  2280. if (fDebug && GetBoolArg("-printpriority"))
  2281. {
  2282. printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
  2283. if (porphan)
  2284. porphan->print();
  2285. printf("\n");
  2286. }
  2287. }
  2288. // Collect transactions into block
  2289. map<uint256, CTxIndex> mapTestPool;
  2290. uint64 nBlockSize = 1000;
  2291. int nBlockSigOps = 100;
  2292. while (!mapPriority.empty())
  2293. {
  2294. // Take highest priority transaction off priority queue
  2295. double dPriority = -(*mapPriority.begin()).first;
  2296. CTransaction& tx = *(*mapPriority.begin()).second;
  2297. mapPriority.erase(mapPriority.begin());
  2298. // Size limits
  2299. unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
  2300. if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
  2301. continue;
  2302. int nTxSigOps = tx.GetSigOpCount();
  2303. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
  2304. continue;
  2305. // Transaction fee required depends on block size
  2306. bool fAllowFree = (nBlockSize + nTxSize < 4000 || CTransaction::AllowFree(dPriority));
  2307. int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, true);
  2308. // Connecting shouldn't fail due to dependency on other memory pool transactions
  2309. // because we're already processing them in order of dependency
  2310. map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
  2311. if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
  2312. continue;
  2313. swap(mapTestPool, mapTestPoolTmp);
  2314. // Added
  2315. pblock->vtx.push_back(tx);
  2316. nBlockSize += nTxSize;
  2317. nBlockSigOps += nTxSigOps;
  2318. // Add transactions that depend on this one to the priority queue
  2319. uint256 hash = tx.GetHash();
  2320. if (mapDependers.count(hash))
  2321. {
  2322. BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
  2323. {
  2324. if (!porphan->setDependsOn.empty())
  2325. {
  2326. porphan->setDependsOn.erase(hash);
  2327. if (porphan->setDependsOn.empty())
  2328. mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
  2329. }
  2330. }
  2331. }
  2332. }
  2333. }
  2334. pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
  2335. // Fill in header
  2336. pblock->hashPrevBlock = pindexPrev->GetBlockHash();
  2337. pblock->hashMerkleRoot = pblock->BuildMerkleTree();
  2338. pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
  2339. pblock->nBits = GetNextWorkRequired(pindexPrev);
  2340. pblock->nNonce = 0;
  2341. return pblock.release();
  2342. }
  2343. void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime)
  2344. {
  2345. // Update nExtraNonce
  2346. int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
  2347. if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
  2348. {
  2349. nExtraNonce = 1;
  2350. nPrevTime = nNow;
  2351. }
  2352. pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nBits << CBigNum(nExtraNonce);
  2353. pblock->hashMerkleRoot = pblock->BuildMerkleTree();
  2354. }
  2355. void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
  2356. {
  2357. //
  2358. // Prebuild hash buffers
  2359. //
  2360. struct
  2361. {
  2362. struct unnamed2
  2363. {
  2364. int nVersion;
  2365. uint256 hashPrevBlock;
  2366. uint256 hashMerkleRoot;
  2367. unsigned int nTime;
  2368. unsigned int nBits;
  2369. unsigned int nNonce;
  2370. }
  2371. block;
  2372. unsigned char pchPadding0[64];
  2373. uint256 hash1;
  2374. unsigned char pchPadding1[64];
  2375. }
  2376. tmp;
  2377. memset(&tmp, 0, sizeof(tmp));
  2378. tmp.block.nVersion = pblock->nVersion;
  2379. tmp.block.hashPrevBlock = pblock->hashPrevBlock;
  2380. tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
  2381. tmp.block.nTime = pblock->nTime;
  2382. tmp.block.nBits = pblock->nBits;
  2383. tmp.block.nNonce = pblock->nNonce;
  2384. FormatHashBlocks(&tmp.block, sizeof(tmp.block));
  2385. FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
  2386. // Byte swap all the input buffer
  2387. for (int i = 0; i < sizeof(tmp)/4; i++)
  2388. ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
  2389. // Precalc the first half of the first hash, which stays constant
  2390. SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
  2391. memcpy(pdata, &tmp.block, 128);
  2392. memcpy(phash1, &tmp.hash1, 64);
  2393. }
  2394. bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
  2395. {
  2396. uint256 hash = pblock->GetHash();
  2397. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  2398. if (hash > hashTarget)
  2399. return false;
  2400. //// debug print
  2401. printf("BitcoinMiner:\n");
  2402. printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
  2403. pblock->print();
  2404. printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
  2405. printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
  2406. // Found a solution
  2407. CRITICAL_BLOCK(cs_main)
  2408. {
  2409. if (pblock->hashPrevBlock != hashBestChain)
  2410. return error("BitcoinMiner : generated block is stale");
  2411. // Remove key from key pool
  2412. reservekey.KeepKey();
  2413. // Track how many getdata requests this block gets
  2414. CRITICAL_BLOCK(wallet.cs_mapRequestCount)
  2415. wallet.mapRequestCount[pblock->GetHash()] = 0;
  2416. // Process this block the same as if we had received it from another node
  2417. if (!ProcessBlock(NULL, pblock))
  2418. return error("BitcoinMiner : ProcessBlock, block not accepted");
  2419. }
  2420. Sleep(2000);
  2421. return true;
  2422. }
  2423. void static ThreadBitcoinMiner(void* parg);
  2424. void static BitcoinMiner(CWallet *pwallet)
  2425. {
  2426. printf("BitcoinMiner started\n");
  2427. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  2428. // Each thread has its own key and counter
  2429. CReserveKey reservekey(pwallet);
  2430. unsigned int nExtraNonce = 0;
  2431. int64 nPrevTime = 0;
  2432. while (fGenerateBitcoins)
  2433. {
  2434. if (AffinityBugWorkaround(ThreadBitcoinMiner))
  2435. return;
  2436. if (fShutdown)
  2437. return;
  2438. while (vNodes.empty() || IsInitialBlockDownload())
  2439. {
  2440. Sleep(1000);
  2441. if (fShutdown)
  2442. return;
  2443. if (!fGenerateBitcoins)
  2444. return;
  2445. }
  2446. //
  2447. // Create new block
  2448. //
  2449. unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
  2450. CBlockIndex* pindexPrev = pindexBest;
  2451. auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
  2452. if (!pblock.get())
  2453. return;
  2454. IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce, nPrevTime);
  2455. printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
  2456. //
  2457. // Prebuild hash buffers
  2458. //
  2459. char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
  2460. char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
  2461. char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
  2462. FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
  2463. unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
  2464. unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
  2465. //
  2466. // Search
  2467. //
  2468. int64 nStart = GetTime();
  2469. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  2470. uint256 hashbuf[2];
  2471. uint256& hash = *alignup<16>(hashbuf);
  2472. loop
  2473. {
  2474. unsigned int nHashesDone = 0;
  2475. unsigned int nNonceFound;
  2476. // Crypto++ SHA-256
  2477. nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
  2478. (char*)&hash, nHashesDone);
  2479. // Check if something found
  2480. if (nNonceFound != -1)
  2481. {
  2482. for (int i = 0; i < sizeof(hash)/4; i++)
  2483. ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
  2484. if (hash <= hashTarget)
  2485. {
  2486. // Found a solution
  2487. pblock->nNonce = ByteReverse(nNonceFound);
  2488. assert(hash == pblock->GetHash());
  2489. SetThreadPriority(THREAD_PRIORITY_NORMAL);
  2490. CheckWork(pblock.get(), *pwalletMain, reservekey);
  2491. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  2492. break;
  2493. }
  2494. }
  2495. // Meter hashes/sec
  2496. static int64 nHashCounter;
  2497. if (nHPSTimerStart == 0)
  2498. {
  2499. nHPSTimerStart = GetTimeMillis();
  2500. nHashCounter = 0;
  2501. }
  2502. else
  2503. nHashCounter += nHashesDone;
  2504. if (GetTimeMillis() - nHPSTimerStart > 4000)
  2505. {
  2506. static CCriticalSection cs;
  2507. CRITICAL_BLOCK(cs)
  2508. {
  2509. if (GetTimeMillis() - nHPSTimerStart > 4000)
  2510. {
  2511. dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
  2512. nHPSTimerStart = GetTimeMillis();
  2513. nHashCounter = 0;
  2514. string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
  2515. UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
  2516. static int64 nLogTime;
  2517. if (GetTime() - nLogTime > 30 * 60)
  2518. {
  2519. nLogTime = GetTime();
  2520. printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
  2521. printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
  2522. }
  2523. }
  2524. }
  2525. }
  2526. // Check for stop or if block needs to be rebuilt
  2527. if (fShutdown)
  2528. return;
  2529. if (!fGenerateBitcoins)
  2530. return;
  2531. if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
  2532. return;
  2533. if (vNodes.empty())
  2534. break;
  2535. if (nBlockNonce >= 0xffff0000)
  2536. break;
  2537. if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
  2538. break;
  2539. if (pindexPrev != pindexBest)
  2540. break;
  2541. // Update nTime every few seconds
  2542. pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
  2543. nBlockTime = ByteReverse(pblock->nTime);
  2544. }
  2545. }
  2546. }
  2547. void static ThreadBitcoinMiner(void* parg)
  2548. {
  2549. CWallet* pwallet = (CWallet*)parg;
  2550. try
  2551. {
  2552. vnThreadsRunning[3]++;
  2553. BitcoinMiner(pwallet);
  2554. vnThreadsRunning[3]--;
  2555. }
  2556. catch (std::exception& e) {
  2557. vnThreadsRunning[3]--;
  2558. PrintException(&e, "ThreadBitcoinMiner()");
  2559. } catch (...) {
  2560. vnThreadsRunning[3]--;
  2561. PrintException(NULL, "ThreadBitcoinMiner()");
  2562. }
  2563. UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
  2564. nHPSTimerStart = 0;
  2565. if (vnThreadsRunning[3] == 0)
  2566. dHashesPerSec = 0;
  2567. printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
  2568. }
  2569. void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
  2570. {
  2571. if (fGenerateBitcoins != fGenerate)
  2572. {
  2573. fGenerateBitcoins = fGenerate;
  2574. WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
  2575. MainFrameRepaint();
  2576. }
  2577. if (fGenerateBitcoins)
  2578. {
  2579. int nProcessors = boost::thread::hardware_concurrency();
  2580. printf("%d processors\n", nProcessors);
  2581. if (nProcessors < 1)
  2582. nProcessors = 1;
  2583. if (fLimitProcessors && nProcessors > nLimitProcessors)
  2584. nProcessors = nLimitProcessors;
  2585. int nAddThreads = nProcessors - vnThreadsRunning[3];
  2586. printf("Starting %d BitcoinMiner threads\n", nAddThreads);
  2587. for (int i = 0; i < nAddThreads; i++)
  2588. {
  2589. if (!CreateThread(ThreadBitcoinMiner, pwallet))
  2590. printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
  2591. Sleep(10);
  2592. }
  2593. }
  2594. }