PageRenderTime 44ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 1ms

/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

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

  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(…

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