PageRenderTime 49ms CodeModel.GetById 38ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main.cpp

https://github.com/peterooch/litecoin
C++ | 3856 lines | 2766 code | 606 blank | 484 comment | 737 complexity | b78adddad1430f1ee0e1e9c0bca2f03c MD5 | raw file
Possible License(s): 0BSD, GPL-3.0, MIT
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2012 The Bitcoin developers
  3. // Copyright (c) 2011-2012 Litecoin Developers
  4. // Distributed under the MIT/X11 software license, see the accompanying
  5. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  6. #include "checkpoints.h"
  7. #include "db.h"
  8. #include "net.h"
  9. #include "init.h"
  10. #include "ui_interface.h"
  11. #include <boost/algorithm/string/replace.hpp>
  12. #include <boost/filesystem.hpp>
  13. #include <boost/filesystem/fstream.hpp>
  14. using namespace std;
  15. using namespace boost;
  16. //
  17. // Global state
  18. //
  19. CCriticalSection cs_setpwalletRegistered;
  20. set<CWallet*> setpwalletRegistered;
  21. CCriticalSection cs_main;
  22. CTxMemPool mempool;
  23. unsigned int nTransactionsUpdated = 0;
  24. map<uint256, CBlockIndex*> mapBlockIndex;
  25. uint256 hashGenesisBlock("0x12a765e31ffd4059bada1e25190f6e98c99d9714d334efa41a195a7e7e04bfe2");
  26. static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // Litecoin: starting difficulty is 1 / 2^12
  27. CBlockIndex* pindexGenesisBlock = NULL;
  28. int nBestHeight = -1;
  29. CBigNum bnBestChainWork = 0;
  30. CBigNum bnBestInvalidWork = 0;
  31. uint256 hashBestChain = 0;
  32. CBlockIndex* pindexBest = NULL;
  33. int64 nTimeBestReceived = 0;
  34. CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
  35. map<uint256, CBlock*> mapOrphanBlocks;
  36. multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
  37. map<uint256, CDataStream*> mapOrphanTransactions;
  38. map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
  39. // Constant stuff for coinbase transactions we create:
  40. CScript COINBASE_FLAGS;
  41. const string strMessageMagic = "Litecoin Signed Message:\n";
  42. double dHashesPerSec;
  43. int64 nHPSTimerStart;
  44. // Settings
  45. int64 nTransactionFee = 0;
  46. int64 nMinimumInputValue = CENT / 100;
  47. //////////////////////////////////////////////////////////////////////////////
  48. //
  49. // dispatching functions
  50. //
  51. // These functions dispatch to one or all registered wallets
  52. void RegisterWallet(CWallet* pwalletIn)
  53. {
  54. {
  55. LOCK(cs_setpwalletRegistered);
  56. setpwalletRegistered.insert(pwalletIn);
  57. }
  58. }
  59. void UnregisterWallet(CWallet* pwalletIn)
  60. {
  61. {
  62. LOCK(cs_setpwalletRegistered);
  63. setpwalletRegistered.erase(pwalletIn);
  64. }
  65. }
  66. // check whether the passed transaction is from us
  67. bool static IsFromMe(CTransaction& tx)
  68. {
  69. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  70. if (pwallet->IsFromMe(tx))
  71. return true;
  72. return false;
  73. }
  74. // get the wallet transaction with the given hash (if it exists)
  75. bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
  76. {
  77. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  78. if (pwallet->GetTransaction(hashTx,wtx))
  79. return true;
  80. return false;
  81. }
  82. // erases transaction with the given hash from all wallets
  83. void static EraseFromWallets(uint256 hash)
  84. {
  85. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  86. pwallet->EraseFromWallet(hash);
  87. }
  88. // make sure all wallets know about the given transaction, in the given block
  89. void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
  90. {
  91. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  92. pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
  93. }
  94. // notify wallets about a new best chain
  95. void static SetBestChain(const CBlockLocator& loc)
  96. {
  97. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  98. pwallet->SetBestChain(loc);
  99. }
  100. // notify wallets about an updated transaction
  101. void static UpdatedTransaction(const uint256& hashTx)
  102. {
  103. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  104. pwallet->UpdatedTransaction(hashTx);
  105. }
  106. // dump all wallets
  107. void static PrintWallets(const CBlock& block)
  108. {
  109. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  110. pwallet->PrintWallet(block);
  111. }
  112. // notify wallets about an incoming inventory (for request counts)
  113. void static Inventory(const uint256& hash)
  114. {
  115. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  116. pwallet->Inventory(hash);
  117. }
  118. // ask wallets to resend their transactions
  119. void static ResendWalletTransactions()
  120. {
  121. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  122. pwallet->ResendWalletTransactions();
  123. }
  124. //////////////////////////////////////////////////////////////////////////////
  125. //
  126. // mapOrphanTransactions
  127. //
  128. bool AddOrphanTx(const CDataStream& vMsg)
  129. {
  130. CTransaction tx;
  131. CDataStream(vMsg) >> tx;
  132. uint256 hash = tx.GetHash();
  133. if (mapOrphanTransactions.count(hash))
  134. return false;
  135. CDataStream* pvMsg = new CDataStream(vMsg);
  136. // Ignore big transactions, to avoid a
  137. // send-big-orphans memory exhaustion attack. If a peer has a legitimate
  138. // large transaction with a missing parent then we assume
  139. // it will rebroadcast it later, after the parent transaction(s)
  140. // have been mined or received.
  141. // 10,000 orphans, each of which is at most 5,000 bytes big is
  142. // at most 500 megabytes of orphans:
  143. if (pvMsg->size() > 5000)
  144. {
  145. printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
  146. delete pvMsg;
  147. return false;
  148. }
  149. mapOrphanTransactions[hash] = pvMsg;
  150. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  151. mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
  152. printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
  153. mapOrphanTransactions.size());
  154. return true;
  155. }
  156. void static EraseOrphanTx(uint256 hash)
  157. {
  158. if (!mapOrphanTransactions.count(hash))
  159. return;
  160. const CDataStream* pvMsg = mapOrphanTransactions[hash];
  161. CTransaction tx;
  162. CDataStream(*pvMsg) >> tx;
  163. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  164. {
  165. mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
  166. if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
  167. mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
  168. }
  169. delete pvMsg;
  170. mapOrphanTransactions.erase(hash);
  171. }
  172. unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
  173. {
  174. unsigned int nEvicted = 0;
  175. while (mapOrphanTransactions.size() > nMaxOrphans)
  176. {
  177. // Evict a random orphan:
  178. uint256 randomhash = GetRandHash();
  179. map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
  180. if (it == mapOrphanTransactions.end())
  181. it = mapOrphanTransactions.begin();
  182. EraseOrphanTx(it->first);
  183. ++nEvicted;
  184. }
  185. return nEvicted;
  186. }
  187. //////////////////////////////////////////////////////////////////////////////
  188. //
  189. // CTransaction and CTxIndex
  190. //
  191. bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
  192. {
  193. SetNull();
  194. if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
  195. return false;
  196. if (!ReadFromDisk(txindexRet.pos))
  197. return false;
  198. if (prevout.n >= vout.size())
  199. {
  200. SetNull();
  201. return false;
  202. }
  203. return true;
  204. }
  205. bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
  206. {
  207. CTxIndex txindex;
  208. return ReadFromDisk(txdb, prevout, txindex);
  209. }
  210. bool CTransaction::ReadFromDisk(COutPoint prevout)
  211. {
  212. CTxDB txdb("r");
  213. CTxIndex txindex;
  214. return ReadFromDisk(txdb, prevout, txindex);
  215. }
  216. bool CTransaction::IsStandard() const
  217. {
  218. if (nVersion > CTransaction::CURRENT_VERSION)
  219. return false;
  220. BOOST_FOREACH(const CTxIn& txin, vin)
  221. {
  222. // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
  223. // pay-to-script-hash, which is 3 ~80-byte signatures, 3
  224. // ~65-byte public keys, plus a few script ops.
  225. if (txin.scriptSig.size() > 500)
  226. return false;
  227. if (!txin.scriptSig.IsPushOnly())
  228. return false;
  229. }
  230. BOOST_FOREACH(const CTxOut& txout, vout)
  231. if (!::IsStandard(txout.scriptPubKey))
  232. return false;
  233. return true;
  234. }
  235. //
  236. // Check transaction inputs, and make sure any
  237. // pay-to-script-hash transactions are evaluating IsStandard scripts
  238. //
  239. // Why bother? To avoid denial-of-service attacks; an attacker
  240. // can submit a standard HASH... OP_EQUAL transaction,
  241. // which will get accepted into blocks. The redemption
  242. // script can be anything; an attacker could use a very
  243. // expensive-to-check-upon-redemption script like:
  244. // DUP CHECKSIG DROP ... repeated 100 times... OP_1
  245. //
  246. bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
  247. {
  248. if (IsCoinBase())
  249. return true; // Coinbases don't use vin normally
  250. for (unsigned int i = 0; i < vin.size(); i++)
  251. {
  252. const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
  253. vector<vector<unsigned char> > vSolutions;
  254. txnouttype whichType;
  255. // get the scriptPubKey corresponding to this input:
  256. const CScript& prevScript = prev.scriptPubKey;
  257. if (!Solver(prevScript, whichType, vSolutions))
  258. return false;
  259. int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
  260. if (nArgsExpected < 0)
  261. return false;
  262. // Transactions with extra stuff in their scriptSigs are
  263. // non-standard. Note that this EvalScript() call will
  264. // be quick, because if there are any operations
  265. // beside "push data" in the scriptSig the
  266. // IsStandard() call returns false
  267. vector<vector<unsigned char> > stack;
  268. if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
  269. return false;
  270. if (whichType == TX_SCRIPTHASH)
  271. {
  272. if (stack.empty())
  273. return false;
  274. CScript subscript(stack.back().begin(), stack.back().end());
  275. vector<vector<unsigned char> > vSolutions2;
  276. txnouttype whichType2;
  277. if (!Solver(subscript, whichType2, vSolutions2))
  278. return false;
  279. if (whichType2 == TX_SCRIPTHASH)
  280. return false;
  281. int tmpExpected;
  282. tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
  283. if (tmpExpected < 0)
  284. return false;
  285. nArgsExpected += tmpExpected;
  286. }
  287. if (stack.size() != (unsigned int)nArgsExpected)
  288. return false;
  289. }
  290. return true;
  291. }
  292. unsigned int
  293. CTransaction::GetLegacySigOpCount() const
  294. {
  295. unsigned int nSigOps = 0;
  296. BOOST_FOREACH(const CTxIn& txin, vin)
  297. {
  298. nSigOps += txin.scriptSig.GetSigOpCount(false);
  299. }
  300. BOOST_FOREACH(const CTxOut& txout, vout)
  301. {
  302. nSigOps += txout.scriptPubKey.GetSigOpCount(false);
  303. }
  304. return nSigOps;
  305. }
  306. int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
  307. {
  308. if (fClient)
  309. {
  310. if (hashBlock == 0)
  311. return 0;
  312. }
  313. else
  314. {
  315. CBlock blockTmp;
  316. if (pblock == NULL)
  317. {
  318. // Load the block this tx is in
  319. CTxIndex txindex;
  320. if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
  321. return 0;
  322. if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
  323. return 0;
  324. pblock = &blockTmp;
  325. }
  326. // Update the tx's hashBlock
  327. hashBlock = pblock->GetHash();
  328. // Locate the transaction
  329. for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
  330. if (pblock->vtx[nIndex] == *(CTransaction*)this)
  331. break;
  332. if (nIndex == (int)pblock->vtx.size())
  333. {
  334. vMerkleBranch.clear();
  335. nIndex = -1;
  336. printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
  337. return 0;
  338. }
  339. // Fill in merkle branch
  340. vMerkleBranch = pblock->GetMerkleBranch(nIndex);
  341. }
  342. // Is the tx in a block that's in the main chain
  343. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  344. if (mi == mapBlockIndex.end())
  345. return 0;
  346. CBlockIndex* pindex = (*mi).second;
  347. if (!pindex || !pindex->IsInMainChain())
  348. return 0;
  349. return pindexBest->nHeight - pindex->nHeight + 1;
  350. }
  351. bool CTransaction::CheckTransaction() const
  352. {
  353. // Basic checks that don't depend on any context
  354. if (vin.empty())
  355. return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
  356. if (vout.empty())
  357. return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
  358. // Size limits
  359. if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
  360. return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
  361. // Check for negative or overflow output values
  362. int64 nValueOut = 0;
  363. BOOST_FOREACH(const CTxOut& txout, vout)
  364. {
  365. if (txout.nValue < 0)
  366. return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
  367. if (txout.nValue > MAX_MONEY)
  368. return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
  369. nValueOut += txout.nValue;
  370. if (!MoneyRange(nValueOut))
  371. return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
  372. }
  373. // Check for duplicate inputs
  374. set<COutPoint> vInOutPoints;
  375. BOOST_FOREACH(const CTxIn& txin, vin)
  376. {
  377. if (vInOutPoints.count(txin.prevout))
  378. return false;
  379. vInOutPoints.insert(txin.prevout);
  380. }
  381. if (IsCoinBase())
  382. {
  383. if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
  384. return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
  385. }
  386. else
  387. {
  388. BOOST_FOREACH(const CTxIn& txin, vin)
  389. if (txin.prevout.IsNull())
  390. return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
  391. }
  392. return true;
  393. }
  394. bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
  395. bool* pfMissingInputs)
  396. {
  397. if (pfMissingInputs)
  398. *pfMissingInputs = false;
  399. if (!tx.CheckTransaction())
  400. return error("CTxMemPool::accept() : CheckTransaction failed");
  401. // Coinbase is only valid in a block, not as a loose transaction
  402. if (tx.IsCoinBase())
  403. return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
  404. // To help v0.1.5 clients who would see it as a negative number
  405. if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
  406. return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
  407. // Rather not work on nonstandard transactions (unless -testnet)
  408. if (!fTestNet && !tx.IsStandard())
  409. return error("CTxMemPool::accept() : nonstandard transaction type");
  410. // Do we already have it?
  411. uint256 hash = tx.GetHash();
  412. {
  413. LOCK(cs);
  414. if (mapTx.count(hash))
  415. return false;
  416. }
  417. if (fCheckInputs)
  418. if (txdb.ContainsTx(hash))
  419. return false;
  420. // Check for conflicts with in-memory transactions
  421. CTransaction* ptxOld = NULL;
  422. for (unsigned int i = 0; i < tx.vin.size(); i++)
  423. {
  424. COutPoint outpoint = tx.vin[i].prevout;
  425. if (mapNextTx.count(outpoint))
  426. {
  427. // Disable replacement feature for now
  428. return false;
  429. // Allow replacing with a newer version of the same transaction
  430. if (i != 0)
  431. return false;
  432. ptxOld = mapNextTx[outpoint].ptx;
  433. if (ptxOld->IsFinal())
  434. return false;
  435. if (!tx.IsNewerThan(*ptxOld))
  436. return false;
  437. for (unsigned int i = 0; i < tx.vin.size(); i++)
  438. {
  439. COutPoint outpoint = tx.vin[i].prevout;
  440. if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
  441. return false;
  442. }
  443. break;
  444. }
  445. }
  446. if (fCheckInputs)
  447. {
  448. MapPrevTx mapInputs;
  449. map<uint256, CTxIndex> mapUnused;
  450. bool fInvalid = false;
  451. if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
  452. {
  453. if (fInvalid)
  454. return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
  455. if (pfMissingInputs)
  456. *pfMissingInputs = true;
  457. return false;
  458. }
  459. // Check for non-standard pay-to-script-hash in inputs
  460. if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
  461. return error("CTxMemPool::accept() : nonstandard transaction input");
  462. // Note: if you modify this code to accept non-standard transactions, then
  463. // you should add code here to check that the transaction does a
  464. // reasonable number of ECDSA signature verifications.
  465. int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
  466. unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  467. // Don't accept it if it can't get into a block
  468. int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
  469. if (nFees < txMinFee)
  470. return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
  471. hash.ToString().c_str(),
  472. nFees, txMinFee);
  473. // Continuously rate-limit free transactions
  474. // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
  475. // be annoying or make other's transactions take longer to confirm.
  476. if (nFees < MIN_RELAY_TX_FEE)
  477. {
  478. static CCriticalSection cs;
  479. static double dFreeCount;
  480. static int64 nLastTime;
  481. int64 nNow = GetTime();
  482. {
  483. LOCK(cs);
  484. // Use an exponentially decaying ~10-minute window:
  485. dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
  486. nLastTime = nNow;
  487. // -limitfreerelay unit is thousand-bytes-per-minute
  488. // At default rate it would take over a month to fill 1GB
  489. if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
  490. return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
  491. if (fDebug)
  492. printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
  493. dFreeCount += nSize;
  494. }
  495. }
  496. // Check against previous transactions
  497. // This is done last to help prevent CPU exhaustion denial-of-service attacks.
  498. if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
  499. {
  500. return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
  501. }
  502. }
  503. // Store transaction in memory
  504. {
  505. LOCK(cs);
  506. if (ptxOld)
  507. {
  508. printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
  509. remove(*ptxOld);
  510. }
  511. addUnchecked(hash, tx);
  512. }
  513. ///// are we sure this is ok when loading transactions or restoring block txes
  514. // If updated, erase old tx from wallet
  515. if (ptxOld)
  516. EraseFromWallets(ptxOld->GetHash());
  517. printf("CTxMemPool::accept() : accepted %s (poolsz %u)\n",
  518. hash.ToString().c_str(),
  519. mapTx.size());
  520. return true;
  521. }
  522. bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
  523. {
  524. return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
  525. }
  526. bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
  527. {
  528. // Add to memory pool without checking anything. Don't call this directly,
  529. // call CTxMemPool::accept to properly check the transaction first.
  530. {
  531. mapTx[hash] = tx;
  532. for (unsigned int i = 0; i < tx.vin.size(); i++)
  533. mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
  534. nTransactionsUpdated++;
  535. }
  536. return true;
  537. }
  538. bool CTxMemPool::remove(CTransaction &tx)
  539. {
  540. // Remove transaction from memory pool
  541. {
  542. LOCK(cs);
  543. uint256 hash = tx.GetHash();
  544. if (mapTx.count(hash))
  545. {
  546. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  547. mapNextTx.erase(txin.prevout);
  548. mapTx.erase(hash);
  549. nTransactionsUpdated++;
  550. }
  551. }
  552. return true;
  553. }
  554. void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
  555. {
  556. vtxid.clear();
  557. LOCK(cs);
  558. vtxid.reserve(mapTx.size());
  559. for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
  560. vtxid.push_back((*mi).first);
  561. }
  562. int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
  563. {
  564. if (hashBlock == 0 || nIndex == -1)
  565. return 0;
  566. // Find the block it claims to be in
  567. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  568. if (mi == mapBlockIndex.end())
  569. return 0;
  570. CBlockIndex* pindex = (*mi).second;
  571. if (!pindex || !pindex->IsInMainChain())
  572. return 0;
  573. // Make sure the merkle branch connects to this block
  574. if (!fMerkleVerified)
  575. {
  576. if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
  577. return 0;
  578. fMerkleVerified = true;
  579. }
  580. pindexRet = pindex;
  581. return pindexBest->nHeight - pindex->nHeight + 1;
  582. }
  583. int CMerkleTx::GetBlocksToMaturity() const
  584. {
  585. if (!IsCoinBase())
  586. return 0;
  587. return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
  588. }
  589. bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
  590. {
  591. if (fClient)
  592. {
  593. if (!IsInMainChain() && !ClientConnectInputs())
  594. return false;
  595. return CTransaction::AcceptToMemoryPool(txdb, false);
  596. }
  597. else
  598. {
  599. return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
  600. }
  601. }
  602. bool CMerkleTx::AcceptToMemoryPool()
  603. {
  604. CTxDB txdb("r");
  605. return AcceptToMemoryPool(txdb);
  606. }
  607. bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
  608. {
  609. {
  610. LOCK(mempool.cs);
  611. // Add previous supporting transactions first
  612. BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
  613. {
  614. if (!tx.IsCoinBase())
  615. {
  616. uint256 hash = tx.GetHash();
  617. if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
  618. tx.AcceptToMemoryPool(txdb, fCheckInputs);
  619. }
  620. }
  621. return AcceptToMemoryPool(txdb, fCheckInputs);
  622. }
  623. return false;
  624. }
  625. bool CWalletTx::AcceptWalletTransaction()
  626. {
  627. CTxDB txdb("r");
  628. return AcceptWalletTransaction(txdb);
  629. }
  630. int CTxIndex::GetDepthInMainChain() const
  631. {
  632. // Read block header
  633. CBlock block;
  634. if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
  635. return 0;
  636. // Find the block in the index
  637. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
  638. if (mi == mapBlockIndex.end())
  639. return 0;
  640. CBlockIndex* pindex = (*mi).second;
  641. if (!pindex || !pindex->IsInMainChain())
  642. return 0;
  643. return 1 + nBestHeight - pindex->nHeight;
  644. }
  645. // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
  646. bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
  647. {
  648. {
  649. LOCK(cs_main);
  650. {
  651. LOCK(mempool.cs);
  652. if (mempool.exists(hash))
  653. {
  654. tx = mempool.lookup(hash);
  655. return true;
  656. }
  657. }
  658. CTxDB txdb("r");
  659. CTxIndex txindex;
  660. if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
  661. {
  662. CBlock block;
  663. if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
  664. hashBlock = block.GetHash();
  665. return true;
  666. }
  667. }
  668. return false;
  669. }
  670. //////////////////////////////////////////////////////////////////////////////
  671. //
  672. // CBlock and CBlockIndex
  673. //
  674. bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
  675. {
  676. if (!fReadTransactions)
  677. {
  678. *this = pindex->GetBlockHeader();
  679. return true;
  680. }
  681. if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
  682. return false;
  683. if (GetHash() != pindex->GetBlockHash())
  684. return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
  685. return true;
  686. }
  687. uint256 static GetOrphanRoot(const CBlock* pblock)
  688. {
  689. // Work back to the first block in the orphan chain
  690. while (mapOrphanBlocks.count(pblock->hashPrevBlock))
  691. pblock = mapOrphanBlocks[pblock->hashPrevBlock];
  692. return pblock->GetHash();
  693. }
  694. int64 static GetBlockValue(int nHeight, int64 nFees)
  695. {
  696. int64 nSubsidy = 50 * COIN;
  697. // Subsidy is cut in half every 840000 blocks, which will occur approximately every 4 years
  698. nSubsidy >>= (nHeight / 840000); // Litecoin: 840k blocks in ~4 years
  699. return nSubsidy + nFees;
  700. }
  701. static const int64 nTargetTimespan = 3.5 * 24 * 60 * 60; // Litecoin: 3.5 days
  702. static const int64 nTargetSpacing = 2.5 * 60; // Litecoin: 2.5 minutes
  703. static const int64 nInterval = nTargetTimespan / nTargetSpacing;
  704. //
  705. // minimum amount of work that could possibly be required nTime after
  706. // minimum work required was nBase
  707. //
  708. unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
  709. {
  710. // Testnet has min-difficulty blocks
  711. // after nTargetSpacing*2 time between blocks:
  712. if (fTestNet && nTime > nTargetSpacing*2)
  713. return bnProofOfWorkLimit.GetCompact();
  714. CBigNum bnResult;
  715. bnResult.SetCompact(nBase);
  716. while (nTime > 0 && bnResult < bnProofOfWorkLimit)
  717. {
  718. // Maximum 400% adjustment...
  719. bnResult *= 4;
  720. // ... in best-case exactly 4-times-normal target time
  721. nTime -= nTargetTimespan*4;
  722. }
  723. if (bnResult > bnProofOfWorkLimit)
  724. bnResult = bnProofOfWorkLimit;
  725. return bnResult.GetCompact();
  726. }
  727. unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
  728. {
  729. unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
  730. // Genesis block
  731. if (pindexLast == NULL)
  732. return nProofOfWorkLimit;
  733. // Only change once per interval
  734. if ((pindexLast->nHeight+1) % nInterval != 0)
  735. {
  736. // Special difficulty rule for testnet:
  737. if (fTestNet)
  738. {
  739. // If the new block's timestamp is more than 2* 10 minutes
  740. // then allow mining of a min-difficulty block.
  741. if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
  742. return nProofOfWorkLimit;
  743. else
  744. {
  745. // Return the last non-special-min-difficulty-rules-block
  746. const CBlockIndex* pindex = pindexLast;
  747. while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
  748. pindex = pindex->pprev;
  749. return pindex->nBits;
  750. }
  751. }
  752. return pindexLast->nBits;
  753. }
  754. // Litecoin: This fixes an issue where a 51% attack can change difficulty at will.
  755. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
  756. int blockstogoback = nInterval-1;
  757. if ((pindexLast->nHeight+1) != nInterval)
  758. blockstogoback = nInterval;
  759. // Go back by what we want to be 14 days worth of blocks
  760. const CBlockIndex* pindexFirst = pindexLast;
  761. for (int i = 0; pindexFirst && i < blockstogoback; i++)
  762. pindexFirst = pindexFirst->pprev;
  763. assert(pindexFirst);
  764. // Limit adjustment step
  765. int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
  766. printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
  767. if (nActualTimespan < nTargetTimespan/4)
  768. nActualTimespan = nTargetTimespan/4;
  769. if (nActualTimespan > nTargetTimespan*4)
  770. nActualTimespan = nTargetTimespan*4;
  771. // Retarget
  772. CBigNum bnNew;
  773. bnNew.SetCompact(pindexLast->nBits);
  774. bnNew *= nActualTimespan;
  775. bnNew /= nTargetTimespan;
  776. if (bnNew > bnProofOfWorkLimit)
  777. bnNew = bnProofOfWorkLimit;
  778. /// debug print
  779. printf("GetNextWorkRequired RETARGET\n");
  780. printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
  781. printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
  782. printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
  783. return bnNew.GetCompact();
  784. }
  785. bool CheckProofOfWork(uint256 hash, unsigned int nBits)
  786. {
  787. CBigNum bnTarget;
  788. bnTarget.SetCompact(nBits);
  789. // Check range
  790. if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
  791. return error("CheckProofOfWork() : nBits below minimum work");
  792. // Check proof of work matches claimed amount
  793. if (hash > bnTarget.getuint256())
  794. return error("CheckProofOfWork() : hash doesn't match nBits");
  795. return true;
  796. }
  797. // Return maximum amount of blocks that other nodes claim to have
  798. int GetNumBlocksOfPeers()
  799. {
  800. return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
  801. }
  802. bool IsInitialBlockDownload()
  803. {
  804. if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
  805. return true;
  806. static int64 nLastUpdate;
  807. static CBlockIndex* pindexLastBest;
  808. if (pindexBest != pindexLastBest)
  809. {
  810. pindexLastBest = pindexBest;
  811. nLastUpdate = GetTime();
  812. }
  813. return (GetTime() - nLastUpdate < 10 &&
  814. pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
  815. }
  816. void static InvalidChainFound(CBlockIndex* pindexNew)
  817. {
  818. if (pindexNew->bnChainWork > bnBestInvalidWork)
  819. {
  820. bnBestInvalidWork = pindexNew->bnChainWork;
  821. CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
  822. uiInterface.NotifyBlocksChanged();
  823. }
  824. printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n",
  825. pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
  826. pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S",
  827. pindexNew->GetBlockTime()).c_str());
  828. printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n",
  829. hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
  830. DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
  831. if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
  832. printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
  833. }
  834. void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
  835. {
  836. nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
  837. // Updating time can change work required on testnet:
  838. if (fTestNet)
  839. nBits = GetNextWorkRequired(pindexPrev, this);
  840. }
  841. bool CTransaction::DisconnectInputs(CTxDB& txdb)
  842. {
  843. // Relinquish previous transactions' spent pointers
  844. if (!IsCoinBase())
  845. {
  846. BOOST_FOREACH(const CTxIn& txin, vin)
  847. {
  848. COutPoint prevout = txin.prevout;
  849. // Get prev txindex from disk
  850. CTxIndex txindex;
  851. if (!txdb.ReadTxIndex(prevout.hash, txindex))
  852. return error("DisconnectInputs() : ReadTxIndex failed");
  853. if (prevout.n >= txindex.vSpent.size())
  854. return error("DisconnectInputs() : prevout.n out of range");
  855. // Mark outpoint as not spent
  856. txindex.vSpent[prevout.n].SetNull();
  857. // Write back
  858. if (!txdb.UpdateTxIndex(prevout.hash, txindex))
  859. return error("DisconnectInputs() : UpdateTxIndex failed");
  860. }
  861. }
  862. // Remove transaction from index
  863. // This can fail if a duplicate of this transaction was in a chain that got
  864. // reorganized away. This is only possible if this transaction was completely
  865. // spent, so erasing it would be a no-op anway.
  866. txdb.EraseTxIndex(*this);
  867. return true;
  868. }
  869. bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
  870. bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
  871. {
  872. // FetchInputs can return false either because we just haven't seen some inputs
  873. // (in which case the transaction should be stored as an orphan)
  874. // or because the transaction is malformed (in which case the transaction should
  875. // be dropped). If tx is definitely invalid, fInvalid will be set to true.
  876. fInvalid = false;
  877. if (IsCoinBase())
  878. return true; // Coinbase transactions have no inputs to fetch.
  879. for (unsigned int i = 0; i < vin.size(); i++)
  880. {
  881. COutPoint prevout = vin[i].prevout;
  882. if (inputsRet.count(prevout.hash))
  883. continue; // Got it already
  884. // Read txindex
  885. CTxIndex& txindex = inputsRet[prevout.hash].first;
  886. bool fFound = true;
  887. if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
  888. {
  889. // Get txindex from current proposed changes
  890. txindex = mapTestPool.find(prevout.hash)->second;
  891. }
  892. else
  893. {
  894. // Read txindex from txdb
  895. fFound = txdb.ReadTxIndex(prevout.hash, txindex);
  896. }
  897. if (!fFound && (fBlock || fMiner))
  898. return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
  899. // Read txPrev
  900. CTransaction& txPrev = inputsRet[prevout.hash].second;
  901. if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
  902. {
  903. // Get prev tx from single transactions in memory
  904. {
  905. LOCK(mempool.cs);
  906. if (!mempool.exists(prevout.hash))
  907. return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
  908. txPrev = mempool.lookup(prevout.hash);
  909. }
  910. if (!fFound)
  911. txindex.vSpent.resize(txPrev.vout.size());
  912. }
  913. else
  914. {
  915. // Get prev tx from disk
  916. if (!txPrev.ReadFromDisk(txindex.pos))
  917. return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
  918. }
  919. }
  920. // Make sure all prevout.n's are valid:
  921. for (unsigned int i = 0; i < vin.size(); i++)
  922. {
  923. const COutPoint prevout = vin[i].prevout;
  924. assert(inputsRet.count(prevout.hash) != 0);
  925. const CTxIndex& txindex = inputsRet[prevout.hash].first;
  926. const CTransaction& txPrev = inputsRet[prevout.hash].second;
  927. if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
  928. {
  929. // Revisit this if/when transaction replacement is implemented and allows
  930. // adding inputs:
  931. fInvalid = true;
  932. return DoS(100, error("FetchInputs() : %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()));
  933. }
  934. }
  935. return true;
  936. }
  937. const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
  938. {
  939. MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
  940. if (mi == inputs.end())
  941. throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
  942. const CTransaction& txPrev = (mi->second).second;
  943. if (input.prevout.n >= txPrev.vout.size())
  944. throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
  945. return txPrev.vout[input.prevout.n];
  946. }
  947. int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
  948. {
  949. if (IsCoinBase())
  950. return 0;
  951. int64 nResult = 0;
  952. for (unsigned int i = 0; i < vin.size(); i++)
  953. {
  954. nResult += GetOutputFor(vin[i], inputs).nValue;
  955. }
  956. return nResult;
  957. }
  958. unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
  959. {
  960. if (IsCoinBase())
  961. return 0;
  962. unsigned int nSigOps = 0;
  963. for (unsigned int i = 0; i < vin.size(); i++)
  964. {
  965. const CTxOut& prevout = GetOutputFor(vin[i], inputs);
  966. if (prevout.scriptPubKey.IsPayToScriptHash())
  967. nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
  968. }
  969. return nSigOps;
  970. }
  971. bool CTransaction::ConnectInputs(MapPrevTx inputs,
  972. map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
  973. const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
  974. {
  975. // Take over previous transactions' spent pointers
  976. // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
  977. // fMiner is true when called from the internal litecoin miner
  978. // ... both are false when called from CTransaction::AcceptToMemoryPool
  979. if (!IsCoinBase())
  980. {
  981. int64 nValueIn = 0;
  982. int64 nFees = 0;
  983. for (unsigned int i = 0; i < vin.size(); i++)
  984. {
  985. COutPoint prevout = vin[i].prevout;
  986. assert(inputs.count(prevout.hash) > 0);
  987. CTxIndex& txindex = inputs[prevout.hash].first;
  988. CTransaction& txPrev = inputs[prevout.hash].second;
  989. if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
  990. return DoS(100, 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()));
  991. // If prev is coinbase, check that it's matured
  992. if (txPrev.IsCoinBase())
  993. for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
  994. if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
  995. return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
  996. // Check for negative or overflow input values
  997. nValueIn += txPrev.vout[prevout.n].nValue;
  998. if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
  999. return DoS(100, error("ConnectInputs() : txin values out of range"));
  1000. }
  1001. // The first loop above does all the inexpensive checks.
  1002. // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
  1003. // Helps prevent CPU exhaustion attacks.
  1004. for (unsigned int i = 0; i < vin.size(); i++)
  1005. {
  1006. COutPoint prevout = vin[i].prevout;
  1007. assert(inputs.count(prevout.hash) > 0);
  1008. CTxIndex& txindex = inputs[prevout.hash].first;
  1009. CTransaction& txPrev = inputs[prevout.hash].second;
  1010. // Check for conflicts (double-spend)
  1011. // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
  1012. // for an attacker to attempt to split the network.
  1013. if (!txindex.vSpent[prevout.n].IsNull())
  1014. 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());
  1015. // Skip ECDSA signature verification when connecting blocks (fBlock=true)
  1016. // before the last blockchain checkpoint. This is safe because block merkle hashes are
  1017. // still computed and checked, and any change will be caught at the next checkpoint.
  1018. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
  1019. {
  1020. // Verify signature
  1021. if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
  1022. {
  1023. // only during transition phase for P2SH: do not invoke anti-DoS code for
  1024. // potentially old clients relaying bad P2SH transactions
  1025. if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
  1026. return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
  1027. return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
  1028. }
  1029. }
  1030. // Mark outpoints as spent
  1031. txindex.vSpent[prevout.n] = posThisTx;
  1032. // Write back
  1033. if (fBlock || fMiner)
  1034. {
  1035. mapTestPool[prevout.hash] = txindex;
  1036. }
  1037. }
  1038. if (nValueIn < GetValueOut())
  1039. return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
  1040. // Tally transaction fees
  1041. int64 nTxFee = nValueIn - GetValueOut();
  1042. if (nTxFee < 0)
  1043. return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
  1044. nFees += nTxFee;
  1045. if (!MoneyRange(nFees))
  1046. return DoS(100, error("ConnectInputs() : nFees out of range"));
  1047. }
  1048. return true;
  1049. }
  1050. bool CTransaction::ClientConnectInputs()
  1051. {
  1052. if (IsCoinBase())
  1053. return false;
  1054. // Take over previous transactions' spent pointers
  1055. {
  1056. LOCK(mempool.cs);
  1057. int64 nValueIn = 0;
  1058. for (unsigned int i = 0; i < vin.size(); i++)
  1059. {
  1060. // Get prev tx from single transactions in memory
  1061. COutPoint prevout = vin[i].prevout;
  1062. if (!mempool.exists(prevout.hash))
  1063. return false;
  1064. CTransaction& txPrev = mempool.lookup(prevout.hash);
  1065. if (prevout.n >= txPrev.vout.size())
  1066. return false;
  1067. // Verify signature
  1068. if (!VerifySignature(txPrev, *this, i, true, 0))
  1069. return error("ConnectInputs() : VerifySignature failed");
  1070. ///// this is redundant with the mempool.mapNextTx stuff,
  1071. ///// not sure which I want to get rid of
  1072. ///// this has to go away now that posNext is gone
  1073. // // Check for conflicts
  1074. // if (!txPrev.vout[prevout.n].posNext.IsNull())
  1075. // return error("ConnectInputs() : prev tx already used");
  1076. //
  1077. // // Flag outpoints as used
  1078. // txPrev.vout[prevout.n].posNext = posThisTx;
  1079. nValueIn += txPrev.vout[prevout.n].nValue;
  1080. if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
  1081. return error("ClientConnectInputs() : txin values out of range");
  1082. }
  1083. if (GetValueOut() > nValueIn)
  1084. return false;
  1085. }
  1086. return true;
  1087. }
  1088. bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
  1089. {
  1090. // Disconnect in reverse order
  1091. for (int i = vtx.size()-1; i >= 0; i--)
  1092. if (!vtx[i].DisconnectInputs(txdb))
  1093. return false;
  1094. // Update block index on disk without changing it in memory.
  1095. // The memory index structure will be changed after the db commits.
  1096. if (pindex->pprev)
  1097. {
  1098. CDiskBlockIndex blockindexPrev(pindex->pprev);
  1099. blockindexPrev.hashNext = 0;
  1100. if (!txdb.WriteBlockIndex(blockindexPrev))
  1101. return error("DisconnectBlock() : WriteBlockIndex failed");
  1102. }
  1103. return true;
  1104. }
  1105. bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
  1106. {
  1107. // Check it again in case a previous version let a bad block in
  1108. if (!CheckBlock())
  1109. return false;
  1110. // Do not allow blocks that contain transactions which 'overwrite' older transactions,
  1111. // unless those are already completely spent.
  1112. // If such overwrites are allowed, coinbases and transactions depending upon those
  1113. // can be duplicated to remove the ability to spend the first instance -- even after
  1114. // being sent to another address.
  1115. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
  1116. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
  1117. // already refuses previously-known transaction id's entirely.
  1118. // This rule applies to all blocks whose timestamp is after October 1, 2012, 0:00 UTC.
  1119. int64 nBIP30SwitchTime = 1349049600;
  1120. bool fEnforceBIP30 = (pindex->nTime > nBIP30SwitchTime);
  1121. // BIP16 didn't become active until October 1 2012
  1122. int64 nBIP16SwitchTime = 1349049600;
  1123. bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
  1124. //// issue here: it doesn't know the version
  1125. unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size());
  1126. map<uint256, CTxIndex> mapQueuedChanges;
  1127. int64 nFees = 0;
  1128. unsigned int nSigOps = 0;
  1129. BOOST_FOREACH(CTransaction& tx, vtx)
  1130. {
  1131. uint256 hashTx = tx.GetHash();
  1132. if (fEnforceBIP30) {
  1133. CTxIndex txindexOld;
  1134. if (txdb.ReadTxIndex(hashTx, txindexOld)) {
  1135. BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
  1136. if (pos.IsNull())
  1137. return false;
  1138. }
  1139. }
  1140. nSigOps += tx.GetLegacySigOpCount();
  1141. if (nSigOps > MAX_BLOCK_SIGOPS)
  1142. return DoS(100, error("ConnectBlock() : too many sigops"));
  1143. CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
  1144. nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
  1145. MapPrevTx mapInputs;
  1146. if (!tx.IsCoinBase())
  1147. {
  1148. bool fInvalid;
  1149. if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
  1150. return false;
  1151. if (fStrictPayToScriptHash)
  1152. {
  1153. // Add in sigops done by pay-to-script-hash inputs;
  1154. // this is to prevent a "rogue miner" from creating
  1155. // an incredibly-expensive-to-validate block.
  1156. nSigOps += tx.GetP2SHSigOpCount(mapInputs);
  1157. if (nSigOps > MAX_BLOCK_SIGOPS)
  1158. return DoS(100, error("ConnectBlock() : too many sigops"));
  1159. }
  1160. nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
  1161. if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
  1162. return false;
  1163. }
  1164. mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
  1165. }
  1166. // Write queued txindex changes
  1167. for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
  1168. {
  1169. if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
  1170. return error("ConnectBlock() : UpdateTxIndex failed");
  1171. }
  1172. if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
  1173. return false;
  1174. // Update block index on disk without changing it in memory.
  1175. // The memory index structure will be changed after the db commits.
  1176. if (pindex->pprev)
  1177. {
  1178. CDiskBlockIndex blockindexPrev(pindex->pprev);
  1179. blockindexPrev.hashNext = pindex->GetBlockHash();
  1180. if (!txdb.WriteBlockIndex(blockindexPrev))
  1181. return error("ConnectBlock() : WriteBlockIndex failed");
  1182. }
  1183. // Watch for transactions paying to me
  1184. BOOST_FOREACH(CTransaction& tx, vtx)
  1185. SyncWithWallets(tx, this, true);
  1186. return true;
  1187. }
  1188. bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
  1189. {
  1190. printf("REORGANIZE\n");
  1191. // Find the fork
  1192. CBlockIndex* pfork = pindexBest;
  1193. CBlockIndex* plonger = pindexNew;
  1194. while (pfork != plonger)
  1195. {
  1196. while (plonger->nHeight > pfork->nHeight)
  1197. if (!(plonger = plonger->pprev))
  1198. return error("Reorganize() : plonger->pprev is null");
  1199. if (pfork == plonger)
  1200. break;
  1201. if (!(pfork = pfork->pprev))
  1202. return error("Reorganize() : pfork->pprev is null");
  1203. }
  1204. // List of what to disconnect
  1205. vector<CBlockIndex*> vDisconnect;
  1206. for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
  1207. vDisconnect.push_back(pindex);
  1208. // List of what to connect
  1209. vector<CBlockIndex*> vConnect;
  1210. for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
  1211. vConnect.push_back(pindex);
  1212. reverse(vConnect.begin(), vConnect.end());
  1213. printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
  1214. printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
  1215. // Disconnect shorter branch
  1216. vector<CTransaction> vResurrect;
  1217. BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
  1218. {
  1219. CBlock block;
  1220. if (!block.ReadFromDisk(pindex))
  1221. return error("Reorganize() : ReadFromDisk for disconnect failed");
  1222. if (!block.DisconnectBlock(txdb, pindex))
  1223. return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
  1224. // Queue memory transactions to resurrect
  1225. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  1226. if (!tx.IsCoinBase())
  1227. vResurrect.push_back(tx);
  1228. }
  1229. // Connect longer branch
  1230. vector<CTransaction> vDelete;
  1231. for (unsigned int i = 0; i < vConnect.size(); i++)
  1232. {
  1233. CBlockIndex* pindex = vConnect[i];
  1234. CBlock block;
  1235. if (!block.ReadFromDisk(pindex))
  1236. return error("Reorganize() : ReadFromDisk for connect failed");
  1237. if (!block.ConnectBlock(txdb, pindex))
  1238. {
  1239. // Invalid block
  1240. return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
  1241. }
  1242. // Queue memory transactions to delete
  1243. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  1244. vDelete.push_back(tx);
  1245. }
  1246. if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
  1247. return error("Reorganize() : WriteHashBestChain failed");
  1248. // Make sure it's successfully written to disk before changing memory structure
  1249. if (!txdb.TxnCommit())
  1250. return error("Reorganize() : TxnCommit failed");
  1251. // Disconnect shorter branch
  1252. BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
  1253. if (pindex->pprev)
  1254. pindex->pprev->pnext = NULL;
  1255. // Connect longer branch
  1256. BOOST_FOREACH(CBlockIndex* pindex, vConnect)
  1257. if (pindex->pprev)
  1258. pindex->pprev->pnext = pindex;
  1259. // Resurrect memory transactions that were in the disconnected branch
  1260. BOOST_FOREACH(CTransaction& tx, vResurrect)
  1261. tx.AcceptToMemoryPool(txdb, false);
  1262. // Delete redundant memory transactions that are in the connected branch
  1263. BOOST_FOREACH(CTransaction& tx, vDelete)
  1264. mempool.remove(tx);
  1265. printf("REORGANIZE: done\n");
  1266. return true;
  1267. }
  1268. // Called from inside SetBestChain: attaches a block to the new best chain being built
  1269. bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
  1270. {
  1271. uint256 hash = GetHash();
  1272. // Adding to current best branch
  1273. if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
  1274. {
  1275. txdb.TxnAbort();
  1276. InvalidChainFound(pindexNew);
  1277. return false;
  1278. }
  1279. if (!txdb.TxnCommit())
  1280. return error("SetBestChain() : TxnCommit failed");
  1281. // Add to current best branch
  1282. pindexNew->pprev->pnext = pindexNew;
  1283. // Delete redundant memory transactions
  1284. BOOST_FOREACH(CTransaction& tx, vtx)
  1285. mempool.remove(tx);
  1286. return true;
  1287. }
  1288. bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
  1289. {
  1290. uint256 hash = GetHash();
  1291. if (!txdb.TxnBegin())
  1292. return error("SetBestChain() : TxnBegin failed");
  1293. if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
  1294. {
  1295. txdb.WriteHashBestChain(hash);
  1296. if (!txdb.TxnCommit())
  1297. return error("SetBestChain() : TxnCommit failed");
  1298. pindexGenesisBlock = pindexNew;
  1299. }
  1300. else if (hashPrevBlock == hashBestChain)
  1301. {
  1302. if (!SetBestChainInner(txdb, pindexNew))
  1303. return error("SetBestChain() : SetBestChainInner failed");
  1304. }
  1305. else
  1306. {
  1307. // the first block in the new chain that will cause it to become the new best chain
  1308. CBlockIndex *pindexIntermediate = pindexNew;
  1309. // list of blocks that need to be connected afterwards
  1310. std::vector<CBlockIndex*> vpindexSecondary;
  1311. // Reorganize is costly in terms of db load, as it works in a single db transaction.
  1312. // Try to limit how much needs to be done inside
  1313. while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork)
  1314. {
  1315. vpindexSecondary.push_back(pindexIntermediate);
  1316. pindexIntermediate = pindexIntermediate->pprev;
  1317. }
  1318. if (!vpindexSecondary.empty())
  1319. printf("Postponing %i reconnects\n", vpindexSecondary.size());
  1320. // Switch to new best branch
  1321. if (!Reorganize(txdb, pindexIntermediate))
  1322. {
  1323. txdb.TxnAbort();
  1324. InvalidChainFound(pindexNew);
  1325. return error("SetBestChain() : Reorganize failed");
  1326. }
  1327. // Connect futher blocks
  1328. BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
  1329. {
  1330. CBlock block;
  1331. if (!block.ReadFromDisk(pindex))
  1332. {
  1333. printf("SetBestChain() : ReadFromDisk failed\n");
  1334. break;
  1335. }
  1336. if (!txdb.TxnBegin()) {
  1337. printf("SetBestChain() : TxnBegin 2 failed\n");
  1338. break;
  1339. }
  1340. // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
  1341. if (!block.SetBestChainInner(txdb, pindex))
  1342. break;
  1343. }
  1344. }
  1345. // Update best block in wallet (so we can detect restored wallets)
  1346. bool fIsInitialDownload = IsInitialBlockDownload();
  1347. if (!fIsInitialDownload)
  1348. {
  1349. const CBlockLocator locator(pindexNew);
  1350. ::SetBestChain(locator);
  1351. }
  1352. // New best block
  1353. hashBestChain = hash;
  1354. pindexBest = pindexNew;
  1355. nBestHeight = pindexBest->nHeight;
  1356. bnBestChainWork = pindexNew->bnChainWork;
  1357. nTimeBestReceived = GetTime();
  1358. nTransactionsUpdated++;
  1359. printf("SetBestChain: new best=%s height=%d work=%s date=%s\n",
  1360. hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
  1361. DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
  1362. // Check the version of the last 100 blocks to see if we need to upgrade:
  1363. if (!fIsInitialDownload)
  1364. {
  1365. int nUpgraded = 0;
  1366. const CBlockIndex* pindex = pindexBest;
  1367. for (int i = 0; i < 100 && pindex != NULL; i++)
  1368. {
  1369. if (pindex->nVersion > CBlock::CURRENT_VERSION)
  1370. ++nUpgraded;
  1371. pindex = pindex->pprev;
  1372. }
  1373. if (nUpgraded > 0)
  1374. printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
  1375. // if (nUpgraded > 100/2)
  1376. // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
  1377. // strMiscWarning = _("Warning: this version is obsolete, upgrade required");
  1378. }
  1379. std::string strCmd = GetArg("-blocknotify", "");
  1380. if (!fIsInitialDownload && !strCmd.empty())
  1381. {
  1382. boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
  1383. boost::thread t(runCommand, strCmd); // thread runs free
  1384. }
  1385. return true;
  1386. }
  1387. bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
  1388. {
  1389. // Check for duplicate
  1390. uint256 hash = GetHash();
  1391. if (mapBlockIndex.count(hash))
  1392. return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
  1393. // Construct new block index object
  1394. CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
  1395. if (!pindexNew)
  1396. return error("AddToBlockIndex() : new CBlockIndex failed");
  1397. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  1398. pindexNew->phashBlock = &((*mi).first);
  1399. map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
  1400. if (miPrev != mapBlockIndex.end())
  1401. {
  1402. pindexNew->pprev = (*miPrev).second;
  1403. pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
  1404. }
  1405. pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
  1406. CTxDB txdb;
  1407. if (!txdb.TxnBegin())
  1408. return false;
  1409. txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
  1410. if (!txdb.TxnCommit())
  1411. return false;
  1412. // New best
  1413. if (pindexNew->bnChainWork > bnBestChainWork)
  1414. if (!SetBestChain(txdb, pindexNew))
  1415. return false;
  1416. txdb.Close();
  1417. if (pindexNew == pindexBest)
  1418. {
  1419. // Notify UI to display prev block's coinbase if it was ours
  1420. static uint256 hashPrevBestCoinBase;
  1421. UpdatedTransaction(hashPrevBestCoinBase);
  1422. hashPrevBestCoinBase = vtx[0].GetHash();
  1423. }
  1424. uiInterface.NotifyBlocksChanged();
  1425. return true;
  1426. }
  1427. bool CBlock::CheckBlock() const
  1428. {
  1429. // These are checks that are independent of context
  1430. // that can be verified before saving an orphan block.
  1431. // Size limits
  1432. if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
  1433. return DoS(100, error("CheckBlock() : size limits failed"));
  1434. // Special short-term limits to avoid 10,000 BDB lock limit:
  1435. if (GetBlockTime() < 1376568000) // stop enforcing 15 August 2013 noon GMT
  1436. {
  1437. // Rule is: #unique txids referenced <= 4,500
  1438. // ... to prevent 10,000 BDB lock exhaustion on old clients
  1439. set<uint256> setTxIn;
  1440. for (size_t i = 0; i < vtx.size(); i++)
  1441. {
  1442. setTxIn.insert(vtx[i].GetHash());
  1443. if (i == 0) continue; // skip coinbase txin
  1444. BOOST_FOREACH(const CTxIn& txin, vtx[i].vin)
  1445. setTxIn.insert(txin.prevout.hash);
  1446. }
  1447. size_t nTxids = setTxIn.size();
  1448. if (nTxids > 4500)
  1449. return error("CheckBlock() : 15 Aug maxlocks violation");
  1450. }
  1451. // Check proof of work matches claimed amount
  1452. if (!CheckProofOfWork(GetPoWHash(), nBits))
  1453. return DoS(50, error("CheckBlock() : proof of work failed"));
  1454. // Check timestamp
  1455. if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
  1456. return error("CheckBlock() : block timestamp too far in the future");
  1457. // First transaction must be coinbase, the rest must not be
  1458. if (vtx.empty() || !vtx[0].IsCoinBase())
  1459. return DoS(100, error("CheckBlock() : first tx is not coinbase"));
  1460. for (unsigned int i = 1; i < vtx.size(); i++)
  1461. if (vtx[i].IsCoinBase())
  1462. return DoS(100, error("CheckBlock() : more than one coinbase"));
  1463. // Check transactions
  1464. BOOST_FOREACH(const CTransaction& tx, vtx)
  1465. if (!tx.CheckTransaction())
  1466. return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
  1467. // Check for duplicate txids. This is caught by ConnectInputs(),
  1468. // but catching it earlier avoids a potential DoS attack:
  1469. set<uint256> uniqueTx;
  1470. BOOST_FOREACH(const CTransaction& tx, vtx)
  1471. {
  1472. uniqueTx.insert(tx.GetHash());
  1473. }
  1474. if (uniqueTx.size() != vtx.size())
  1475. return DoS(100, error("CheckBlock() : duplicate transaction"));
  1476. unsigned int nSigOps = 0;
  1477. BOOST_FOREACH(const CTransaction& tx, vtx)
  1478. {
  1479. nSigOps += tx.GetLegacySigOpCount();
  1480. }
  1481. if (nSigOps > MAX_BLOCK_SIGOPS)
  1482. return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
  1483. // Check merkleroot
  1484. if (hashMerkleRoot != BuildMerkleTree())
  1485. return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
  1486. return true;
  1487. }
  1488. bool CBlock::AcceptBlock()
  1489. {
  1490. // Check for duplicate
  1491. uint256 hash = GetHash();
  1492. if (mapBlockIndex.count(hash))
  1493. return error("AcceptBlock() : block already in mapBlockIndex");
  1494. // Get prev block index
  1495. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
  1496. if (mi == mapBlockIndex.end())
  1497. return DoS(10, error("AcceptBlock() : prev block not found"));
  1498. CBlockIndex* pindexPrev = (*mi).second;
  1499. int nHeight = pindexPrev->nHeight+1;
  1500. // Check proof of work
  1501. if (nBits != GetNextWorkRequired(pindexPrev, this))
  1502. return DoS(100, error("AcceptBlock() : incorrect proof of work"));
  1503. // Check timestamp against prev
  1504. if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
  1505. return error("AcceptBlock() : block's timestamp is too early");
  1506. // Check that all transactions are finalized
  1507. BOOST_FOREACH(const CTransaction& tx, vtx)
  1508. if (!tx.IsFinal(nHeight, GetBlockTime()))
  1509. return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
  1510. // Check that the block chain matches the known block chain up to a checkpoint
  1511. if (!Checkpoints::CheckBlock(nHeight, hash))
  1512. return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
  1513. // Write block to history file
  1514. if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
  1515. return error("AcceptBlock() : out of disk space");
  1516. unsigned int nFile = -1;
  1517. unsigned int nBlockPos = 0;
  1518. if (!WriteToDisk(nFile, nBlockPos))
  1519. return error("AcceptBlock() : WriteToDisk failed");
  1520. if (!AddToBlockIndex(nFile, nBlockPos))
  1521. return error("AcceptBlock() : AddToBlockIndex failed");
  1522. // Relay inventory, but don't relay old inventory during initial block download
  1523. int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
  1524. if (hashBestChain == hash)
  1525. {
  1526. LOCK(cs_vNodes);
  1527. BOOST_FOREACH(CNode* pnode, vNodes)
  1528. if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
  1529. pnode->PushInventory(CInv(MSG_BLOCK, hash));
  1530. }
  1531. return true;
  1532. }
  1533. bool ProcessBlock(CNode* pfrom, CBlock* pblock)
  1534. {
  1535. // Check for duplicate
  1536. uint256 hash = pblock->GetHash();
  1537. if (mapBlockIndex.count(hash))
  1538. return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
  1539. if (mapOrphanBlocks.count(hash))
  1540. return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
  1541. // Preliminary checks
  1542. if (!pblock->CheckBlock())
  1543. return error("ProcessBlock() : CheckBlock FAILED");
  1544. CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
  1545. if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
  1546. {
  1547. // Extra checks to prevent "fill up memory by spamming with bogus blocks"
  1548. int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
  1549. if (deltaTime < 0)
  1550. {
  1551. if (pfrom)
  1552. pfrom->Misbehaving(100);
  1553. return error("ProcessBlock() : block with timestamp before last checkpoint");
  1554. }
  1555. CBigNum bnNewBlock;
  1556. bnNewBlock.SetCompact(pblock->nBits);
  1557. CBigNum bnRequired;
  1558. bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
  1559. if (bnNewBlock > bnRequired)
  1560. {
  1561. if (pfrom)
  1562. pfrom->Misbehaving(100);
  1563. return error("ProcessBlock() : block with too little proof-of-work");
  1564. }
  1565. }
  1566. // If don't already have its previous block, shunt it off to holding area until we get it
  1567. if (!mapBlockIndex.count(pblock->hashPrevBlock))
  1568. {
  1569. printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
  1570. CBlock* pblock2 = new CBlock(*pblock);
  1571. mapOrphanBlocks.insert(make_pair(hash, pblock2));
  1572. mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
  1573. // Ask this guy to fill in what we're missing
  1574. if (pfrom)
  1575. pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
  1576. return true;
  1577. }
  1578. // Store to disk
  1579. if (!pblock->AcceptBlock())
  1580. return error("ProcessBlock() : AcceptBlock FAILED");
  1581. // Recursively process any orphan blocks that depended on this one
  1582. vector<uint256> vWorkQueue;
  1583. vWorkQueue.push_back(hash);
  1584. for (unsigned int i = 0; i < vWorkQueue.size(); i++)
  1585. {
  1586. uint256 hashPrev = vWorkQueue[i];
  1587. for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
  1588. mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
  1589. ++mi)
  1590. {
  1591. CBlock* pblockOrphan = (*mi).second;
  1592. if (pblockOrphan->AcceptBlock())
  1593. vWorkQueue.push_back(pblockOrphan->GetHash());
  1594. mapOrphanBlocks.erase(pblockOrphan->GetHash());
  1595. delete pblockOrphan;
  1596. }
  1597. mapOrphanBlocksByPrev.erase(hashPrev);
  1598. }
  1599. printf("ProcessBlock: ACCEPTED\n");
  1600. return true;
  1601. }
  1602. bool CheckDiskSpace(uint64 nAdditionalBytes)
  1603. {
  1604. uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
  1605. // Check for nMinDiskSpace bytes (currently 50MB)
  1606. if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
  1607. {
  1608. fShutdown = true;
  1609. string strMessage = _("Warning: Disk space is low");
  1610. strMiscWarning = strMessage;
  1611. printf("*** %s\n", strMessage.c_str());
  1612. uiInterface.ThreadSafeMessageBox(strMessage, "Litecoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
  1613. StartShutdown();
  1614. return false;
  1615. }
  1616. return true;
  1617. }
  1618. FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
  1619. {
  1620. if ((nFile < 1) || (nFile == (unsigned int) -1))
  1621. return NULL;
  1622. FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
  1623. if (!file)
  1624. return NULL;
  1625. if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
  1626. {
  1627. if (fseek(file, nBlockPos, SEEK_SET) != 0)
  1628. {
  1629. fclose(file);
  1630. return NULL;
  1631. }
  1632. }
  1633. return file;
  1634. }
  1635. static unsigned int nCurrentBlockFile = 1;
  1636. FILE* AppendBlockFile(unsigned int& nFileRet)
  1637. {
  1638. nFileRet = 0;
  1639. loop
  1640. {
  1641. FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
  1642. if (!file)
  1643. return NULL;
  1644. if (fseek(file, 0, SEEK_END) != 0)
  1645. return NULL;
  1646. // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
  1647. if (ftell(file) < 0x7F000000 - MAX_SIZE)
  1648. {
  1649. nFileRet = nCurrentBlockFile;
  1650. return file;
  1651. }
  1652. fclose(file);
  1653. nCurrentBlockFile++;
  1654. }
  1655. }
  1656. bool LoadBlockIndex(bool fAllowNew)
  1657. {
  1658. if (fTestNet)
  1659. {
  1660. pchMessageStart[0] = 0xfc;
  1661. pchMessageStart[1] = 0xc1;
  1662. pchMessageStart[2] = 0xb7;
  1663. pchMessageStart[3] = 0xdc;
  1664. hashGenesisBlock = uint256("0xf5ae71e26c74beacc88382716aced69cddf3dffff24f384e1808905e0188f68f");
  1665. }
  1666. //
  1667. // Load block index
  1668. //
  1669. CTxDB txdb("cr");
  1670. if (!txdb.LoadBlockIndex())
  1671. return false;
  1672. txdb.Close();
  1673. //
  1674. // Init with genesis block
  1675. //
  1676. if (mapBlockIndex.empty())
  1677. {
  1678. if (!fAllowNew)
  1679. return false;
  1680. // Genesis Block:
  1681. // CBlock(hash=12a765e31ffd4059bada, PoW=0000050c34a64b415b6b, ver=1, hashPrevBlock=00000000000000000000, hashMerkleRoot=97ddfbbae6, nTime=1317972665, nBits=1e0ffff0, nNonce=2084524493, vtx=1)
  1682. // CTransaction(hash=97ddfbbae6, ver=1, vin.size=1, vout.size=1, nLockTime=0)
  1683. // CTxIn(COutPoint(0000000000, -1), coinbase 04ffff001d0104404e592054696d65732030352f4f63742f32303131205374657665204a6f62732c204170706c65e280997320566973696f6e6172792c2044696573206174203536)
  1684. // CTxOut(nValue=50.00000000, scriptPubKey=040184710fa689ad5023690c80f3a4)
  1685. // vMerkleTree: 97ddfbbae6
  1686. // Genesis block
  1687. const char* pszTimestamp = "NY Times 05/Oct/2011 Steve Jobs, Apple’s Visionary, Dies at 56";
  1688. CTransaction txNew;
  1689. txNew.vin.resize(1);
  1690. txNew.vout.resize(1);
  1691. txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
  1692. txNew.vout[0].nValue = 50 * COIN;
  1693. txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
  1694. CBlock block;
  1695. block.vtx.push_back(txNew);
  1696. block.hashPrevBlock = 0;
  1697. block.hashMerkleRoot = block.BuildMerkleTree();
  1698. block.nVersion = 1;
  1699. block.nTime = 1317972665;
  1700. block.nBits = 0x1e0ffff0;
  1701. block.nNonce = 2084524493;
  1702. if (fTestNet)
  1703. {
  1704. block.nTime = 1317798646;
  1705. block.nNonce = 385270584;
  1706. }
  1707. //// debug print
  1708. printf("%s\n", block.GetHash().ToString().c_str());
  1709. printf("%s\n", hashGenesisBlock.ToString().c_str());
  1710. printf("%s\n", block.hashMerkleRoot.ToString().c_str());
  1711. assert(block.hashMerkleRoot == uint256("0x97ddfbbae6be97fd6cdf3e7ca13232a3afff2353e29badfab7f73011edd4ced9"));
  1712. // If genesis block hash does not match, then generate new genesis hash.
  1713. if (false && block.GetHash() != hashGenesisBlock)
  1714. {
  1715. printf("Searching for genesis block...\n");
  1716. // This will figure out a valid hash and Nonce if you're
  1717. // creating a different genesis block:
  1718. uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256();
  1719. uint256 thash;
  1720. char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
  1721. loop
  1722. {
  1723. scrypt_1024_1_1_256_sp(BEGIN(block.nVersion), BEGIN(thash), scratchpad);
  1724. if (thash <= hashTarget)
  1725. break;
  1726. if ((block.nNonce & 0xFFF) == 0)
  1727. {
  1728. printf("nonce %08X: hash = %s (target = %s)\n", block.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
  1729. }
  1730. ++block.nNonce;
  1731. if (block.nNonce == 0)
  1732. {
  1733. printf("NONCE WRAPPED, incrementing time\n");
  1734. ++block.nTime;
  1735. }
  1736. }
  1737. printf("block.nTime = %u \n", block.nTime);
  1738. printf("block.nNonce = %u \n", block.nNonce);
  1739. printf("block.GetHash = %s\n", block.GetHash().ToString().c_str());
  1740. }
  1741. block.print();
  1742. assert(block.GetHash() == hashGenesisBlock);
  1743. // Start new block file
  1744. unsigned int nFile;
  1745. unsigned int nBlockPos;
  1746. if (!block.WriteToDisk(nFile, nBlockPos))
  1747. return error("LoadBlockIndex() : writing genesis block to disk failed");
  1748. if (!block.AddToBlockIndex(nFile, nBlockPos))
  1749. return error("LoadBlockIndex() : genesis block not accepted");
  1750. }
  1751. return true;
  1752. }
  1753. void PrintBlockTree()
  1754. {
  1755. // precompute tree structure
  1756. map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
  1757. for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
  1758. {
  1759. CBlockIndex* pindex = (*mi).second;
  1760. mapNext[pindex->pprev].push_back(pindex);
  1761. // test
  1762. //while (rand() % 3 == 0)
  1763. // mapNext[pindex->pprev].push_back(pindex);
  1764. }
  1765. vector<pair<int, CBlockIndex*> > vStack;
  1766. vStack.push_back(make_pair(0, pindexGenesisBlock));
  1767. int nPrevCol = 0;
  1768. while (!vStack.empty())
  1769. {
  1770. int nCol = vStack.back().first;
  1771. CBlockIndex* pindex = vStack.back().second;
  1772. vStack.pop_back();
  1773. // print split or gap
  1774. if (nCol > nPrevCol)
  1775. {
  1776. for (int i = 0; i < nCol-1; i++)
  1777. printf("| ");
  1778. printf("|\\\n");
  1779. }
  1780. else if (nCol < nPrevCol)
  1781. {
  1782. for (int i = 0; i < nCol; i++)
  1783. printf("| ");
  1784. printf("|\n");
  1785. }
  1786. nPrevCol = nCol;
  1787. // print columns
  1788. for (int i = 0; i < nCol; i++)
  1789. printf("| ");
  1790. // print item
  1791. CBlock block;
  1792. block.ReadFromDisk(pindex);
  1793. printf("%d (%u,%u) %s %s tx %d",
  1794. pindex->nHeight,
  1795. pindex->nFile,
  1796. pindex->nBlockPos,
  1797. block.GetHash().ToString().substr(0,20).c_str(),
  1798. DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
  1799. block.vtx.size());
  1800. PrintWallets(block);
  1801. // put the main timechain first
  1802. vector<CBlockIndex*>& vNext = mapNext[pindex];
  1803. for (unsigned int i = 0; i < vNext.size(); i++)
  1804. {
  1805. if (vNext[i]->pnext)
  1806. {
  1807. swap(vNext[0], vNext[i]);
  1808. break;
  1809. }
  1810. }
  1811. // iterate children
  1812. for (unsigned int i = 0; i < vNext.size(); i++)
  1813. vStack.push_back(make_pair(nCol+i, vNext[i]));
  1814. }
  1815. }
  1816. bool LoadExternalBlockFile(FILE* fileIn)
  1817. {
  1818. int nLoaded = 0;
  1819. {
  1820. LOCK(cs_main);
  1821. try {
  1822. CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
  1823. unsigned int nPos = 0;
  1824. while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
  1825. {
  1826. unsigned char pchData[65536];
  1827. do {
  1828. fseek(blkdat, nPos, SEEK_SET);
  1829. int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
  1830. if (nRead <= 8)
  1831. {
  1832. nPos = (unsigned int)-1;
  1833. break;
  1834. }
  1835. void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
  1836. if (nFind)
  1837. {
  1838. if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
  1839. {
  1840. nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
  1841. break;
  1842. }
  1843. nPos += ((unsigned char*)nFind - pchData) + 1;
  1844. }
  1845. else
  1846. nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
  1847. } while(!fRequestShutdown);
  1848. if (nPos == (unsigned int)-1)
  1849. break;
  1850. fseek(blkdat, nPos, SEEK_SET);
  1851. unsigned int nSize;
  1852. blkdat >> nSize;
  1853. if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
  1854. {
  1855. CBlock block;
  1856. blkdat >> block;
  1857. if (ProcessBlock(NULL,&block))
  1858. {
  1859. nLoaded++;
  1860. nPos += 4 + nSize;
  1861. }
  1862. }
  1863. }
  1864. }
  1865. catch (std::exception &e) {
  1866. printf("%s() : Deserialize or I/O error caught during load\n",
  1867. __PRETTY_FUNCTION__);
  1868. }
  1869. }
  1870. printf("Loaded %i blocks from external file\n", nLoaded);
  1871. return nLoaded > 0;
  1872. }
  1873. //////////////////////////////////////////////////////////////////////////////
  1874. //
  1875. // CAlert
  1876. //
  1877. map<uint256, CAlert> mapAlerts;
  1878. CCriticalSection cs_mapAlerts;
  1879. string GetWarnings(string strFor)
  1880. {
  1881. int nPriority = 0;
  1882. string strStatusBar;
  1883. string strRPC;
  1884. if (GetBoolArg("-testsafemode"))
  1885. strRPC = "test";
  1886. // Misc warnings like out of disk space and clock is wrong
  1887. if (strMiscWarning != "")
  1888. {
  1889. nPriority = 1000;
  1890. strStatusBar = strMiscWarning;
  1891. }
  1892. // Longer invalid proof-of-work chain
  1893. if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
  1894. {
  1895. nPriority = 2000;
  1896. strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
  1897. }
  1898. // Alerts
  1899. {
  1900. LOCK(cs_mapAlerts);
  1901. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  1902. {
  1903. const CAlert& alert = item.second;
  1904. if (alert.AppliesToMe() && alert.nPriority > nPriority)
  1905. {
  1906. nPriority = alert.nPriority;
  1907. strStatusBar = alert.strStatusBar;
  1908. }
  1909. }
  1910. }
  1911. if (strFor == "statusbar")
  1912. return strStatusBar;
  1913. else if (strFor == "rpc")
  1914. return strRPC;
  1915. assert(!"GetWarnings() : invalid parameter");
  1916. return "error";
  1917. }
  1918. CAlert CAlert::getAlertByHash(const uint256 &hash)
  1919. {
  1920. CAlert retval;
  1921. {
  1922. LOCK(cs_mapAlerts);
  1923. map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);
  1924. if(mi != mapAlerts.end())
  1925. retval = mi->second;
  1926. }
  1927. return retval;
  1928. }
  1929. bool CAlert::ProcessAlert()
  1930. {
  1931. if (!CheckSignature())
  1932. return false;
  1933. if (!IsInEffect())
  1934. return false;
  1935. {
  1936. LOCK(cs_mapAlerts);
  1937. // Cancel previous alerts
  1938. for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
  1939. {
  1940. const CAlert& alert = (*mi).second;
  1941. if (Cancels(alert))
  1942. {
  1943. printf("cancelling alert %d\n", alert.nID);
  1944. uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
  1945. mapAlerts.erase(mi++);
  1946. }
  1947. else if (!alert.IsInEffect())
  1948. {
  1949. printf("expiring alert %d\n", alert.nID);
  1950. uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
  1951. mapAlerts.erase(mi++);
  1952. }
  1953. else
  1954. mi++;
  1955. }
  1956. // Check if this alert has been cancelled
  1957. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  1958. {
  1959. const CAlert& alert = item.second;
  1960. if (alert.Cancels(*this))
  1961. {
  1962. printf("alert already cancelled by %d\n", alert.nID);
  1963. return false;
  1964. }
  1965. }
  1966. // Add to mapAlerts
  1967. mapAlerts.insert(make_pair(GetHash(), *this));
  1968. // Notify UI if it applies to me
  1969. if(AppliesToMe())
  1970. uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
  1971. }
  1972. printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
  1973. return true;
  1974. }
  1975. //////////////////////////////////////////////////////////////////////////////
  1976. //
  1977. // Messages
  1978. //
  1979. bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
  1980. {
  1981. switch (inv.type)
  1982. {
  1983. case MSG_TX:
  1984. {
  1985. bool txInMap = false;
  1986. {
  1987. LOCK(mempool.cs);
  1988. txInMap = (mempool.exists(inv.hash));
  1989. }
  1990. return txInMap ||
  1991. mapOrphanTransactions.count(inv.hash) ||
  1992. txdb.ContainsTx(inv.hash);
  1993. }
  1994. case MSG_BLOCK:
  1995. return mapBlockIndex.count(inv.hash) ||
  1996. mapOrphanBlocks.count(inv.hash);
  1997. }
  1998. // Don't know what it is, just say we already got one
  1999. return true;
  2000. }
  2001. // The message start string is designed to be unlikely to occur in normal data.
  2002. // The characters are rarely used upper ascii, not valid as UTF-8, and produce
  2003. // a large 4-byte int at any alignment.
  2004. unsigned char pchMessageStart[4] = { 0xfb, 0xc0, 0xb6, 0xdb }; // Litecoin: increase each by adding 2 to bitcoin's value.
  2005. bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
  2006. {
  2007. static map<CService, CPubKey> mapReuseKey;
  2008. RandAddSeedPerfmon();
  2009. if (fDebug)
  2010. printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
  2011. if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
  2012. {
  2013. printf("dropmessagestest DROPPING RECV MESSAGE\n");
  2014. return true;
  2015. }
  2016. if (strCommand == "version")
  2017. {
  2018. // Each connection can only send one version message
  2019. if (pfrom->nVersion != 0)
  2020. {
  2021. pfrom->Misbehaving(1);
  2022. return false;
  2023. }
  2024. int64 nTime;
  2025. CAddress addrMe;
  2026. CAddress addrFrom;
  2027. uint64 nNonce = 1;
  2028. vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
  2029. if (pfrom->nVersion < MIN_PROTO_VERSION)
  2030. {
  2031. // Since February 20, 2012, the protocol is initiated at version 209,
  2032. // and earlier versions are no longer supported
  2033. printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
  2034. pfrom->fDisconnect = true;
  2035. return false;
  2036. }
  2037. if (pfrom->nVersion == 10300)
  2038. pfrom->nVersion = 300;
  2039. if (!vRecv.empty())
  2040. vRecv >> addrFrom >> nNonce;
  2041. if (!vRecv.empty())
  2042. vRecv >> pfrom->strSubVer;
  2043. if (!vRecv.empty())
  2044. vRecv >> pfrom->nStartingHeight;
  2045. if (pfrom->fInbound && addrMe.IsRoutable())
  2046. {
  2047. pfrom->addrLocal = addrMe;
  2048. SeenLocal(addrMe);
  2049. }
  2050. // Disconnect if we connected to ourself
  2051. if (nNonce == nLocalHostNonce && nNonce > 1)
  2052. {
  2053. printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
  2054. pfrom->fDisconnect = true;
  2055. return true;
  2056. }
  2057. // Be shy and don't send version until we hear
  2058. if (pfrom->fInbound)
  2059. pfrom->PushVersion();
  2060. pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
  2061. AddTimeData(pfrom->addr, nTime);
  2062. // Change version
  2063. pfrom->PushMessage("verack");
  2064. pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
  2065. if (!pfrom->fInbound)
  2066. {
  2067. // Advertise our address
  2068. if (!fNoListen && !IsInitialBlockDownload())
  2069. {
  2070. CAddress addr = GetLocalAddress(&pfrom->addr);
  2071. if (addr.IsRoutable())
  2072. pfrom->PushAddress(addr);
  2073. }
  2074. // Get recent addresses
  2075. if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
  2076. {
  2077. pfrom->PushMessage("getaddr");
  2078. pfrom->fGetAddr = true;
  2079. }
  2080. addrman.Good(pfrom->addr);
  2081. } else {
  2082. if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
  2083. {
  2084. addrman.Add(addrFrom, addrFrom);
  2085. addrman.Good(addrFrom);
  2086. }
  2087. }
  2088. // Ask the first connected node for block updates
  2089. static int nAskedForBlocks = 0;
  2090. if (!pfrom->fClient && !pfrom->fOneShot &&
  2091. (pfrom->nVersion < NOBLKS_VERSION_START ||
  2092. pfrom->nVersion >= NOBLKS_VERSION_END) &&
  2093. (nAskedForBlocks < 1 || vNodes.size() <= 1))
  2094. {
  2095. nAskedForBlocks++;
  2096. pfrom->PushGetBlocks(pindexBest, uint256(0));
  2097. }
  2098. // Relay alerts
  2099. {
  2100. LOCK(cs_mapAlerts);
  2101. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  2102. item.second.RelayTo(pfrom);
  2103. }
  2104. pfrom->fSuccessfullyConnected = true;
  2105. printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
  2106. cPeerBlockCounts.input(pfrom->nStartingHeight);
  2107. }
  2108. else if (pfrom->nVersion == 0)
  2109. {
  2110. // Must have a version message before anything else
  2111. pfrom->Misbehaving(1);
  2112. return false;
  2113. }
  2114. else if (strCommand == "verack")
  2115. {
  2116. pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
  2117. }
  2118. else if (strCommand == "addr")
  2119. {
  2120. vector<CAddress> vAddr;
  2121. vRecv >> vAddr;
  2122. // Don't want addr from older versions unless seeding
  2123. if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
  2124. return true;
  2125. if (vAddr.size() > 1000)
  2126. {
  2127. pfrom->Misbehaving(20);
  2128. return error("message addr size() = %d", vAddr.size());
  2129. }
  2130. // Store the new addresses
  2131. vector<CAddress> vAddrOk;
  2132. int64 nNow = GetAdjustedTime();
  2133. int64 nSince = nNow - 10 * 60;
  2134. BOOST_FOREACH(CAddress& addr, vAddr)
  2135. {
  2136. if (fShutdown)
  2137. return true;
  2138. if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
  2139. addr.nTime = nNow - 5 * 24 * 60 * 60;
  2140. pfrom->AddAddressKnown(addr);
  2141. bool fReachable = IsReachable(addr);
  2142. if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
  2143. {
  2144. // Relay to a limited number of other nodes
  2145. {
  2146. LOCK(cs_vNodes);
  2147. // Use deterministic randomness to send to the same nodes for 24 hours
  2148. // at a time so the setAddrKnowns of the chosen nodes prevent repeats
  2149. static uint256 hashSalt;
  2150. if (hashSalt == 0)
  2151. hashSalt = GetRandHash();
  2152. uint64 hashAddr = addr.GetHash();
  2153. uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
  2154. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  2155. multimap<uint256, CNode*> mapMix;
  2156. BOOST_FOREACH(CNode* pnode, vNodes)
  2157. {
  2158. if (pnode->nVersion < CADDR_TIME_VERSION)
  2159. continue;
  2160. unsigned int nPointer;
  2161. memcpy(&nPointer, &pnode, sizeof(nPointer));
  2162. uint256 hashKey = hashRand ^ nPointer;
  2163. hashKey = Hash(BEGIN(hashKey), END(hashKey));
  2164. mapMix.insert(make_pair(hashKey, pnode));
  2165. }
  2166. int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
  2167. for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
  2168. ((*mi).second)->PushAddress(addr);
  2169. }
  2170. }
  2171. // Do not store addresses outside our network
  2172. if (fReachable)
  2173. vAddrOk.push_back(addr);
  2174. }
  2175. addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
  2176. if (vAddr.size() < 1000)
  2177. pfrom->fGetAddr = false;
  2178. if (pfrom->fOneShot)
  2179. pfrom->fDisconnect = true;
  2180. }
  2181. else if (strCommand == "inv")
  2182. {
  2183. vector<CInv> vInv;
  2184. vRecv >> vInv;
  2185. if (vInv.size() > 50000)
  2186. {
  2187. pfrom->Misbehaving(20);
  2188. return error("message inv size() = %d", vInv.size());
  2189. }
  2190. // find last block in inv vector
  2191. unsigned int nLastBlock = (unsigned int)(-1);
  2192. for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
  2193. if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
  2194. nLastBlock = vInv.size() - 1 - nInv;
  2195. break;
  2196. }
  2197. }
  2198. CTxDB txdb("r");
  2199. for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
  2200. {
  2201. const CInv &inv = vInv[nInv];
  2202. if (fShutdown)
  2203. return true;
  2204. pfrom->AddInventoryKnown(inv);
  2205. bool fAlreadyHave = AlreadyHave(txdb, inv);
  2206. if (fDebug)
  2207. printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
  2208. if (!fAlreadyHave)
  2209. pfrom->AskFor(inv);
  2210. else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
  2211. pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
  2212. } else if (nInv == nLastBlock) {
  2213. // In case we are on a very long side-chain, it is possible that we already have
  2214. // the last block in an inv bundle sent in response to getblocks. Try to detect
  2215. // this situation and push another getblocks to continue.
  2216. std::vector<CInv> vGetData(1,inv);
  2217. pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
  2218. if (fDebug)
  2219. printf("force request: %s\n", inv.ToString().c_str());
  2220. }
  2221. // Track requests for our stuff
  2222. Inventory(inv.hash);
  2223. }
  2224. }
  2225. else if (strCommand == "getdata")
  2226. {
  2227. vector<CInv> vInv;
  2228. vRecv >> vInv;
  2229. if (vInv.size() > 50000)
  2230. {
  2231. pfrom->Misbehaving(20);
  2232. return error("message getdata size() = %d", vInv.size());
  2233. }
  2234. if (fDebugNet || (vInv.size() != 1))
  2235. printf("received getdata (%d invsz)\n", vInv.size());
  2236. BOOST_FOREACH(const CInv& inv, vInv)
  2237. {
  2238. if (fShutdown)
  2239. return true;
  2240. if (fDebugNet || (vInv.size() == 1))
  2241. printf("received getdata for: %s\n", inv.ToString().c_str());
  2242. if (inv.type == MSG_BLOCK)
  2243. {
  2244. // Send block from disk
  2245. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
  2246. if (mi != mapBlockIndex.end())
  2247. {
  2248. CBlock block;
  2249. block.ReadFromDisk((*mi).second);
  2250. pfrom->PushMessage("block", block);
  2251. // Trigger them to send a getblocks request for the next batch of inventory
  2252. if (inv.hash == pfrom->hashContinue)
  2253. {
  2254. // Bypass PushInventory, this must send even if redundant,
  2255. // and we want it right after the last block so they don't
  2256. // wait for other stuff first.
  2257. vector<CInv> vInv;
  2258. vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
  2259. pfrom->PushMessage("inv", vInv);
  2260. pfrom->hashContinue = 0;
  2261. }
  2262. }
  2263. }
  2264. else if (inv.IsKnownType())
  2265. {
  2266. // Send stream from relay memory
  2267. {
  2268. LOCK(cs_mapRelay);
  2269. map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
  2270. if (mi != mapRelay.end())
  2271. pfrom->PushMessage(inv.GetCommand(), (*mi).second);
  2272. }
  2273. }
  2274. // Track requests for our stuff
  2275. Inventory(inv.hash);
  2276. }
  2277. }
  2278. else if (strCommand == "getblocks")
  2279. {
  2280. CBlockLocator locator;
  2281. uint256 hashStop;
  2282. vRecv >> locator >> hashStop;
  2283. // Find the last block the caller has in the main chain
  2284. CBlockIndex* pindex = locator.GetBlockIndex();
  2285. // Send the rest of the chain
  2286. if (pindex)
  2287. pindex = pindex->pnext;
  2288. int nLimit = 500;
  2289. printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
  2290. for (; pindex; pindex = pindex->pnext)
  2291. {
  2292. if (pindex->GetBlockHash() == hashStop)
  2293. {
  2294. printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
  2295. break;
  2296. }
  2297. pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
  2298. if (--nLimit <= 0)
  2299. {
  2300. // When this block is requested, we'll send an inv that'll make them
  2301. // getblocks the next batch of inventory.
  2302. printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
  2303. pfrom->hashContinue = pindex->GetBlockHash();
  2304. break;
  2305. }
  2306. }
  2307. }
  2308. else if (strCommand == "getheaders")
  2309. {
  2310. CBlockLocator locator;
  2311. uint256 hashStop;
  2312. vRecv >> locator >> hashStop;
  2313. CBlockIndex* pindex = NULL;
  2314. if (locator.IsNull())
  2315. {
  2316. // If locator is null, return the hashStop block
  2317. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
  2318. if (mi == mapBlockIndex.end())
  2319. return true;
  2320. pindex = (*mi).second;
  2321. }
  2322. else
  2323. {
  2324. // Find the last block the caller has in the main chain
  2325. pindex = locator.GetBlockIndex();
  2326. if (pindex)
  2327. pindex = pindex->pnext;
  2328. }
  2329. vector<CBlock> vHeaders;
  2330. int nLimit = 2000;
  2331. printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
  2332. for (; pindex; pindex = pindex->pnext)
  2333. {
  2334. vHeaders.push_back(pindex->GetBlockHeader());
  2335. if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
  2336. break;
  2337. }
  2338. pfrom->PushMessage("headers", vHeaders);
  2339. }
  2340. else if (strCommand == "tx")
  2341. {
  2342. vector<uint256> vWorkQueue;
  2343. vector<uint256> vEraseQueue;
  2344. CDataStream vMsg(vRecv);
  2345. CTxDB txdb("r");
  2346. CTransaction tx;
  2347. vRecv >> tx;
  2348. CInv inv(MSG_TX, tx.GetHash());
  2349. pfrom->AddInventoryKnown(inv);
  2350. // Truncate messages to the size of the tx in them
  2351. unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  2352. unsigned int oldSize = vMsg.size();
  2353. if (nSize < oldSize) {
  2354. vMsg.resize(nSize);
  2355. printf("truncating oversized TX %s (%u -> %u)\n",
  2356. tx.GetHash().ToString().c_str(),
  2357. oldSize, nSize);
  2358. }
  2359. bool fMissingInputs = false;
  2360. if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
  2361. {
  2362. SyncWithWallets(tx, NULL, true);
  2363. RelayMessage(inv, vMsg);
  2364. mapAlreadyAskedFor.erase(inv);
  2365. vWorkQueue.push_back(inv.hash);
  2366. vEraseQueue.push_back(inv.hash);
  2367. // Recursively process any orphan transactions that depended on this one
  2368. for (unsigned int i = 0; i < vWorkQueue.size(); i++)
  2369. {
  2370. uint256 hashPrev = vWorkQueue[i];
  2371. for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
  2372. mi != mapOrphanTransactionsByPrev[hashPrev].end();
  2373. ++mi)
  2374. {
  2375. const CDataStream& vMsg = *((*mi).second);
  2376. CTransaction tx;
  2377. CDataStream(vMsg) >> tx;
  2378. CInv inv(MSG_TX, tx.GetHash());
  2379. bool fMissingInputs2 = false;
  2380. if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
  2381. {
  2382. printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
  2383. SyncWithWallets(tx, NULL, true);
  2384. RelayMessage(inv, vMsg);
  2385. mapAlreadyAskedFor.erase(inv);
  2386. vWorkQueue.push_back(inv.hash);
  2387. vEraseQueue.push_back(inv.hash);
  2388. }
  2389. else if (!fMissingInputs2)
  2390. {
  2391. // invalid orphan
  2392. vEraseQueue.push_back(inv.hash);
  2393. printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
  2394. }
  2395. }
  2396. }
  2397. BOOST_FOREACH(uint256 hash, vEraseQueue)
  2398. EraseOrphanTx(hash);
  2399. }
  2400. else if (fMissingInputs)
  2401. {
  2402. AddOrphanTx(vMsg);
  2403. // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
  2404. unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
  2405. if (nEvicted > 0)
  2406. printf("mapOrphan overflow, removed %u tx\n", nEvicted);
  2407. }
  2408. if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
  2409. }
  2410. else if (strCommand == "block")
  2411. {
  2412. CBlock block;
  2413. vRecv >> block;
  2414. printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
  2415. // block.print();
  2416. CInv inv(MSG_BLOCK, block.GetHash());
  2417. pfrom->AddInventoryKnown(inv);
  2418. if (ProcessBlock(pfrom, &block))
  2419. mapAlreadyAskedFor.erase(inv);
  2420. if (block.nDoS) pfrom->Misbehaving(block.nDoS);
  2421. }
  2422. else if (strCommand == "getaddr")
  2423. {
  2424. pfrom->vAddrToSend.clear();
  2425. vector<CAddress> vAddr = addrman.GetAddr();
  2426. BOOST_FOREACH(const CAddress &addr, vAddr)
  2427. pfrom->PushAddress(addr);
  2428. }
  2429. else if (strCommand == "checkorder")
  2430. {
  2431. uint256 hashReply;
  2432. vRecv >> hashReply;
  2433. if (!GetBoolArg("-allowreceivebyip"))
  2434. {
  2435. pfrom->PushMessage("reply", hashReply, (int)2, string(""));
  2436. return true;
  2437. }
  2438. CWalletTx order;
  2439. vRecv >> order;
  2440. /// we have a chance to check the order here
  2441. // Keep giving the same key to the same ip until they use it
  2442. if (!mapReuseKey.count(pfrom->addr))
  2443. pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
  2444. // Send back approval of order and pubkey to use
  2445. CScript scriptPubKey;
  2446. scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
  2447. pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
  2448. }
  2449. else if (strCommand == "reply")
  2450. {
  2451. uint256 hashReply;
  2452. vRecv >> hashReply;
  2453. CRequestTracker tracker;
  2454. {
  2455. LOCK(pfrom->cs_mapRequests);
  2456. map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
  2457. if (mi != pfrom->mapRequests.end())
  2458. {
  2459. tracker = (*mi).second;
  2460. pfrom->mapRequests.erase(mi);
  2461. }
  2462. }
  2463. if (!tracker.IsNull())
  2464. tracker.fn(tracker.param1, vRecv);
  2465. }
  2466. else if (strCommand == "ping")
  2467. {
  2468. if (pfrom->nVersion > BIP0031_VERSION)
  2469. {
  2470. uint64 nonce = 0;
  2471. vRecv >> nonce;
  2472. // Echo the message back with the nonce. This allows for two useful features:
  2473. //
  2474. // 1) A remote node can quickly check if the connection is operational
  2475. // 2) Remote nodes can measure the latency of the network thread. If this node
  2476. // is overloaded it won't respond to pings quickly and the remote node can
  2477. // avoid sending us more work, like chain download requests.
  2478. //
  2479. // The nonce stops the remote getting confused between different pings: without
  2480. // it, if the remote node sends a ping once per second and this node takes 5
  2481. // seconds to respond to each, the 5th ping the remote sends would appear to
  2482. // return very quickly.
  2483. pfrom->PushMessage("pong", nonce);
  2484. }
  2485. }
  2486. else if (strCommand == "alert")
  2487. {
  2488. CAlert alert;
  2489. vRecv >> alert;
  2490. if (alert.ProcessAlert())
  2491. {
  2492. // Relay
  2493. pfrom->setKnown.insert(alert.GetHash());
  2494. {
  2495. LOCK(cs_vNodes);
  2496. BOOST_FOREACH(CNode* pnode, vNodes)
  2497. alert.RelayTo(pnode);
  2498. }
  2499. }
  2500. }
  2501. else
  2502. {
  2503. // Ignore unknown commands for extensibility
  2504. }
  2505. // Update the last seen time for this node's address
  2506. if (pfrom->fNetworkNode)
  2507. if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
  2508. AddressCurrentlyConnected(pfrom->addr);
  2509. return true;
  2510. }
  2511. bool ProcessMessages(CNode* pfrom)
  2512. {
  2513. CDataStream& vRecv = pfrom->vRecv;
  2514. if (vRecv.empty())
  2515. return true;
  2516. //if (fDebug)
  2517. // printf("ProcessMessages(%u bytes)\n", vRecv.size());
  2518. //
  2519. // Message format
  2520. // (4) message start
  2521. // (12) command
  2522. // (4) size
  2523. // (4) checksum
  2524. // (x) data
  2525. //
  2526. loop
  2527. {
  2528. // Don't bother if send buffer is too full to respond anyway
  2529. if (pfrom->vSend.size() >= SendBufferSize())
  2530. break;
  2531. // Scan for message start
  2532. CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
  2533. int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
  2534. if (vRecv.end() - pstart < nHeaderSize)
  2535. {
  2536. if ((int)vRecv.size() > nHeaderSize)
  2537. {
  2538. printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
  2539. vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
  2540. }
  2541. break;
  2542. }
  2543. if (pstart - vRecv.begin() > 0)
  2544. printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
  2545. vRecv.erase(vRecv.begin(), pstart);
  2546. // Read header
  2547. vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
  2548. CMessageHeader hdr;
  2549. vRecv >> hdr;
  2550. if (!hdr.IsValid())
  2551. {
  2552. printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
  2553. continue;
  2554. }
  2555. string strCommand = hdr.GetCommand();
  2556. // Message size
  2557. unsigned int nMessageSize = hdr.nMessageSize;
  2558. if (nMessageSize > MAX_SIZE)
  2559. {
  2560. printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
  2561. continue;
  2562. }
  2563. if (nMessageSize > vRecv.size())
  2564. {
  2565. // Rewind and wait for rest of message
  2566. vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
  2567. break;
  2568. }
  2569. // Checksum
  2570. uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
  2571. unsigned int nChecksum = 0;
  2572. memcpy(&nChecksum, &hash, sizeof(nChecksum));
  2573. if (nChecksum != hdr.nChecksum)
  2574. {
  2575. printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
  2576. strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
  2577. continue;
  2578. }
  2579. // Copy message to its own buffer
  2580. CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
  2581. vRecv.ignore(nMessageSize);
  2582. // Process message
  2583. bool fRet = false;
  2584. try
  2585. {
  2586. {
  2587. LOCK(cs_main);
  2588. fRet = ProcessMessage(pfrom, strCommand, vMsg);
  2589. }
  2590. if (fShutdown)
  2591. return true;
  2592. }
  2593. catch (std::ios_base::failure& e)
  2594. {
  2595. if (strstr(e.what(), "end of data"))
  2596. {
  2597. // Allow exceptions from underlength message on vRecv
  2598. printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
  2599. }
  2600. else if (strstr(e.what(), "size too large"))
  2601. {
  2602. // Allow exceptions from overlong size
  2603. printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
  2604. }
  2605. else
  2606. {
  2607. PrintExceptionContinue(&e, "ProcessMessages()");
  2608. }
  2609. }
  2610. catch (std::exception& e) {
  2611. PrintExceptionContinue(&e, "ProcessMessages()");
  2612. } catch (...) {
  2613. PrintExceptionContinue(NULL, "ProcessMessages()");
  2614. }
  2615. if (!fRet)
  2616. printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
  2617. }
  2618. vRecv.Compact();
  2619. return true;
  2620. }
  2621. bool SendMessages(CNode* pto, bool fSendTrickle)
  2622. {
  2623. TRY_LOCK(cs_main, lockMain);
  2624. if (lockMain) {
  2625. // Don't send anything until we get their version message
  2626. if (pto->nVersion == 0)
  2627. return true;
  2628. // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
  2629. // right now.
  2630. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
  2631. uint64 nonce = 0;
  2632. if (pto->nVersion > BIP0031_VERSION)
  2633. pto->PushMessage("ping", nonce);
  2634. else
  2635. pto->PushMessage("ping");
  2636. }
  2637. // Resend wallet transactions that haven't gotten in a block yet
  2638. ResendWalletTransactions();
  2639. // Address refresh broadcast
  2640. static int64 nLastRebroadcast;
  2641. if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
  2642. {
  2643. {
  2644. LOCK(cs_vNodes);
  2645. BOOST_FOREACH(CNode* pnode, vNodes)
  2646. {
  2647. // Periodically clear setAddrKnown to allow refresh broadcasts
  2648. if (nLastRebroadcast)
  2649. pnode->setAddrKnown.clear();
  2650. // Rebroadcast our address
  2651. if (!fNoListen)
  2652. {
  2653. CAddress addr = GetLocalAddress(&pnode->addr);
  2654. if (addr.IsRoutable())
  2655. pnode->PushAddress(addr);
  2656. }
  2657. }
  2658. }
  2659. nLastRebroadcast = GetTime();
  2660. }
  2661. //
  2662. // Message: addr
  2663. //
  2664. if (fSendTrickle)
  2665. {
  2666. vector<CAddress> vAddr;
  2667. vAddr.reserve(pto->vAddrToSend.size());
  2668. BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
  2669. {
  2670. // returns true if wasn't already contained in the set
  2671. if (pto->setAddrKnown.insert(addr).second)
  2672. {
  2673. vAddr.push_back(addr);
  2674. // receiver rejects addr messages larger than 1000
  2675. if (vAddr.size() >= 1000)
  2676. {
  2677. pto->PushMessage("addr", vAddr);
  2678. vAddr.clear();
  2679. }
  2680. }
  2681. }
  2682. pto->vAddrToSend.clear();
  2683. if (!vAddr.empty())
  2684. pto->PushMessage("addr", vAddr);
  2685. }
  2686. //
  2687. // Message: inventory
  2688. //
  2689. vector<CInv> vInv;
  2690. vector<CInv> vInvWait;
  2691. {
  2692. LOCK(pto->cs_inventory);
  2693. vInv.reserve(pto->vInventoryToSend.size());
  2694. vInvWait.reserve(pto->vInventoryToSend.size());
  2695. BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
  2696. {
  2697. if (pto->setInventoryKnown.count(inv))
  2698. continue;
  2699. // trickle out tx inv to protect privacy
  2700. if (inv.type == MSG_TX && !fSendTrickle)
  2701. {
  2702. // 1/4 of tx invs blast to all immediately
  2703. static uint256 hashSalt;
  2704. if (hashSalt == 0)
  2705. hashSalt = GetRandHash();
  2706. uint256 hashRand = inv.hash ^ hashSalt;
  2707. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  2708. bool fTrickleWait = ((hashRand & 3) != 0);
  2709. // always trickle our own transactions
  2710. if (!fTrickleWait)
  2711. {
  2712. CWalletTx wtx;
  2713. if (GetTransaction(inv.hash, wtx))
  2714. if (wtx.fFromMe)
  2715. fTrickleWait = true;
  2716. }
  2717. if (fTrickleWait)
  2718. {
  2719. vInvWait.push_back(inv);
  2720. continue;
  2721. }
  2722. }
  2723. // returns true if wasn't already contained in the set
  2724. if (pto->setInventoryKnown.insert(inv).second)
  2725. {
  2726. vInv.push_back(inv);
  2727. if (vInv.size() >= 1000)
  2728. {
  2729. pto->PushMessage("inv", vInv);
  2730. vInv.clear();
  2731. }
  2732. }
  2733. }
  2734. pto->vInventoryToSend = vInvWait;
  2735. }
  2736. if (!vInv.empty())
  2737. pto->PushMessage("inv", vInv);
  2738. //
  2739. // Message: getdata
  2740. //
  2741. vector<CInv> vGetData;
  2742. int64 nNow = GetTime() * 1000000;
  2743. CTxDB txdb("r");
  2744. while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
  2745. {
  2746. const CInv& inv = (*pto->mapAskFor.begin()).second;
  2747. if (!AlreadyHave(txdb, inv))
  2748. {
  2749. if (fDebugNet)
  2750. printf("sending getdata: %s\n", inv.ToString().c_str());
  2751. vGetData.push_back(inv);
  2752. if (vGetData.size() >= 1000)
  2753. {
  2754. pto->PushMessage("getdata", vGetData);
  2755. vGetData.clear();
  2756. }
  2757. mapAlreadyAskedFor[inv] = nNow;
  2758. }
  2759. pto->mapAskFor.erase(pto->mapAskFor.begin());
  2760. }
  2761. if (!vGetData.empty())
  2762. pto->PushMessage("getdata", vGetData);
  2763. }
  2764. return true;
  2765. }
  2766. //////////////////////////////////////////////////////////////////////////////
  2767. //
  2768. // BitcoinMiner
  2769. //
  2770. int static FormatHashBlocks(void* pbuffer, unsigned int len)
  2771. {
  2772. unsigned char* pdata = (unsigned char*)pbuffer;
  2773. unsigned int blocks = 1 + ((len + 8) / 64);
  2774. unsigned char* pend = pdata + 64 * blocks;
  2775. memset(pdata + len, 0, 64 * blocks - len);
  2776. pdata[len] = 0x80;
  2777. unsigned int bits = len * 8;
  2778. pend[-1] = (bits >> 0) & 0xff;
  2779. pend[-2] = (bits >> 8) & 0xff;
  2780. pend[-3] = (bits >> 16) & 0xff;
  2781. pend[-4] = (bits >> 24) & 0xff;
  2782. return blocks;
  2783. }
  2784. static const unsigned int pSHA256InitState[8] =
  2785. {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
  2786. void SHA256Transform(void* pstate, void* pinput, const void* pinit)
  2787. {
  2788. SHA256_CTX ctx;
  2789. unsigned char data[64];
  2790. SHA256_Init(&ctx);
  2791. for (int i = 0; i < 16; i++)
  2792. ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
  2793. for (int i = 0; i < 8; i++)
  2794. ctx.h[i] = ((uint32_t*)pinit)[i];
  2795. SHA256_Update(&ctx, data, sizeof(data));
  2796. for (int i = 0; i < 8; i++)
  2797. ((uint32_t*)pstate)[i] = ctx.h[i];
  2798. }
  2799. //
  2800. // ScanHash scans nonces looking for a hash with at least some zero bits.
  2801. // It operates on big endian data. Caller does the byte reversing.
  2802. // All input buffers are 16-byte aligned. nNonce is usually preserved
  2803. // between calls, but periodically or if nNonce is 0xffff0000 or above,
  2804. // the block is rebuilt and nNonce starts over at zero.
  2805. //
  2806. unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
  2807. {
  2808. unsigned int& nNonce = *(unsigned int*)(pdata + 12);
  2809. for (;;)
  2810. {
  2811. // Crypto++ SHA-256
  2812. // Hash pdata using pmidstate as the starting state into
  2813. // preformatted buffer phash1, then hash phash1 into phash
  2814. nNonce++;
  2815. SHA256Transform(phash1, pdata, pmidstate);
  2816. SHA256Transform(phash, phash1, pSHA256InitState);
  2817. // Return the nonce if the hash has at least some zero bits,
  2818. // caller will check if it has enough to reach the target
  2819. if (((unsigned short*)phash)[14] == 0)
  2820. return nNonce;
  2821. // If nothing found after trying for a while, return -1
  2822. if ((nNonce & 0xffff) == 0)
  2823. {
  2824. nHashesDone = 0xffff+1;
  2825. return (unsigned int) -1;
  2826. }
  2827. }
  2828. }
  2829. // Some explaining would be appreciated
  2830. class COrphan
  2831. {
  2832. public:
  2833. CTransaction* ptx;
  2834. set<uint256> setDependsOn;
  2835. double dPriority;
  2836. COrphan(CTransaction* ptxIn)
  2837. {
  2838. ptx = ptxIn;
  2839. dPriority = 0;
  2840. }
  2841. void print() const
  2842. {
  2843. printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
  2844. BOOST_FOREACH(uint256 hash, setDependsOn)
  2845. printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
  2846. }
  2847. };
  2848. uint64 nLastBlockTx = 0;
  2849. uint64 nLastBlockSize = 0;
  2850. CBlock* CreateNewBlock(CReserveKey& reservekey)
  2851. {
  2852. CBlockIndex* pindexPrev = pindexBest;
  2853. // Create new block
  2854. auto_ptr<CBlock> pblock(new CBlock());
  2855. if (!pblock.get())
  2856. return NULL;
  2857. // Create coinbase tx
  2858. CTransaction txNew;
  2859. txNew.vin.resize(1);
  2860. txNew.vin[0].prevout.SetNull();
  2861. txNew.vout.resize(1);
  2862. txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
  2863. // Add our coinbase tx as first transaction
  2864. pblock->vtx.push_back(txNew);
  2865. // Collect memory pool transactions into the block
  2866. int64 nFees = 0;
  2867. {
  2868. LOCK2(cs_main, mempool.cs);
  2869. CTxDB txdb("r");
  2870. // Priority order to process transactions
  2871. list<COrphan> vOrphan; // list memory doesn't move
  2872. map<uint256, vector<COrphan*> > mapDependers;
  2873. multimap<double, CTransaction*> mapPriority;
  2874. for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
  2875. {
  2876. CTransaction& tx = (*mi).second;
  2877. if (tx.IsCoinBase() || !tx.IsFinal())
  2878. continue;
  2879. COrphan* porphan = NULL;
  2880. double dPriority = 0;
  2881. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  2882. {
  2883. // Read prev transaction
  2884. CTransaction txPrev;
  2885. CTxIndex txindex;
  2886. if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
  2887. {
  2888. // Has to wait for dependencies
  2889. if (!porphan)
  2890. {
  2891. // Use list for automatic deletion
  2892. vOrphan.push_back(COrphan(&tx));
  2893. porphan = &vOrphan.back();
  2894. }
  2895. mapDependers[txin.prevout.hash].push_back(porphan);
  2896. porphan->setDependsOn.insert(txin.prevout.hash);
  2897. continue;
  2898. }
  2899. int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
  2900. // Read block header
  2901. int nConf = txindex.GetDepthInMainChain();
  2902. dPriority += (double)nValueIn * nConf;
  2903. if (fDebug && GetBoolArg("-printpriority"))
  2904. printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
  2905. }
  2906. // Priority is sum(valuein * age) / txsize
  2907. dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  2908. if (porphan)
  2909. porphan->dPriority = dPriority;
  2910. else
  2911. mapPriority.insert(make_pair(-dPriority, &(*mi).second));
  2912. if (fDebug && GetBoolArg("-printpriority"))
  2913. {
  2914. printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
  2915. if (porphan)
  2916. porphan->print();
  2917. printf("\n");
  2918. }
  2919. }
  2920. // Collect transactions into block
  2921. map<uint256, CTxIndex> mapTestPool;
  2922. uint64 nBlockSize = 1000;
  2923. uint64 nBlockTx = 0;
  2924. int nBlockSigOps = 100;
  2925. while (!mapPriority.empty())
  2926. {
  2927. // Take highest priority transaction off priority queue
  2928. double dPriority = -(*mapPriority.begin()).first;
  2929. CTransaction& tx = *(*mapPriority.begin()).second;
  2930. mapPriority.erase(mapPriority.begin());
  2931. // Size limits
  2932. unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  2933. if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
  2934. continue;
  2935. // Legacy limits on sigOps:
  2936. unsigned int nTxSigOps = tx.GetLegacySigOpCount();
  2937. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
  2938. continue;
  2939. // Transaction fee required depends on block size
  2940. // Litecoind: Reduce the exempted free transactions to 500 bytes (from Bitcoin's 3000 bytes)
  2941. bool fAllowFree = (nBlockSize + nTxSize < 1500 || CTransaction::AllowFree(dPriority));
  2942. int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
  2943. // Connecting shouldn't fail due to dependency on other memory pool transactions
  2944. // because we're already processing them in order of dependency
  2945. map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
  2946. MapPrevTx mapInputs;
  2947. bool fInvalid;
  2948. if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
  2949. continue;
  2950. int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
  2951. if (nTxFees < nMinFee)
  2952. continue;
  2953. nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
  2954. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
  2955. continue;
  2956. if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
  2957. continue;
  2958. mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
  2959. swap(mapTestPool, mapTestPoolTmp);
  2960. // Added
  2961. pblock->vtx.push_back(tx);
  2962. nBlockSize += nTxSize;
  2963. ++nBlockTx;
  2964. nBlockSigOps += nTxSigOps;
  2965. nFees += nTxFees;
  2966. // Add transactions that depend on this one to the priority queue
  2967. uint256 hash = tx.GetHash();
  2968. if (mapDependers.count(hash))
  2969. {
  2970. BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
  2971. {
  2972. if (!porphan->setDependsOn.empty())
  2973. {
  2974. porphan->setDependsOn.erase(hash);
  2975. if (porphan->setDependsOn.empty())
  2976. mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
  2977. }
  2978. }
  2979. }
  2980. }
  2981. nLastBlockTx = nBlockTx;
  2982. nLastBlockSize = nBlockSize;
  2983. printf("CreateNewBlock(): total size %lu\n", nBlockSize);
  2984. }
  2985. pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
  2986. // Fill in header
  2987. pblock->hashPrevBlock = pindexPrev->GetBlockHash();
  2988. pblock->hashMerkleRoot = pblock->BuildMerkleTree();
  2989. pblock->UpdateTime(pindexPrev);
  2990. pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
  2991. pblock->nNonce = 0;
  2992. return pblock.release();
  2993. }
  2994. void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
  2995. {
  2996. // Update nExtraNonce
  2997. static uint256 hashPrevBlock;
  2998. if (hashPrevBlock != pblock->hashPrevBlock)
  2999. {
  3000. nExtraNonce = 0;
  3001. hashPrevBlock = pblock->hashPrevBlock;
  3002. }
  3003. ++nExtraNonce;
  3004. pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
  3005. assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
  3006. pblock->hashMerkleRoot = pblock->BuildMerkleTree();
  3007. }
  3008. void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
  3009. {
  3010. //
  3011. // Prebuild hash buffers
  3012. //
  3013. struct
  3014. {
  3015. struct unnamed2
  3016. {
  3017. int nVersion;
  3018. uint256 hashPrevBlock;
  3019. uint256 hashMerkleRoot;
  3020. unsigned int nTime;
  3021. unsigned int nBits;
  3022. unsigned int nNonce;
  3023. }
  3024. block;
  3025. unsigned char pchPadding0[64];
  3026. uint256 hash1;
  3027. unsigned char pchPadding1[64];
  3028. }
  3029. tmp;
  3030. memset(&tmp, 0, sizeof(tmp));
  3031. tmp.block.nVersion = pblock->nVersion;
  3032. tmp.block.hashPrevBlock = pblock->hashPrevBlock;
  3033. tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
  3034. tmp.block.nTime = pblock->nTime;
  3035. tmp.block.nBits = pblock->nBits;
  3036. tmp.block.nNonce = pblock->nNonce;
  3037. FormatHashBlocks(&tmp.block, sizeof(tmp.block));
  3038. FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
  3039. // Byte swap all the input buffer
  3040. for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
  3041. ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
  3042. // Precalc the first half of the first hash, which stays constant
  3043. SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
  3044. memcpy(pdata, &tmp.block, 128);
  3045. memcpy(phash1, &tmp.hash1, 64);
  3046. }
  3047. bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
  3048. {
  3049. uint256 hash = pblock->GetPoWHash();
  3050. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  3051. if (hash > hashTarget)
  3052. return false;
  3053. //// debug print
  3054. printf("BitcoinMiner:\n");
  3055. printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
  3056. pblock->print();
  3057. printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
  3058. // Found a solution
  3059. {
  3060. LOCK(cs_main);
  3061. if (pblock->hashPrevBlock != hashBestChain)
  3062. return error("BitcoinMiner : generated block is stale");
  3063. // Remove key from key pool
  3064. reservekey.KeepKey();
  3065. // Track how many getdata requests this block gets
  3066. {
  3067. LOCK(wallet.cs_wallet);
  3068. wallet.mapRequestCount[pblock->GetHash()] = 0;
  3069. }
  3070. // Process this block the same as if we had received it from another node
  3071. if (!ProcessBlock(NULL, pblock))
  3072. return error("BitcoinMiner : ProcessBlock, block not accepted");
  3073. }
  3074. return true;
  3075. }
  3076. void static ThreadBitcoinMiner(void* parg);
  3077. static bool fGenerateBitcoins = false;
  3078. static bool fLimitProcessors = false;
  3079. static int nLimitProcessors = -1;
  3080. void static BitcoinMiner(CWallet *pwallet)
  3081. {
  3082. printf("BitcoinMiner started\n");
  3083. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  3084. // Make this thread recognisable as the mining thread
  3085. RenameThread("bitcoin-miner");
  3086. // Each thread has its own key and counter
  3087. CReserveKey reservekey(pwallet);
  3088. unsigned int nExtraNonce = 0;
  3089. while (fGenerateBitcoins)
  3090. {
  3091. if (fShutdown)
  3092. return;
  3093. while (vNodes.empty() || IsInitialBlockDownload())
  3094. {
  3095. Sleep(1000);
  3096. if (fShutdown)
  3097. return;
  3098. if (!fGenerateBitcoins)
  3099. return;
  3100. }
  3101. //
  3102. // Create new block
  3103. //
  3104. unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
  3105. CBlockIndex* pindexPrev = pindexBest;
  3106. auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
  3107. if (!pblock.get())
  3108. return;
  3109. IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
  3110. printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
  3111. //
  3112. // Prebuild hash buffers
  3113. //
  3114. char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
  3115. char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
  3116. char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
  3117. FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
  3118. unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
  3119. unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
  3120. //unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
  3121. //
  3122. // Search
  3123. //
  3124. int64 nStart = GetTime();
  3125. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  3126. loop
  3127. {
  3128. unsigned int nHashesDone = 0;
  3129. //unsigned int nNonceFound;
  3130. uint256 thash;
  3131. char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
  3132. loop
  3133. {
  3134. scrypt_1024_1_1_256_sp(BEGIN(pblock->nVersion), BEGIN(thash), scratchpad);
  3135. if (thash <= hashTarget)
  3136. {
  3137. // Found a solution
  3138. SetThreadPriority(THREAD_PRIORITY_NORMAL);
  3139. CheckWork(pblock.get(), *pwalletMain, reservekey);
  3140. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  3141. break;
  3142. }
  3143. pblock->nNonce += 1;
  3144. nHashesDone += 1;
  3145. if ((pblock->nNonce & 0xFF) == 0)
  3146. break;
  3147. }
  3148. // Meter hashes/sec
  3149. static int64 nHashCounter;
  3150. if (nHPSTimerStart == 0)
  3151. {
  3152. nHPSTimerStart = GetTimeMillis();
  3153. nHashCounter = 0;
  3154. }
  3155. else
  3156. nHashCounter += nHashesDone;
  3157. if (GetTimeMillis() - nHPSTimerStart > 4000)
  3158. {
  3159. static CCriticalSection cs;
  3160. {
  3161. LOCK(cs);
  3162. if (GetTimeMillis() - nHPSTimerStart > 4000)
  3163. {
  3164. dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
  3165. nHPSTimerStart = GetTimeMillis();
  3166. nHashCounter = 0;
  3167. string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
  3168. static int64 nLogTime;
  3169. if (GetTime() - nLogTime > 30 * 60)
  3170. {
  3171. nLogTime = GetTime();
  3172. printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
  3173. printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
  3174. }
  3175. }
  3176. }
  3177. }
  3178. // Check for stop or if block needs to be rebuilt
  3179. if (fShutdown)
  3180. return;
  3181. if (!fGenerateBitcoins)
  3182. return;
  3183. if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
  3184. return;
  3185. if (vNodes.empty())
  3186. break;
  3187. if (pblock->nNonce >= 0xffff0000)
  3188. break;
  3189. if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
  3190. break;
  3191. if (pindexPrev != pindexBest)
  3192. break;
  3193. // Update nTime every few seconds
  3194. pblock->UpdateTime(pindexPrev);
  3195. nBlockTime = ByteReverse(pblock->nTime);
  3196. if (fTestNet)
  3197. {
  3198. // Changing pblock->nTime can change work required on testnet:
  3199. nBlockBits = ByteReverse(pblock->nBits);
  3200. hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  3201. }
  3202. }
  3203. }
  3204. }
  3205. void static ThreadBitcoinMiner(void* parg)
  3206. {
  3207. CWallet* pwallet = (CWallet*)parg;
  3208. try
  3209. {
  3210. vnThreadsRunning[THREAD_MINER]++;
  3211. BitcoinMiner(pwallet);
  3212. vnThreadsRunning[THREAD_MINER]--;
  3213. }
  3214. catch (std::exception& e) {
  3215. vnThreadsRunning[THREAD_MINER]--;
  3216. PrintException(&e, "ThreadBitcoinMiner()");
  3217. } catch (...) {
  3218. vnThreadsRunning[THREAD_MINER]--;
  3219. PrintException(NULL, "ThreadBitcoinMiner()");
  3220. }
  3221. nHPSTimerStart = 0;
  3222. if (vnThreadsRunning[THREAD_MINER] == 0)
  3223. dHashesPerSec = 0;
  3224. printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
  3225. }
  3226. void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
  3227. {
  3228. fGenerateBitcoins = fGenerate;
  3229. nLimitProcessors = GetArg("-genproclimit", -1);
  3230. if (nLimitProcessors == 0)
  3231. fGenerateBitcoins = false;
  3232. fLimitProcessors = (nLimitProcessors != -1);
  3233. if (fGenerate)
  3234. {
  3235. int nProcessors = boost::thread::hardware_concurrency();
  3236. printf("%d processors\n", nProcessors);
  3237. if (nProcessors < 1)
  3238. nProcessors = 1;
  3239. if (fLimitProcessors && nProcessors > nLimitProcessors)
  3240. nProcessors = nLimitProcessors;
  3241. int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
  3242. printf("Starting %d BitcoinMiner threads\n", nAddThreads);
  3243. for (int i = 0; i < nAddThreads; i++)
  3244. {
  3245. if (!CreateThread(ThreadBitcoinMiner, pwallet))
  3246. printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
  3247. Sleep(10);
  3248. }
  3249. }
  3250. }