Advertisement
Fromubiz

Untitled

Nov 20th, 2021
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 172.92 KB | None | 0 0
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5.  
  6. #include "alert.h"
  7. #include "checkpoints.h"
  8. #include "db.h"
  9. #include "txdb.h"
  10. #include "net.h"
  11. #include "init.h"
  12. #include "ui_interface.h"
  13. #include "checkqueue.h"
  14. #include <boost/algorithm/string/replace.hpp>
  15. #include <boost/filesystem.hpp>
  16. #include <boost/filesystem/fstream.hpp>
  17.  
  18. using namespace std;
  19. using namespace boost;
  20.  
  21. #if defined(NDEBUG)
  22. # error "Shibacoin cannot be compiled without assertions."
  23. #endif
  24.  
  25. //
  26. // Global state
  27. //
  28.  
  29. CCriticalSection cs_setpwalletRegistered;
  30. set<CWallet*> setpwalletRegistered;
  31.  
  32. CCriticalSection cs_main;
  33.  
  34. CTxMemPool mempool;
  35. unsigned int nTransactionsUpdated = 0;
  36.  
  37. map<uint256, CBlockIndex*> mapBlockIndex;
  38. uint256 hashGenesisBlock("0xb28190c0335ef142d1c8cb4ad844f6943c50838428eb983b43d9cdeadd5fe3f0");
  39. static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // Shibacoin: starting difficulty is 1 / 2^12
  40. CBlockIndex* pindexGenesisBlock = NULL;
  41. int nBestHeight = -1;
  42. uint256 nBestChainWork = 0;
  43. uint256 nBestInvalidWork = 0;
  44. uint256 hashBestChain = 0;
  45. CBlockIndex* pindexBest = NULL;
  46. set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; // may contain all CBlockIndex*'s that have validness >=BLOCK_VALID_TRANSACTIONS, and must contain those who aren't failed
  47. int64 nTimeBestReceived = 0;
  48. int nScriptCheckThreads = 0;
  49. bool fImporting = false;
  50. bool fReindex = false;
  51. bool fBenchmark = false;
  52. bool fTxIndex = false;
  53. unsigned int nCoinCacheSize = 5000;
  54.  
  55. /** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
  56. int64 CTransaction::nMinTxFee = 100000;
  57. /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
  58. int64 CTransaction::nMinRelayTxFee = 100000;
  59.  
  60. CMedianFilter<int> cPeerBlockCounts(8, 0); // Amount of blocks that other nodes claim to have
  61.  
  62. map<uint256, CBlock*> mapOrphanBlocks;
  63. multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
  64.  
  65. map<uint256, CTransaction> mapOrphanTransactions;
  66. map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
  67.  
  68. // Constant stuff for coinbase transactions we create:
  69. CScript COINBASE_FLAGS;
  70.  
  71. const string strMessageMagic = "Shibacoin Signed Message:\n";
  72.  
  73. double dHashesPerSec = 0.0;
  74. int64 nHPSTimerStart = 0;
  75.  
  76. // Settings
  77. int64 nTransactionFee = 0;
  78. int64 nMinimumInputValue = DUST_HARD_LIMIT;
  79.  
  80.  
  81. //////////////////////////////////////////////////////////////////////////////
  82. //
  83. // dispatching functions
  84. //
  85.  
  86. // These functions dispatch to one or all registered wallets
  87.  
  88.  
  89. void RegisterWallet(CWallet* pwalletIn)
  90. {
  91. {
  92. LOCK(cs_setpwalletRegistered);
  93. setpwalletRegistered.insert(pwalletIn);
  94. }
  95. }
  96.  
  97. void UnregisterWallet(CWallet* pwalletIn)
  98. {
  99. {
  100. LOCK(cs_setpwalletRegistered);
  101. setpwalletRegistered.erase(pwalletIn);
  102. }
  103. }
  104.  
  105. // get the wallet transaction with the given hash (if it exists)
  106. bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
  107. {
  108. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  109. if (pwallet->GetTransaction(hashTx,wtx))
  110. return true;
  111. return false;
  112. }
  113.  
  114. // erases transaction with the given hash from all wallets
  115. void static EraseFromWallets(uint256 hash)
  116. {
  117. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  118. pwallet->EraseFromWallet(hash);
  119. }
  120.  
  121. // make sure all wallets know about the given transaction, in the given block
  122. void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate)
  123. {
  124. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  125. pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
  126. }
  127.  
  128. // notify wallets about a new best chain
  129. void static SetBestChain(const CBlockLocator& loc)
  130. {
  131. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  132. pwallet->SetBestChain(loc);
  133. }
  134.  
  135. // notify wallets about an updated transaction
  136. void static UpdatedTransaction(const uint256& hashTx)
  137. {
  138. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  139. pwallet->UpdatedTransaction(hashTx);
  140. }
  141.  
  142. // dump all wallets
  143. void static PrintWallets(const CBlock& block)
  144. {
  145. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  146. pwallet->PrintWallet(block);
  147. }
  148.  
  149. // notify wallets about an incoming inventory (for request counts)
  150. void static Inventory(const uint256& hash)
  151. {
  152. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  153. pwallet->Inventory(hash);
  154. }
  155.  
  156. // ask wallets to resend their transactions
  157. void static ResendWalletTransactions()
  158. {
  159. BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
  160. pwallet->ResendWalletTransactions();
  161. }
  162.  
  163.  
  164.  
  165.  
  166.  
  167.  
  168.  
  169. //////////////////////////////////////////////////////////////////////////////
  170. //
  171. // CCoinsView implementations
  172. //
  173.  
  174. bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) { return false; }
  175. bool CCoinsView::SetCoins(const uint256 &txid, const CCoins &coins) { return false; }
  176. bool CCoinsView::HaveCoins(const uint256 &txid) { return false; }
  177. CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
  178. bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
  179. bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
  180. bool CCoinsView::GetStats(CCoinsStats &stats) { return false; }
  181.  
  182.  
  183. CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
  184. bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) { return base->GetCoins(txid, coins); }
  185. bool CCoinsViewBacked::SetCoins(const uint256 &txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
  186. bool CCoinsViewBacked::HaveCoins(const uint256 &txid) { return base->HaveCoins(txid); }
  187. CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
  188. bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
  189. void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
  190. bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
  191. bool CCoinsViewBacked::GetStats(CCoinsStats &stats) { return base->GetStats(stats); }
  192.  
  193. CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
  194.  
  195. bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) {
  196. if (cacheCoins.count(txid)) {
  197. coins = cacheCoins[txid];
  198. return true;
  199. }
  200. if (base->GetCoins(txid, coins)) {
  201. cacheCoins[txid] = coins;
  202. return true;
  203. }
  204. return false;
  205. }
  206.  
  207. std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(const uint256 &txid) {
  208. std::map<uint256,CCoins>::iterator it = cacheCoins.lower_bound(txid);
  209. if (it != cacheCoins.end() && it->first == txid)
  210. return it;
  211. CCoins tmp;
  212. if (!base->GetCoins(txid,tmp))
  213. return cacheCoins.end();
  214. std::map<uint256,CCoins>::iterator ret = cacheCoins.insert(it, std::make_pair(txid, CCoins()));
  215. tmp.swap(ret->second);
  216. return ret;
  217. }
  218.  
  219. CCoins &CCoinsViewCache::GetCoins(const uint256 &txid) {
  220. std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
  221. assert(it != cacheCoins.end());
  222. return it->second;
  223. }
  224.  
  225. bool CCoinsViewCache::SetCoins(const uint256 &txid, const CCoins &coins) {
  226. cacheCoins[txid] = coins;
  227. return true;
  228. }
  229.  
  230. bool CCoinsViewCache::HaveCoins(const uint256 &txid) {
  231. return FetchCoins(txid) != cacheCoins.end();
  232. }
  233.  
  234. CBlockIndex *CCoinsViewCache::GetBestBlock() {
  235. if (pindexTip == NULL)
  236. pindexTip = base->GetBestBlock();
  237. return pindexTip;
  238. }
  239.  
  240. bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
  241. pindexTip = pindex;
  242. return true;
  243. }
  244.  
  245. bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
  246. for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
  247. cacheCoins[it->first] = it->second;
  248. pindexTip = pindex;
  249. return true;
  250. }
  251.  
  252. bool CCoinsViewCache::Flush() {
  253. bool fOk = base->BatchWrite(cacheCoins, pindexTip);
  254. if (fOk)
  255. cacheCoins.clear();
  256. return fOk;
  257. }
  258.  
  259. unsigned int CCoinsViewCache::GetCacheSize() {
  260. return cacheCoins.size();
  261. }
  262.  
  263. /** CCoinsView that brings transactions from a memorypool into view.
  264. It does not check for spendings by memory pool transactions. */
  265. CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
  266.  
  267. bool CCoinsViewMemPool::GetCoins(const uint256 &txid, CCoins &coins) {
  268. if (base->GetCoins(txid, coins))
  269. return true;
  270. if (mempool.exists(txid)) {
  271. const CTransaction &tx = mempool.lookup(txid);
  272. coins = CCoins(tx, MEMPOOL_HEIGHT);
  273. return true;
  274. }
  275. return false;
  276. }
  277.  
  278. bool CCoinsViewMemPool::HaveCoins(const uint256 &txid) {
  279. return mempool.exists(txid) || base->HaveCoins(txid);
  280. }
  281.  
  282. CCoinsViewCache *pcoinsTip = NULL;
  283. CBlockTreeDB *pblocktree = NULL;
  284.  
  285. //////////////////////////////////////////////////////////////////////////////
  286. //
  287. // mapOrphanTransactions
  288. //
  289.  
  290. bool AddOrphanTx(const CTransaction& tx)
  291. {
  292. uint256 hash = tx.GetHash();
  293. if (mapOrphanTransactions.count(hash))
  294. return false;
  295.  
  296. // Ignore big transactions, to avoid a
  297. // send-big-orphans memory exhaustion attack. If a peer has a legitimate
  298. // large transaction with a missing parent then we assume
  299. // it will rebroadcast it later, after the parent transaction(s)
  300. // have been mined or received.
  301. // 10,000 orphans, each of which is at most 5,000 bytes big is
  302. // at most 500 megabytes of orphans:
  303. unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
  304. if (sz > 5000)
  305. {
  306. printf("ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString().c_str());
  307. return false;
  308. }
  309.  
  310. mapOrphanTransactions[hash] = tx;
  311. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  312. mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
  313.  
  314. printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().c_str(),
  315. mapOrphanTransactions.size());
  316. return true;
  317. }
  318.  
  319. void static EraseOrphanTx(uint256 hash)
  320. {
  321. map<uint256, CTransaction>::iterator it = mapOrphanTransactions.find(hash);
  322. if (it == mapOrphanTransactions.end())
  323. return;
  324. BOOST_FOREACH(const CTxIn& txin, it->second.vin)
  325. {
  326. map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
  327. if (itPrev == mapOrphanTransactionsByPrev.end())
  328. continue;
  329. itPrev->second.erase(hash);
  330. if (itPrev->second.empty())
  331. mapOrphanTransactionsByPrev.erase(itPrev);
  332. }
  333. mapOrphanTransactions.erase(it);
  334. }
  335.  
  336. unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
  337. {
  338. unsigned int nEvicted = 0;
  339. while (mapOrphanTransactions.size() > nMaxOrphans)
  340. {
  341. // Evict a random orphan:
  342. uint256 randomhash = GetRandHash();
  343. map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
  344. if (it == mapOrphanTransactions.end())
  345. it = mapOrphanTransactions.begin();
  346. EraseOrphanTx(it->first);
  347. ++nEvicted;
  348. }
  349. return nEvicted;
  350. }
  351.  
  352.  
  353.  
  354.  
  355.  
  356.  
  357.  
  358. //////////////////////////////////////////////////////////////////////////////
  359. //
  360. // CTransaction / CTxOut
  361. //
  362.  
  363. bool CTxOut::IsDust() const
  364. {
  365. // Shibacoin: IsDust() detection disabled, allows any valid dust to be relayed.
  366. // The fees imposed on each dust txo is considered sufficient spam deterrant.
  367. return false;
  368. }
  369.  
  370. bool CTransaction::IsStandard(string& strReason) const
  371. {
  372. if (nVersion > CTransaction::CURRENT_VERSION || nVersion < 1) {
  373. strReason = "version";
  374. return false;
  375. }
  376.  
  377. if (!IsFinal()) {
  378. strReason = "not-final";
  379. return false;
  380. }
  381.  
  382. // Extremely large transactions with lots of inputs can cost the network
  383. // almost as much to process as they cost the sender in fees, because
  384. // computing signature hashes is O(ninputs*txsize). Limiting transactions
  385. // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
  386. unsigned int sz = this->GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
  387. if (sz >= MAX_STANDARD_TX_SIZE) {
  388. strReason = "tx-size";
  389. return false;
  390. }
  391.  
  392. BOOST_FOREACH(const CTxIn& txin, vin)
  393. {
  394. // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
  395. // pay-to-script-hash, which is 3 ~80-byte signatures, 3
  396. // ~65-byte public keys, plus a few script ops.
  397. if (txin.scriptSig.size() > 500) {
  398. strReason = "scriptsig-size";
  399. return false;
  400. }
  401. if (!txin.scriptSig.IsPushOnly()) {
  402. strReason = "scriptsig-not-pushonly";
  403. return false;
  404. }
  405. if (!txin.scriptSig.HasCanonicalPushes()) {
  406. strReason = "non-canonical-push";
  407. return false;
  408. }
  409. }
  410. BOOST_FOREACH(const CTxOut& txout, vout) {
  411. if (!::IsStandard(txout.scriptPubKey)) {
  412. strReason = "scriptpubkey";
  413. return false;
  414. }
  415. if (txout.IsDust()) {
  416. strReason = "dust";
  417. return false;
  418. }
  419. }
  420. return true;
  421. }
  422.  
  423. //
  424. // Check transaction inputs, and make sure any
  425. // pay-to-script-hash transactions are evaluating IsStandard scripts
  426. //
  427. // Why bother? To avoid denial-of-service attacks; an attacker
  428. // can submit a standard HASH... OP_EQUAL transaction,
  429. // which will get accepted into blocks. The redemption
  430. // script can be anything; an attacker could use a very
  431. // expensive-to-check-upon-redemption script like:
  432. // DUP CHECKSIG DROP ... repeated 100 times... OP_1
  433. //
  434. bool CTransaction::AreInputsStandard(CCoinsViewCache& mapInputs) const
  435. {
  436. if (IsCoinBase())
  437. return true; // Coinbases don't use vin normally
  438.  
  439. for (unsigned int i = 0; i < vin.size(); i++)
  440. {
  441. const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
  442.  
  443. vector<vector<unsigned char> > vSolutions;
  444. txnouttype whichType;
  445. // get the scriptPubKey corresponding to this input:
  446. const CScript& prevScript = prev.scriptPubKey;
  447. if (!Solver(prevScript, whichType, vSolutions))
  448. return false;
  449. int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
  450. if (nArgsExpected < 0)
  451. return false;
  452.  
  453. // Transactions with extra stuff in their scriptSigs are
  454. // non-standard. Note that this EvalScript() call will
  455. // be quick, because if there are any operations
  456. // beside "push data" in the scriptSig the
  457. // IsStandard() call returns false
  458. vector<vector<unsigned char> > stack;
  459. if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
  460. return false;
  461.  
  462. if (whichType == TX_SCRIPTHASH)
  463. {
  464. if (stack.empty())
  465. return false;
  466. CScript subscript(stack.back().begin(), stack.back().end());
  467. vector<vector<unsigned char> > vSolutions2;
  468. txnouttype whichType2;
  469. if (!Solver(subscript, whichType2, vSolutions2))
  470. return false;
  471. if (whichType2 == TX_SCRIPTHASH)
  472. return false;
  473.  
  474. int tmpExpected;
  475. tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
  476. if (tmpExpected < 0)
  477. return false;
  478. nArgsExpected += tmpExpected;
  479. }
  480.  
  481. if (stack.size() != (unsigned int)nArgsExpected)
  482. return false;
  483. }
  484.  
  485. return true;
  486. }
  487.  
  488. unsigned int CTransaction::GetLegacySigOpCount() const
  489. {
  490. unsigned int nSigOps = 0;
  491. BOOST_FOREACH(const CTxIn& txin, vin)
  492. {
  493. nSigOps += txin.scriptSig.GetSigOpCount(false);
  494. }
  495. BOOST_FOREACH(const CTxOut& txout, vout)
  496. {
  497. nSigOps += txout.scriptPubKey.GetSigOpCount(false);
  498. }
  499. return nSigOps;
  500. }
  501.  
  502.  
  503. int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
  504. {
  505. CBlock blockTmp;
  506.  
  507. if (pblock == NULL) {
  508. CCoins coins;
  509. if (pcoinsTip->GetCoins(GetHash(), coins)) {
  510. CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
  511. if (pindex) {
  512. if (!blockTmp.ReadFromDisk(pindex))
  513. return 0;
  514. pblock = &blockTmp;
  515. }
  516. }
  517. }
  518.  
  519. if (pblock) {
  520. // Update the tx's hashBlock
  521. hashBlock = pblock->GetHash();
  522.  
  523. // Locate the transaction
  524. for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
  525. if (pblock->vtx[nIndex] == *(CTransaction*)this)
  526. break;
  527. if (nIndex == (int)pblock->vtx.size())
  528. {
  529. vMerkleBranch.clear();
  530. nIndex = -1;
  531. printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
  532. return 0;
  533. }
  534.  
  535. // Fill in merkle branch
  536. vMerkleBranch = pblock->GetMerkleBranch(nIndex);
  537. }
  538.  
  539. // Is the tx in a block that's in the main chain
  540. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  541. if (mi == mapBlockIndex.end())
  542. return 0;
  543. CBlockIndex* pindex = (*mi).second;
  544. if (!pindex || !pindex->IsInMainChain())
  545. return 0;
  546.  
  547. return pindexBest->nHeight - pindex->nHeight + 1;
  548. }
  549.  
  550.  
  551.  
  552.  
  553.  
  554.  
  555.  
  556. bool CTransaction::CheckTransaction(CValidationState &state) const
  557. {
  558. // Basic checks that don't depend on any context
  559. if (vin.empty())
  560. return state.DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
  561. if (vout.empty())
  562. return state.DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
  563. // Size limits
  564. if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
  565. return state.DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
  566.  
  567. // Check for negative or overflow output values
  568. int64 nValueOut = 0;
  569. BOOST_FOREACH(const CTxOut& txout, vout)
  570. {
  571. if (txout.nValue < 0)
  572. return state.DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
  573. if (txout.nValue > MAX_MONEY)
  574. return state.DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
  575. nValueOut += txout.nValue;
  576. if (!MoneyRange(nValueOut))
  577. return state.DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
  578. }
  579.  
  580. // Check for duplicate inputs
  581. set<COutPoint> vInOutPoints;
  582. BOOST_FOREACH(const CTxIn& txin, vin)
  583. {
  584. if (vInOutPoints.count(txin.prevout))
  585. return state.DoS(100, error("CTransaction::CheckTransaction() : duplicate inputs"));
  586. vInOutPoints.insert(txin.prevout);
  587. }
  588.  
  589. if (IsCoinBase())
  590. {
  591. if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
  592. return state.DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
  593. }
  594. else
  595. {
  596. BOOST_FOREACH(const CTxIn& txin, vin)
  597. if (txin.prevout.IsNull())
  598. return state.DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
  599. }
  600.  
  601. return true;
  602. }
  603.  
  604. int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
  605. enum GetMinFee_mode mode) const
  606. {
  607. // Base fee is either nMinTxFee or nMinRelayTxFee
  608. int64 nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
  609.  
  610. unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
  611. unsigned int nNewBlockSize = nBlockSize + nBytes;
  612. int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
  613.  
  614. if (fAllowFree)
  615. {
  616. // There is a free transaction area in blocks created by most miners,
  617. // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
  618. // to be considered to fall into this category. We don't want to encourage sending
  619. // multiple transactions instead of one big transaction to avoid fees.
  620. // * If we are creating a transaction we allow transactions up to 5,000 bytes
  621. // to be considered safe and assume they can likely make it into this section.
  622. if (nBytes < (mode == GMF_SEND ? 5000 : (DEFAULT_BLOCK_PRIORITY_SIZE - 1000)))
  623. nMinFee = 0;
  624. }
  625.  
  626. // Shibacoin
  627. // To limit dust spam, add nBaseFee for each output less than DUST_SOFT_LIMIT
  628. BOOST_FOREACH(const CTxOut& txout, vout)
  629. if (txout.nValue < DUST_SOFT_LIMIT)
  630. nMinFee += nBaseFee;
  631.  
  632. // Raise the price as the block approaches full
  633. if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
  634. {
  635. if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
  636. return MAX_MONEY;
  637. nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
  638. }
  639.  
  640. if (!MoneyRange(nMinFee))
  641. nMinFee = MAX_MONEY;
  642. return nMinFee;
  643. }
  644.  
  645. void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
  646. {
  647. LOCK(cs);
  648.  
  649. std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
  650.  
  651. // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
  652. while (it != mapNextTx.end() && it->first.hash == hashTx) {
  653. coins.Spend(it->first.n); // and remove those outputs from coins
  654. it++;
  655. }
  656. }
  657.  
  658. bool CTxMemPool::accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree,
  659. bool* pfMissingInputs, bool fRejectInsaneFee)
  660. {
  661. if (pfMissingInputs)
  662. *pfMissingInputs = false;
  663.  
  664. if (!tx.CheckTransaction(state))
  665. return error("CTxMemPool::accept() : CheckTransaction failed");
  666.  
  667. // Coinbase is only valid in a block, not as a loose transaction
  668. if (tx.IsCoinBase())
  669. return state.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
  670.  
  671. // To help v0.1.5 clients who would see it as a negative number
  672. if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
  673. return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
  674.  
  675. // Rather not work on nonstandard transactions (unless -testnet)
  676. string strNonStd;
  677. if (!fTestNet && !tx.IsStandard(strNonStd))
  678. return error("CTxMemPool::accept() : nonstandard transaction (%s)",
  679. strNonStd.c_str());
  680.  
  681. // is it already in the memory pool?
  682. uint256 hash = tx.GetHash();
  683. {
  684. LOCK(cs);
  685. if (mapTx.count(hash))
  686. return false;
  687. }
  688.  
  689. // Check for conflicts with in-memory transactions
  690. CTransaction* ptxOld = NULL;
  691. for (unsigned int i = 0; i < tx.vin.size(); i++)
  692. {
  693. COutPoint outpoint = tx.vin[i].prevout;
  694. if (mapNextTx.count(outpoint))
  695. {
  696. // Disable replacement feature for now
  697. return false;
  698.  
  699. // Allow replacing with a newer version of the same transaction
  700. if (i != 0)
  701. return false;
  702. ptxOld = mapNextTx[outpoint].ptx;
  703. if (ptxOld->IsFinal())
  704. return false;
  705. if (!tx.IsNewerThan(*ptxOld))
  706. return false;
  707. for (unsigned int i = 0; i < tx.vin.size(); i++)
  708. {
  709. COutPoint outpoint = tx.vin[i].prevout;
  710. if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
  711. return false;
  712. }
  713. break;
  714. }
  715. }
  716.  
  717. if (fCheckInputs)
  718. {
  719. CCoinsView dummy;
  720. CCoinsViewCache view(dummy);
  721.  
  722. {
  723. LOCK(cs);
  724. CCoinsViewMemPool viewMemPool(*pcoinsTip, *this);
  725. view.SetBackend(viewMemPool);
  726.  
  727. // do we already have it?
  728. if (view.HaveCoins(hash))
  729. return false;
  730.  
  731. // do all inputs exist?
  732. // Note that this does not check for the presence of actual outputs (see the next check for that),
  733. // only helps filling in pfMissingInputs (to determine missing vs spent).
  734. BOOST_FOREACH(const CTxIn txin, tx.vin) {
  735. if (!view.HaveCoins(txin.prevout.hash)) {
  736. if (pfMissingInputs)
  737. *pfMissingInputs = true;
  738. return false;
  739. }
  740. }
  741.  
  742. // are the actual inputs available?
  743. if (!tx.HaveInputs(view))
  744. return state.Invalid(error("CTxMemPool::accept() : inputs already spent"));
  745.  
  746. // Bring the best block into scope
  747. view.GetBestBlock();
  748.  
  749. // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
  750. view.SetBackend(dummy);
  751. }
  752.  
  753. // Check for non-standard pay-to-script-hash in inputs
  754. if (!tx.AreInputsStandard(view) && !fTestNet)
  755. return error("CTxMemPool::accept() : nonstandard transaction input");
  756.  
  757. // Note: if you modify this code to accept non-standard transactions, then
  758. // you should add code here to check that the transaction does a
  759. // reasonable number of ECDSA signature verifications.
  760.  
  761. int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
  762. unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  763.  
  764. // Don't accept it if it can't get into a block
  765. int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
  766. if (fLimitFree && nFees < txMinFee)
  767. return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
  768. hash.ToString().c_str(),
  769. nFees, txMinFee);
  770.  
  771. // Continuously rate-limit free transactions
  772. // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
  773. // be annoying or make others' transactions take longer to confirm.
  774. if (fLimitFree && nFees < CTransaction::nMinRelayTxFee)
  775. {
  776. static double dFreeCount;
  777. static int64 nLastTime;
  778. int64 nNow = GetTime();
  779.  
  780. LOCK(cs);
  781.  
  782. // Use an exponentially decaying ~10-minute window:
  783. dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
  784. nLastTime = nNow;
  785. // -limitfreerelay unit is thousand-bytes-per-minute
  786. // At default rate it would take over a month to fill 1GB
  787. if (dFreeCount >= GetArg("-limitfreerelay", 15)*10*1000)
  788. return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
  789. if (fDebug)
  790. printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
  791. dFreeCount += nSize;
  792. }
  793.  
  794. if (fRejectInsaneFee && nFees > CTransaction::nMinRelayTxFee * 1000)
  795. return error("CTxMemPool::accept() : insane fees %s, %"PRI64d" > %"PRI64d,
  796. hash.ToString().c_str(),
  797. nFees, CTransaction::nMinRelayTxFee * 1000);
  798.  
  799. // Check against previous transactions
  800. // This is done last to help prevent CPU exhaustion denial-of-service attacks.
  801. if (!tx.CheckInputs(state, view, true, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC))
  802. {
  803. return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().c_str());
  804. }
  805. }
  806.  
  807. // Store transaction in memory
  808. {
  809. LOCK(cs);
  810. if (ptxOld)
  811. {
  812. printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
  813. remove(*ptxOld);
  814. }
  815. addUnchecked(hash, tx);
  816. }
  817.  
  818. ///// are we sure this is ok when loading transactions or restoring block txes
  819. // If updated, erase old tx from wallet
  820. if (ptxOld)
  821. EraseFromWallets(ptxOld->GetHash());
  822. SyncWithWallets(hash, tx, NULL, true);
  823.  
  824. return true;
  825. }
  826.  
  827. bool CTransaction::AcceptToMemoryPool(CValidationState &state, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee)
  828. {
  829. try {
  830. return mempool.accept(state, *this, fCheckInputs, fLimitFree, pfMissingInputs, fRejectInsaneFee);
  831. } catch(std::runtime_error &e) {
  832. return state.Abort(_("System error: ") + e.what());
  833. }
  834. }
  835.  
  836. bool CTxMemPool::addUnchecked(const uint256& hash, const CTransaction &tx)
  837. {
  838. // Add to memory pool without checking anything. Don't call this directly,
  839. // call CTxMemPool::accept to properly check the transaction first.
  840. {
  841. mapTx[hash] = tx;
  842. for (unsigned int i = 0; i < tx.vin.size(); i++)
  843. mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
  844. nTransactionsUpdated++;
  845. }
  846. return true;
  847. }
  848.  
  849.  
  850. bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive)
  851. {
  852. // Remove transaction from memory pool
  853. {
  854. LOCK(cs);
  855. uint256 hash = tx.GetHash();
  856. if (fRecursive) {
  857. for (unsigned int i = 0; i < tx.vout.size(); i++) {
  858. std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
  859. if (it != mapNextTx.end())
  860. remove(*it->second.ptx, true);
  861. }
  862. }
  863. if (mapTx.count(hash))
  864. {
  865. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  866. mapNextTx.erase(txin.prevout);
  867. mapTx.erase(hash);
  868. nTransactionsUpdated++;
  869. }
  870. }
  871. return true;
  872. }
  873.  
  874. bool CTxMemPool::removeConflicts(const CTransaction &tx)
  875. {
  876. // Remove transactions which depend on inputs of tx, recursively
  877. LOCK(cs);
  878. BOOST_FOREACH(const CTxIn &txin, tx.vin) {
  879. std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
  880. if (it != mapNextTx.end()) {
  881. const CTransaction &txConflict = *it->second.ptx;
  882. if (txConflict != tx)
  883. remove(txConflict, true);
  884. }
  885. }
  886. return true;
  887. }
  888.  
  889. void CTxMemPool::clear()
  890. {
  891. LOCK(cs);
  892. mapTx.clear();
  893. mapNextTx.clear();
  894. ++nTransactionsUpdated;
  895. }
  896.  
  897. void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
  898. {
  899. vtxid.clear();
  900.  
  901. LOCK(cs);
  902. vtxid.reserve(mapTx.size());
  903. for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
  904. vtxid.push_back((*mi).first);
  905. }
  906.  
  907.  
  908.  
  909.  
  910. int CMerkleTx::GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const
  911. {
  912. if (hashBlock == 0 || nIndex == -1)
  913. return 0;
  914.  
  915. // Find the block it claims to be in
  916. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
  917. if (mi == mapBlockIndex.end())
  918. return 0;
  919. CBlockIndex* pindex = (*mi).second;
  920. if (!pindex || !pindex->IsInMainChain())
  921. return 0;
  922.  
  923. // Make sure the merkle branch connects to this block
  924. if (!fMerkleVerified)
  925. {
  926. if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
  927. return 0;
  928. fMerkleVerified = true;
  929. }
  930.  
  931. pindexRet = pindex;
  932. return pindexBest->nHeight - pindex->nHeight + 1;
  933. }
  934.  
  935. int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
  936. {
  937. int nResult = GetDepthInMainChainINTERNAL(pindexRet);
  938. if (nResult == 0 && !mempool.exists(GetHash()))
  939. return -1; // Not in chain, not in mempool
  940.  
  941. return nResult;
  942. }
  943.  
  944. int CMerkleTx::GetBlocksToMaturity() const
  945. {
  946. if (!IsCoinBase())
  947. return 0;
  948. return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
  949. }
  950.  
  951.  
  952. bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs, bool fLimitFree)
  953. {
  954. CValidationState state;
  955. return CTransaction::AcceptToMemoryPool(state, fCheckInputs, fLimitFree);
  956. }
  957.  
  958.  
  959.  
  960. bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
  961. {
  962. {
  963. LOCK(mempool.cs);
  964. // Add previous supporting transactions first
  965. BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
  966. {
  967. if (!tx.IsCoinBase())
  968. {
  969. uint256 hash = tx.GetHash();
  970. if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
  971. tx.AcceptToMemoryPool(fCheckInputs, false);
  972. }
  973. }
  974. return AcceptToMemoryPool(fCheckInputs, false);
  975. }
  976. return false;
  977. }
  978.  
  979.  
  980. // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
  981. bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
  982. {
  983. CBlockIndex *pindexSlow = NULL;
  984. {
  985. LOCK(cs_main);
  986. {
  987. LOCK(mempool.cs);
  988. if (mempool.exists(hash))
  989. {
  990. txOut = mempool.lookup(hash);
  991. return true;
  992. }
  993. }
  994.  
  995. if (fTxIndex) {
  996. CDiskTxPos postx;
  997. if (pblocktree->ReadTxIndex(hash, postx)) {
  998. CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
  999. CBlockHeader header;
  1000. try {
  1001. file >> header;
  1002. fseek(file, postx.nTxOffset, SEEK_CUR);
  1003. file >> txOut;
  1004. } catch (std::exception &e) {
  1005. return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
  1006. }
  1007. hashBlock = header.GetHash();
  1008. if (txOut.GetHash() != hash)
  1009. return error("%s() : txid mismatch", __PRETTY_FUNCTION__);
  1010. return true;
  1011. }
  1012. }
  1013.  
  1014. if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
  1015. int nHeight = -1;
  1016. {
  1017. CCoinsViewCache &view = *pcoinsTip;
  1018. CCoins coins;
  1019. if (view.GetCoins(hash, coins))
  1020. nHeight = coins.nHeight;
  1021. }
  1022. if (nHeight > 0)
  1023. pindexSlow = FindBlockByHeight(nHeight);
  1024. }
  1025. }
  1026.  
  1027. if (pindexSlow) {
  1028. CBlock block;
  1029. if (block.ReadFromDisk(pindexSlow)) {
  1030. BOOST_FOREACH(const CTransaction &tx, block.vtx) {
  1031. if (tx.GetHash() == hash) {
  1032. txOut = tx;
  1033. hashBlock = pindexSlow->GetBlockHash();
  1034. return true;
  1035. }
  1036. }
  1037. }
  1038. }
  1039.  
  1040. return false;
  1041. }
  1042.  
  1043.  
  1044.  
  1045.  
  1046.  
  1047.  
  1048. //////////////////////////////////////////////////////////////////////////////
  1049. //
  1050. // CBlock and CBlockIndex
  1051. //
  1052.  
  1053. static CBlockIndex* pblockindexFBBHLast;
  1054. CBlockIndex* FindBlockByHeight(int nHeight)
  1055. {
  1056. CBlockIndex *pblockindex;
  1057. if (nHeight < nBestHeight / 2)
  1058. pblockindex = pindexGenesisBlock;
  1059. else
  1060. pblockindex = pindexBest;
  1061. if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
  1062. pblockindex = pblockindexFBBHLast;
  1063. while (pblockindex->nHeight > nHeight)
  1064. pblockindex = pblockindex->pprev;
  1065. while (pblockindex->nHeight < nHeight)
  1066. pblockindex = pblockindex->pnext;
  1067. pblockindexFBBHLast = pblockindex;
  1068. return pblockindex;
  1069. }
  1070.  
  1071. bool CBlock::ReadFromDisk(const CBlockIndex* pindex)
  1072. {
  1073. if (!ReadFromDisk(pindex->GetBlockPos()))
  1074. return false;
  1075. if (GetHash() != pindex->GetBlockHash())
  1076. return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
  1077. return true;
  1078. }
  1079.  
  1080. uint256 static GetOrphanRoot(const CBlockHeader* pblock)
  1081. {
  1082. // Work back to the first block in the orphan chain
  1083. while (mapOrphanBlocks.count(pblock->hashPrevBlock))
  1084. pblock = mapOrphanBlocks[pblock->hashPrevBlock];
  1085. return pblock->GetHash();
  1086. }
  1087.  
  1088. int64 static GetBlockValue(int nHeight, int64 nFees)
  1089. {
  1090. int64 nSubsidy = 50 * COIN;
  1091.  
  1092. // Subsidy is cut in half every 840000 blocks, which will occur approximately every 4 years
  1093. nSubsidy >>= (nHeight / 840000); // Shibacoin: 840k blocks in ~4 years
  1094.  
  1095. return nSubsidy + nFees;
  1096. }
  1097.  
  1098. static const int64 nTargetTimespan = 3.5 * 24 * 60 * 60; // Shibacoin: 3.5 days
  1099. static const int64 nTargetSpacing = 2.5 * 60; // Shibacoin: 2.5 minutes
  1100. static const int64 nInterval = nTargetTimespan / nTargetSpacing;
  1101.  
  1102. //
  1103. // minimum amount of work that could possibly be required nTime after
  1104. // minimum work required was nBase
  1105. //
  1106. unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
  1107. {
  1108. // Testnet has min-difficulty blocks
  1109. // after nTargetSpacing*2 time between blocks:
  1110. if (fTestNet && nTime > nTargetSpacing*2)
  1111. return bnProofOfWorkLimit.GetCompact();
  1112.  
  1113. CBigNum bnResult;
  1114. bnResult.SetCompact(nBase);
  1115. while (nTime > 0 && bnResult < bnProofOfWorkLimit)
  1116. {
  1117. // Maximum 400% adjustment...
  1118. bnResult *= 4;
  1119. // ... in best-case exactly 4-times-normal target time
  1120. nTime -= nTargetTimespan*4;
  1121. }
  1122. if (bnResult > bnProofOfWorkLimit)
  1123. bnResult = bnProofOfWorkLimit;
  1124. return bnResult.GetCompact();
  1125. }
  1126.  
  1127. unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)
  1128. {
  1129. unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
  1130.  
  1131. // Genesis block
  1132. if (pindexLast == NULL)
  1133. return nProofOfWorkLimit;
  1134.  
  1135. // Only change once per interval
  1136. if ((pindexLast->nHeight+1) % nInterval != 0)
  1137. {
  1138. // Special difficulty rule for testnet:
  1139. if (fTestNet)
  1140. {
  1141. // If the new block's timestamp is more than 2* 10 minutes
  1142. // then allow mining of a min-difficulty block.
  1143. if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
  1144. return nProofOfWorkLimit;
  1145. else
  1146. {
  1147. // Return the last non-special-min-difficulty-rules-block
  1148. const CBlockIndex* pindex = pindexLast;
  1149. while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
  1150. pindex = pindex->pprev;
  1151. return pindex->nBits;
  1152. }
  1153. }
  1154.  
  1155. return pindexLast->nBits;
  1156. }
  1157.  
  1158. // Shibacoin: This fixes an issue where a 51% attack can change difficulty at will.
  1159. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
  1160. int blockstogoback = nInterval-1;
  1161. if ((pindexLast->nHeight+1) != nInterval)
  1162. blockstogoback = nInterval;
  1163.  
  1164. // Go back by what we want to be 14 days worth of blocks
  1165. const CBlockIndex* pindexFirst = pindexLast;
  1166. for (int i = 0; pindexFirst && i < blockstogoback; i++)
  1167. pindexFirst = pindexFirst->pprev;
  1168. assert(pindexFirst);
  1169.  
  1170. // Limit adjustment step
  1171. int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
  1172. printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
  1173. if (nActualTimespan < nTargetTimespan/4)
  1174. nActualTimespan = nTargetTimespan/4;
  1175. if (nActualTimespan > nTargetTimespan*4)
  1176. nActualTimespan = nTargetTimespan*4;
  1177.  
  1178. // Retarget
  1179. CBigNum bnNew;
  1180. bnNew.SetCompact(pindexLast->nBits);
  1181. bnNew *= nActualTimespan;
  1182. bnNew /= nTargetTimespan;
  1183.  
  1184. if (bnNew > bnProofOfWorkLimit)
  1185. bnNew = bnProofOfWorkLimit;
  1186.  
  1187. /// debug print
  1188. printf("GetNextWorkRequired RETARGET\n");
  1189. printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
  1190. printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
  1191. printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
  1192.  
  1193. return bnNew.GetCompact();
  1194. }
  1195.  
  1196. bool CheckProofOfWork(uint256 hash, unsigned int nBits)
  1197. {
  1198. CBigNum bnTarget;
  1199. bnTarget.SetCompact(nBits);
  1200.  
  1201. // Check range
  1202. if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
  1203. return error("CheckProofOfWork() : nBits below minimum work");
  1204.  
  1205. // Check proof of work matches claimed amount
  1206. if (hash > bnTarget.getuint256())
  1207. return error("CheckProofOfWork() : hash doesn't match nBits");
  1208.  
  1209. return true;
  1210. }
  1211.  
  1212. // Return maximum amount of blocks that other nodes claim to have
  1213. int GetNumBlocksOfPeers()
  1214. {
  1215. return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
  1216. }
  1217.  
  1218. bool IsInitialBlockDownload()
  1219. {
  1220. if (pindexBest == NULL || fImporting || fReindex || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
  1221. return true;
  1222. static int64 nLastUpdate;
  1223. static CBlockIndex* pindexLastBest;
  1224. if (pindexBest != pindexLastBest)
  1225. {
  1226. pindexLastBest = pindexBest;
  1227. nLastUpdate = GetTime();
  1228. }
  1229. return (GetTime() - nLastUpdate < 10 &&
  1230. pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
  1231. }
  1232.  
  1233. void static InvalidChainFound(CBlockIndex* pindexNew)
  1234. {
  1235. if (pindexNew->nChainWork > nBestInvalidWork)
  1236. {
  1237. nBestInvalidWork = pindexNew->nChainWork;
  1238. pblocktree->WriteBestInvalidWork(CBigNum(nBestInvalidWork));
  1239. uiInterface.NotifyBlocksChanged();
  1240. }
  1241. printf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
  1242. pindexNew->GetBlockHash().ToString().c_str(), pindexNew->nHeight,
  1243. log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
  1244. pindexNew->GetBlockTime()).c_str());
  1245. printf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
  1246. hashBestChain.ToString().c_str(), nBestHeight, log(nBestChainWork.getdouble())/log(2.0),
  1247. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
  1248. if (pindexBest && nBestInvalidWork > nBestChainWork + (pindexBest->GetBlockWork() * 6).getuint256())
  1249. printf("InvalidChainFound: Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
  1250. }
  1251.  
  1252. void static InvalidBlockFound(CBlockIndex *pindex) {
  1253. pindex->nStatus |= BLOCK_FAILED_VALID;
  1254. pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex));
  1255. setBlockIndexValid.erase(pindex);
  1256. InvalidChainFound(pindex);
  1257. if (pindex->pnext) {
  1258. CValidationState stateDummy;
  1259. ConnectBestBlock(stateDummy); // reorganise away from the failed block
  1260. }
  1261. }
  1262.  
  1263. bool ConnectBestBlock(CValidationState &state) {
  1264. do {
  1265. CBlockIndex *pindexNewBest;
  1266.  
  1267. {
  1268. std::set<CBlockIndex*,CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexValid.rbegin();
  1269. if (it == setBlockIndexValid.rend())
  1270. return true;
  1271. pindexNewBest = *it;
  1272. }
  1273.  
  1274. if (pindexNewBest == pindexBest || (pindexBest && pindexNewBest->nChainWork == pindexBest->nChainWork))
  1275. return true; // nothing to do
  1276.  
  1277. // check ancestry
  1278. CBlockIndex *pindexTest = pindexNewBest;
  1279. std::vector<CBlockIndex*> vAttach;
  1280. do {
  1281. if (pindexTest->nStatus & BLOCK_FAILED_MASK) {
  1282. // mark descendants failed
  1283. CBlockIndex *pindexFailed = pindexNewBest;
  1284. while (pindexTest != pindexFailed) {
  1285. pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
  1286. setBlockIndexValid.erase(pindexFailed);
  1287. pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexFailed));
  1288. pindexFailed = pindexFailed->pprev;
  1289. }
  1290. InvalidChainFound(pindexNewBest);
  1291. break;
  1292. }
  1293.  
  1294. if (pindexBest == NULL || pindexTest->nChainWork > pindexBest->nChainWork)
  1295. vAttach.push_back(pindexTest);
  1296.  
  1297. if (pindexTest->pprev == NULL || pindexTest->pnext != NULL) {
  1298. reverse(vAttach.begin(), vAttach.end());
  1299. BOOST_FOREACH(CBlockIndex *pindexSwitch, vAttach) {
  1300. boost::this_thread::interruption_point();
  1301. try {
  1302. if (!SetBestChain(state, pindexSwitch))
  1303. return false;
  1304. } catch(std::runtime_error &e) {
  1305. return state.Abort(_("System error: ") + e.what());
  1306. }
  1307. }
  1308. return true;
  1309. }
  1310. pindexTest = pindexTest->pprev;
  1311. } while(true);
  1312. } while(true);
  1313. }
  1314.  
  1315. void CBlockHeader::UpdateTime(const CBlockIndex* pindexPrev)
  1316. {
  1317. nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
  1318.  
  1319. // Updating time can change work required on testnet:
  1320. if (fTestNet)
  1321. nBits = GetNextWorkRequired(pindexPrev, this);
  1322. }
  1323.  
  1324.  
  1325.  
  1326.  
  1327.  
  1328.  
  1329.  
  1330.  
  1331.  
  1332.  
  1333.  
  1334. const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view)
  1335. {
  1336. const CCoins &coins = view.GetCoins(input.prevout.hash);
  1337. assert(coins.IsAvailable(input.prevout.n));
  1338. return coins.vout[input.prevout.n];
  1339. }
  1340.  
  1341. int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const
  1342. {
  1343. if (IsCoinBase())
  1344. return 0;
  1345.  
  1346. int64 nResult = 0;
  1347. for (unsigned int i = 0; i < vin.size(); i++)
  1348. nResult += GetOutputFor(vin[i], inputs).nValue;
  1349.  
  1350. return nResult;
  1351. }
  1352.  
  1353. unsigned int CTransaction::GetP2SHSigOpCount(CCoinsViewCache& inputs) const
  1354. {
  1355. if (IsCoinBase())
  1356. return 0;
  1357.  
  1358. unsigned int nSigOps = 0;
  1359. for (unsigned int i = 0; i < vin.size(); i++)
  1360. {
  1361. const CTxOut &prevout = GetOutputFor(vin[i], inputs);
  1362. if (prevout.scriptPubKey.IsPayToScriptHash())
  1363. nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
  1364. }
  1365. return nSigOps;
  1366. }
  1367.  
  1368. void CTransaction::UpdateCoins(CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash) const
  1369. {
  1370. bool ret;
  1371. // mark inputs spent
  1372. if (!IsCoinBase()) {
  1373. BOOST_FOREACH(const CTxIn &txin, vin) {
  1374. CCoins &coins = inputs.GetCoins(txin.prevout.hash);
  1375. CTxInUndo undo;
  1376. ret = coins.Spend(txin.prevout, undo);
  1377. assert(ret);
  1378. txundo.vprevout.push_back(undo);
  1379. }
  1380. }
  1381.  
  1382. // add outputs
  1383. assert(inputs.SetCoins(txhash, CCoins(*this, nHeight)));
  1384. }
  1385.  
  1386. bool CTransaction::HaveInputs(CCoinsViewCache &inputs) const
  1387. {
  1388. if (!IsCoinBase()) {
  1389. // first check whether information about the prevout hash is available
  1390. for (unsigned int i = 0; i < vin.size(); i++) {
  1391. const COutPoint &prevout = vin[i].prevout;
  1392. if (!inputs.HaveCoins(prevout.hash))
  1393. return false;
  1394. }
  1395.  
  1396. // then check whether the actual outputs are available
  1397. for (unsigned int i = 0; i < vin.size(); i++) {
  1398. const COutPoint &prevout = vin[i].prevout;
  1399. const CCoins &coins = inputs.GetCoins(prevout.hash);
  1400. if (!coins.IsAvailable(prevout.n))
  1401. return false;
  1402. }
  1403. }
  1404. return true;
  1405. }
  1406.  
  1407. bool CScriptCheck::operator()() const {
  1408. const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
  1409. if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
  1410. return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().c_str());
  1411. return true;
  1412. }
  1413.  
  1414. bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
  1415. {
  1416. return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
  1417. }
  1418.  
  1419. bool CTransaction::CheckInputs(CValidationState &state, CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks) const
  1420. {
  1421. if (!IsCoinBase())
  1422. {
  1423. if (pvChecks)
  1424. pvChecks->reserve(vin.size());
  1425.  
  1426. // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
  1427. // for an attacker to attempt to split the network.
  1428. if (!HaveInputs(inputs))
  1429. return state.Invalid(error("CheckInputs() : %s inputs unavailable", GetHash().ToString().c_str()));
  1430.  
  1431. // While checking, GetBestBlock() refers to the parent block.
  1432. // This is also true for mempool checks.
  1433. int nSpendHeight = inputs.GetBestBlock()->nHeight + 1;
  1434. int64 nValueIn = 0;
  1435. int64 nFees = 0;
  1436. for (unsigned int i = 0; i < vin.size(); i++)
  1437. {
  1438. const COutPoint &prevout = vin[i].prevout;
  1439. const CCoins &coins = inputs.GetCoins(prevout.hash);
  1440.  
  1441. // If prev is coinbase, check that it's matured
  1442. if (coins.IsCoinBase()) {
  1443. if (nSpendHeight - coins.nHeight < COINBASE_MATURITY)
  1444. return state.Invalid(error("CheckInputs() : tried to spend coinbase at depth %d", nSpendHeight - coins.nHeight));
  1445. }
  1446.  
  1447. // Check for negative or overflow input values
  1448. nValueIn += coins.vout[prevout.n].nValue;
  1449. if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
  1450. return state.DoS(100, error("CheckInputs() : txin values out of range"));
  1451.  
  1452. }
  1453.  
  1454. if (nValueIn < GetValueOut())
  1455. return state.DoS(100, error("CheckInputs() : %s value in < value out", GetHash().ToString().c_str()));
  1456.  
  1457. // Tally transaction fees
  1458. int64 nTxFee = nValueIn - GetValueOut();
  1459. if (nTxFee < 0)
  1460. return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().c_str()));
  1461. nFees += nTxFee;
  1462. if (!MoneyRange(nFees))
  1463. return state.DoS(100, error("CheckInputs() : nFees out of range"));
  1464.  
  1465. // The first loop above does all the inexpensive checks.
  1466. // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
  1467. // Helps prevent CPU exhaustion attacks.
  1468.  
  1469. // Skip ECDSA signature verification when connecting blocks
  1470. // before the last block chain checkpoint. This is safe because block merkle hashes are
  1471. // still computed and checked, and any change will be caught at the next checkpoint.
  1472. if (fScriptChecks) {
  1473. for (unsigned int i = 0; i < vin.size(); i++) {
  1474. const COutPoint &prevout = vin[i].prevout;
  1475. const CCoins &coins = inputs.GetCoins(prevout.hash);
  1476.  
  1477. // Verify signature
  1478. CScriptCheck check(coins, *this, i, flags, 0);
  1479. if (pvChecks) {
  1480. pvChecks->push_back(CScriptCheck());
  1481. check.swap(pvChecks->back());
  1482. } else if (!check()) {
  1483. if (flags & SCRIPT_VERIFY_STRICTENC) {
  1484. // For now, check whether the failure was caused by non-canonical
  1485. // encodings or not; if so, don't trigger DoS protection.
  1486. CScriptCheck check(coins, *this, i, flags & (~SCRIPT_VERIFY_STRICTENC), 0);
  1487. if (check())
  1488. return state.Invalid();
  1489. }
  1490. return state.DoS(100,false);
  1491. }
  1492. }
  1493. }
  1494. }
  1495.  
  1496. return true;
  1497. }
  1498.  
  1499.  
  1500.  
  1501.  
  1502. bool CBlock::DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &view, bool *pfClean)
  1503. {
  1504. assert(pindex == view.GetBestBlock());
  1505.  
  1506. if (pfClean)
  1507. *pfClean = false;
  1508.  
  1509. bool fClean = true;
  1510.  
  1511. CBlockUndo blockUndo;
  1512. CDiskBlockPos pos = pindex->GetUndoPos();
  1513. if (pos.IsNull())
  1514. return error("DisconnectBlock() : no undo data available");
  1515. if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
  1516. return error("DisconnectBlock() : failure reading undo data");
  1517.  
  1518. if (blockUndo.vtxundo.size() + 1 != vtx.size())
  1519. return error("DisconnectBlock() : block and undo data inconsistent");
  1520.  
  1521. // undo transactions in reverse order
  1522. for (int i = vtx.size() - 1; i >= 0; i--) {
  1523. const CTransaction &tx = vtx[i];
  1524. uint256 hash = tx.GetHash();
  1525.  
  1526. // check that all outputs are available
  1527. if (!view.HaveCoins(hash)) {
  1528. fClean = fClean && error("DisconnectBlock() : outputs still spent? database corrupted");
  1529. view.SetCoins(hash, CCoins());
  1530. }
  1531. CCoins &outs = view.GetCoins(hash);
  1532.  
  1533. CCoins outsBlock = CCoins(tx, pindex->nHeight);
  1534. // The CCoins serialization does not serialize negative numbers.
  1535. // No network rules currently depend on the version here, so an inconsistency is harmless
  1536. // but it must be corrected before txout nversion ever influences a network rule.
  1537. if (outsBlock.nVersion < 0)
  1538. outs.nVersion = outsBlock.nVersion;
  1539. if (outs != outsBlock)
  1540. fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
  1541.  
  1542. // remove outputs
  1543. outs = CCoins();
  1544.  
  1545. // restore inputs
  1546. if (i > 0) { // not coinbases
  1547. const CTxUndo &txundo = blockUndo.vtxundo[i-1];
  1548. if (txundo.vprevout.size() != tx.vin.size())
  1549. return error("DisconnectBlock() : transaction and undo data inconsistent");
  1550. for (unsigned int j = tx.vin.size(); j-- > 0;) {
  1551. const COutPoint &out = tx.vin[j].prevout;
  1552. const CTxInUndo &undo = txundo.vprevout[j];
  1553. CCoins coins;
  1554. view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
  1555. if (undo.nHeight != 0) {
  1556. // undo data contains height: this is the last output of the prevout tx being spent
  1557. if (!coins.IsPruned())
  1558. fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
  1559. coins = CCoins();
  1560. coins.fCoinBase = undo.fCoinBase;
  1561. coins.nHeight = undo.nHeight;
  1562. coins.nVersion = undo.nVersion;
  1563. } else {
  1564. if (coins.IsPruned())
  1565. fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
  1566. }
  1567. if (coins.IsAvailable(out.n))
  1568. fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
  1569. if (coins.vout.size() < out.n+1)
  1570. coins.vout.resize(out.n+1);
  1571. coins.vout[out.n] = undo.txout;
  1572. if (!view.SetCoins(out.hash, coins))
  1573. return error("DisconnectBlock() : cannot restore coin inputs");
  1574. }
  1575. }
  1576. }
  1577.  
  1578. // move best block pointer to prevout block
  1579. view.SetBestBlock(pindex->pprev);
  1580.  
  1581. if (pfClean) {
  1582. *pfClean = fClean;
  1583. return true;
  1584. } else {
  1585. return fClean;
  1586. }
  1587. }
  1588.  
  1589. void static FlushBlockFile(bool fFinalize = false)
  1590. {
  1591. LOCK(cs_LastBlockFile);
  1592.  
  1593. CDiskBlockPos posOld(nLastBlockFile, 0);
  1594.  
  1595. FILE *fileOld = OpenBlockFile(posOld);
  1596. if (fileOld) {
  1597. if (fFinalize)
  1598. TruncateFile(fileOld, infoLastBlockFile.nSize);
  1599. FileCommit(fileOld);
  1600. fclose(fileOld);
  1601. }
  1602.  
  1603. fileOld = OpenUndoFile(posOld);
  1604. if (fileOld) {
  1605. if (fFinalize)
  1606. TruncateFile(fileOld, infoLastBlockFile.nUndoSize);
  1607. FileCommit(fileOld);
  1608. fclose(fileOld);
  1609. }
  1610. }
  1611.  
  1612. bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
  1613.  
  1614. static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
  1615.  
  1616. void ThreadScriptCheck() {
  1617. RenameThread("bitcoin-scriptch");
  1618. scriptcheckqueue.Thread();
  1619. }
  1620.  
  1621. bool CBlock::ConnectBlock(CValidationState &state, CBlockIndex* pindex, CCoinsViewCache &view, bool fJustCheck)
  1622. {
  1623. // Check it again in case a previous version let a bad block in
  1624. if (!CheckBlock(state, !fJustCheck, !fJustCheck))
  1625. return false;
  1626.  
  1627. // verify that the view's current state corresponds to the previous block
  1628. assert(pindex->pprev == view.GetBestBlock());
  1629.  
  1630. // Special case for the genesis block, skipping connection of its transactions
  1631. // (its coinbase is unspendable)
  1632. if (GetHash() == hashGenesisBlock) {
  1633. view.SetBestBlock(pindex);
  1634. pindexGenesisBlock = pindex;
  1635. return true;
  1636. }
  1637.  
  1638. bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
  1639.  
  1640. // Do not allow blocks that contain transactions which 'overwrite' older transactions,
  1641. // unless those are already completely spent.
  1642. // If such overwrites are allowed, coinbases and transactions depending upon those
  1643. // can be duplicated to remove the ability to spend the first instance -- even after
  1644. // being sent to another address.
  1645. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
  1646. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
  1647. // already refuses previously-known transaction ids entirely.
  1648. // This rule was originally applied all blocks whose timestamp was after October 1, 2012, 0:00 UTC.
  1649. // Now that the whole chain is irreversibly beyond that time it is applied to all blocks,
  1650. // this prevents exploiting the issue against nodes in their initial block download.
  1651. bool fEnforceBIP30 = true;
  1652.  
  1653. if (fEnforceBIP30) {
  1654. for (unsigned int i=0; i<vtx.size(); i++) {
  1655. uint256 hash = GetTxHash(i);
  1656. if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
  1657. return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"));
  1658. }
  1659. }
  1660.  
  1661. // BIP16 didn't become active until Oct 1 2012
  1662. int64 nBIP16SwitchTime = 1349049600;
  1663. bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
  1664.  
  1665. unsigned int flags = SCRIPT_VERIFY_NOCACHE |
  1666. (fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE);
  1667.  
  1668. CBlockUndo blockundo;
  1669.  
  1670. CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
  1671.  
  1672. int64 nStart = GetTimeMicros();
  1673. int64 nFees = 0;
  1674. int nInputs = 0;
  1675. unsigned int nSigOps = 0;
  1676. CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(vtx.size()));
  1677. std::vector<std::pair<uint256, CDiskTxPos> > vPos;
  1678. vPos.reserve(vtx.size());
  1679. for (unsigned int i=0; i<vtx.size(); i++)
  1680. {
  1681. const CTransaction &tx = vtx[i];
  1682.  
  1683. nInputs += tx.vin.size();
  1684. nSigOps += tx.GetLegacySigOpCount();
  1685. if (nSigOps > MAX_BLOCK_SIGOPS)
  1686. return state.DoS(100, error("ConnectBlock() : too many sigops"));
  1687.  
  1688. if (!tx.IsCoinBase())
  1689. {
  1690. if (!tx.HaveInputs(view))
  1691. return state.DoS(100, error("ConnectBlock() : inputs missing/spent"));
  1692.  
  1693. if (fStrictPayToScriptHash)
  1694. {
  1695. // Add in sigops done by pay-to-script-hash inputs;
  1696. // this is to prevent a "rogue miner" from creating
  1697. // an incredibly-expensive-to-validate block.
  1698. nSigOps += tx.GetP2SHSigOpCount(view);
  1699. if (nSigOps > MAX_BLOCK_SIGOPS)
  1700. return state.DoS(100, error("ConnectBlock() : too many sigops"));
  1701. }
  1702.  
  1703. nFees += tx.GetValueIn(view)-tx.GetValueOut();
  1704.  
  1705. std::vector<CScriptCheck> vChecks;
  1706. if (!tx.CheckInputs(state, view, fScriptChecks, flags, nScriptCheckThreads ? &vChecks : NULL))
  1707. return false;
  1708. control.Add(vChecks);
  1709. }
  1710.  
  1711. CTxUndo txundo;
  1712. tx.UpdateCoins(state, view, txundo, pindex->nHeight, GetTxHash(i));
  1713. if (!tx.IsCoinBase())
  1714. blockundo.vtxundo.push_back(txundo);
  1715.  
  1716. vPos.push_back(std::make_pair(GetTxHash(i), pos));
  1717. pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
  1718. }
  1719. int64 nTime = GetTimeMicros() - nStart;
  1720. if (fBenchmark)
  1721. printf("- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (unsigned)vtx.size(), 0.001 * nTime, 0.001 * nTime / vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
  1722.  
  1723. if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
  1724. return state.DoS(100, error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)));
  1725.  
  1726. if (!control.Wait())
  1727. return state.DoS(100, false);
  1728. int64 nTime2 = GetTimeMicros() - nStart;
  1729. if (fBenchmark)
  1730. printf("- Verify %u txins: %.2fms (%.3fms/txin)\n", nInputs - 1, 0.001 * nTime2, nInputs <= 1 ? 0 : 0.001 * nTime2 / (nInputs-1));
  1731.  
  1732. if (fJustCheck)
  1733. return true;
  1734.  
  1735. // Write undo information to disk
  1736. if (pindex->GetUndoPos().IsNull() || (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS)
  1737. {
  1738. if (pindex->GetUndoPos().IsNull()) {
  1739. CDiskBlockPos pos;
  1740. if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
  1741. return error("ConnectBlock() : FindUndoPos failed");
  1742. if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
  1743. return state.Abort(_("Failed to write undo data"));
  1744.  
  1745. // update nUndoPos in block index
  1746. pindex->nUndoPos = pos.nPos;
  1747. pindex->nStatus |= BLOCK_HAVE_UNDO;
  1748. }
  1749.  
  1750. pindex->nStatus = (pindex->nStatus & ~BLOCK_VALID_MASK) | BLOCK_VALID_SCRIPTS;
  1751.  
  1752. CDiskBlockIndex blockindex(pindex);
  1753. if (!pblocktree->WriteBlockIndex(blockindex))
  1754. return state.Abort(_("Failed to write block index"));
  1755. }
  1756.  
  1757. if (fTxIndex)
  1758. if (!pblocktree->WriteTxIndex(vPos))
  1759. return state.Abort(_("Failed to write transaction index"));
  1760.  
  1761. // add this block to the view's block chain
  1762. assert(view.SetBestBlock(pindex));
  1763.  
  1764. // Watch for transactions paying to me
  1765. for (unsigned int i=0; i<vtx.size(); i++)
  1766. SyncWithWallets(GetTxHash(i), vtx[i], this, true);
  1767.  
  1768. return true;
  1769. }
  1770.  
  1771. bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
  1772. {
  1773. // All modifications to the coin state will be done in this cache.
  1774. // Only when all have succeeded, we push it to pcoinsTip.
  1775. CCoinsViewCache view(*pcoinsTip, true);
  1776.  
  1777. // Find the fork (typically, there is none)
  1778. CBlockIndex* pfork = view.GetBestBlock();
  1779. CBlockIndex* plonger = pindexNew;
  1780. while (pfork && pfork != plonger)
  1781. {
  1782. while (plonger->nHeight > pfork->nHeight) {
  1783. plonger = plonger->pprev;
  1784. assert(plonger != NULL);
  1785. }
  1786. if (pfork == plonger)
  1787. break;
  1788. pfork = pfork->pprev;
  1789. assert(pfork != NULL);
  1790. }
  1791.  
  1792. // List of what to disconnect (typically nothing)
  1793. vector<CBlockIndex*> vDisconnect;
  1794. for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
  1795. vDisconnect.push_back(pindex);
  1796.  
  1797. // List of what to connect (typically only pindexNew)
  1798. vector<CBlockIndex*> vConnect;
  1799. for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
  1800. vConnect.push_back(pindex);
  1801. reverse(vConnect.begin(), vConnect.end());
  1802.  
  1803. if (vDisconnect.size() > 0) {
  1804. printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..\n", vDisconnect.size(), pfork->GetBlockHash().ToString().c_str());
  1805. printf("REORGANIZE: Connect %"PRIszu" blocks; ..%s\n", vConnect.size(), pindexNew->GetBlockHash().ToString().c_str());
  1806. }
  1807.  
  1808. // Disconnect shorter branch
  1809. vector<CTransaction> vResurrect;
  1810. BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
  1811. CBlock block;
  1812. if (!block.ReadFromDisk(pindex))
  1813. return state.Abort(_("Failed to read block"));
  1814. int64 nStart = GetTimeMicros();
  1815. if (!block.DisconnectBlock(state, pindex, view))
  1816. return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
  1817. if (fBenchmark)
  1818. printf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
  1819.  
  1820. // Queue memory transactions to resurrect.
  1821. // We only do this for blocks after the last checkpoint (reorganisation before that
  1822. // point should only happen with -reindex/-loadblock, or a misbehaving peer.
  1823. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  1824. if (!tx.IsCoinBase() && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
  1825. vResurrect.push_back(tx);
  1826. }
  1827.  
  1828. // Connect longer branch
  1829. vector<CTransaction> vDelete;
  1830. BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
  1831. CBlock block;
  1832. if (!block.ReadFromDisk(pindex))
  1833. return state.Abort(_("Failed to read block"));
  1834. int64 nStart = GetTimeMicros();
  1835. if (!block.ConnectBlock(state, pindex, view)) {
  1836. if (state.IsInvalid()) {
  1837. InvalidChainFound(pindexNew);
  1838. InvalidBlockFound(pindex);
  1839. }
  1840. return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
  1841. }
  1842. if (fBenchmark)
  1843. printf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
  1844.  
  1845. // Queue memory transactions to delete
  1846. BOOST_FOREACH(const CTransaction& tx, block.vtx)
  1847. vDelete.push_back(tx);
  1848. }
  1849.  
  1850. // Flush changes to global coin state
  1851. int64 nStart = GetTimeMicros();
  1852. int nModified = view.GetCacheSize();
  1853. assert(view.Flush());
  1854. int64 nTime = GetTimeMicros() - nStart;
  1855. if (fBenchmark)
  1856. printf("- Flush %i transactions: %.2fms (%.4fms/tx)\n", nModified, 0.001 * nTime, 0.001 * nTime / nModified);
  1857.  
  1858. // Make sure it's successfully written to disk before changing memory structure
  1859. bool fIsInitialDownload = IsInitialBlockDownload();
  1860. if (!fIsInitialDownload || pcoinsTip->GetCacheSize() > nCoinCacheSize) {
  1861. // Typical CCoins structures on disk are around 100 bytes in size.
  1862. // Pushing a new one to the database can cause it to be written
  1863. // twice (once in the log, and once in the tables). This is already
  1864. // an overestimation, as most will delete an existing entry or
  1865. // overwrite one. Still, use a conservative safety factor of 2.
  1866. if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
  1867. return state.Error();
  1868. FlushBlockFile();
  1869. pblocktree->Sync();
  1870. if (!pcoinsTip->Flush())
  1871. return state.Abort(_("Failed to write to coin database"));
  1872. }
  1873.  
  1874. // At this point, all changes have been done to the database.
  1875. // Proceed by updating the memory structures.
  1876.  
  1877. // Disconnect shorter branch
  1878. BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
  1879. if (pindex->pprev)
  1880. pindex->pprev->pnext = NULL;
  1881.  
  1882. // Connect longer branch
  1883. BOOST_FOREACH(CBlockIndex* pindex, vConnect)
  1884. if (pindex->pprev)
  1885. pindex->pprev->pnext = pindex;
  1886.  
  1887. // Resurrect memory transactions that were in the disconnected branch
  1888. BOOST_FOREACH(CTransaction& tx, vResurrect) {
  1889. // ignore validation errors in resurrected transactions
  1890. CValidationState stateDummy;
  1891. if (!tx.AcceptToMemoryPool(stateDummy, true, false))
  1892. mempool.remove(tx, true);
  1893. }
  1894.  
  1895. // Delete redundant memory transactions that are in the connected branch
  1896. BOOST_FOREACH(CTransaction& tx, vDelete) {
  1897. mempool.remove(tx);
  1898. mempool.removeConflicts(tx);
  1899. }
  1900.  
  1901. // Update best block in wallet (so we can detect restored wallets)
  1902. if ((pindexNew->nHeight % 20160) == 0 || (!fIsInitialDownload && (pindexNew->nHeight % 144) == 0))
  1903. {
  1904. const CBlockLocator locator(pindexNew);
  1905. ::SetBestChain(locator);
  1906. }
  1907.  
  1908. // New best block
  1909. hashBestChain = pindexNew->GetBlockHash();
  1910. pindexBest = pindexNew;
  1911. pblockindexFBBHLast = NULL;
  1912. nBestHeight = pindexBest->nHeight;
  1913. nBestChainWork = pindexNew->nChainWork;
  1914. nTimeBestReceived = GetTime();
  1915. nTransactionsUpdated++;
  1916. printf("SetBestChain: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n",
  1917. hashBestChain.ToString().c_str(), nBestHeight, log(nBestChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
  1918. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str(),
  1919. Checkpoints::GuessVerificationProgress(pindexBest));
  1920.  
  1921. // Check the version of the last 100 blocks to see if we need to upgrade:
  1922. if (!fIsInitialDownload)
  1923. {
  1924. int nUpgraded = 0;
  1925. const CBlockIndex* pindex = pindexBest;
  1926. for (int i = 0; i < 100 && pindex != NULL; i++)
  1927. {
  1928. if (pindex->nVersion > CBlock::CURRENT_VERSION)
  1929. ++nUpgraded;
  1930. pindex = pindex->pprev;
  1931. }
  1932. if (nUpgraded > 0)
  1933. printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
  1934. if (nUpgraded > 100/2)
  1935. // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
  1936. strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
  1937. }
  1938.  
  1939. std::string strCmd = GetArg("-blocknotify", "");
  1940.  
  1941. if (!fIsInitialDownload && !strCmd.empty())
  1942. {
  1943. boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
  1944. boost::thread t(runCommand, strCmd); // thread runs free
  1945. }
  1946.  
  1947. return true;
  1948. }
  1949.  
  1950.  
  1951. bool CBlock::AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos)
  1952. {
  1953. // Check for duplicate
  1954. uint256 hash = GetHash();
  1955. if (mapBlockIndex.count(hash))
  1956. return state.Invalid(error("AddToBlockIndex() : %s already exists", hash.ToString().c_str()));
  1957.  
  1958. // Construct new block index object
  1959. CBlockIndex* pindexNew = new CBlockIndex(*this);
  1960. assert(pindexNew);
  1961. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  1962. pindexNew->phashBlock = &((*mi).first);
  1963. map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
  1964. if (miPrev != mapBlockIndex.end())
  1965. {
  1966. pindexNew->pprev = (*miPrev).second;
  1967. pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
  1968. }
  1969. pindexNew->nTx = vtx.size();
  1970. pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + pindexNew->GetBlockWork().getuint256();
  1971. pindexNew->nChainTx = (pindexNew->pprev ? pindexNew->pprev->nChainTx : 0) + pindexNew->nTx;
  1972. pindexNew->nFile = pos.nFile;
  1973. pindexNew->nDataPos = pos.nPos;
  1974. pindexNew->nUndoPos = 0;
  1975. pindexNew->nStatus = BLOCK_VALID_TRANSACTIONS | BLOCK_HAVE_DATA;
  1976. setBlockIndexValid.insert(pindexNew);
  1977.  
  1978. if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindexNew)))
  1979. return state.Abort(_("Failed to write block index"));
  1980.  
  1981. // New best?
  1982. if (!ConnectBestBlock(state))
  1983. return false;
  1984.  
  1985. if (pindexNew == pindexBest)
  1986. {
  1987. // Notify UI to display prev block's coinbase if it was ours
  1988. static uint256 hashPrevBestCoinBase;
  1989. UpdatedTransaction(hashPrevBestCoinBase);
  1990. hashPrevBestCoinBase = GetTxHash(0);
  1991. }
  1992.  
  1993. if (!pblocktree->Flush())
  1994. return state.Abort(_("Failed to sync block index"));
  1995.  
  1996. uiInterface.NotifyBlocksChanged();
  1997. return true;
  1998. }
  1999.  
  2000.  
  2001. bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime, bool fKnown = false)
  2002. {
  2003. bool fUpdatedLast = false;
  2004.  
  2005. LOCK(cs_LastBlockFile);
  2006.  
  2007. if (fKnown) {
  2008. if (nLastBlockFile != pos.nFile) {
  2009. nLastBlockFile = pos.nFile;
  2010. infoLastBlockFile.SetNull();
  2011. pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile);
  2012. fUpdatedLast = true;
  2013. }
  2014. } else {
  2015. while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
  2016. printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
  2017. FlushBlockFile(true);
  2018. nLastBlockFile++;
  2019. infoLastBlockFile.SetNull();
  2020. pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
  2021. fUpdatedLast = true;
  2022. }
  2023. pos.nFile = nLastBlockFile;
  2024. pos.nPos = infoLastBlockFile.nSize;
  2025. }
  2026.  
  2027. infoLastBlockFile.nSize += nAddSize;
  2028. infoLastBlockFile.AddBlock(nHeight, nTime);
  2029.  
  2030. if (!fKnown) {
  2031. unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
  2032. unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
  2033. if (nNewChunks > nOldChunks) {
  2034. if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
  2035. FILE *file = OpenBlockFile(pos);
  2036. if (file) {
  2037. printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
  2038. AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
  2039. fclose(file);
  2040. }
  2041. }
  2042. else
  2043. return state.Error();
  2044. }
  2045. }
  2046.  
  2047. if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
  2048. return state.Abort(_("Failed to write file info"));
  2049. if (fUpdatedLast)
  2050. pblocktree->WriteLastBlockFile(nLastBlockFile);
  2051.  
  2052. return true;
  2053. }
  2054.  
  2055. bool FindUndoPos(CValidationState &state, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
  2056. {
  2057. pos.nFile = nFile;
  2058.  
  2059. LOCK(cs_LastBlockFile);
  2060.  
  2061. unsigned int nNewSize;
  2062. if (nFile == nLastBlockFile) {
  2063. pos.nPos = infoLastBlockFile.nUndoSize;
  2064. nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
  2065. if (!pblocktree->WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
  2066. return state.Abort(_("Failed to write block info"));
  2067. } else {
  2068. CBlockFileInfo info;
  2069. if (!pblocktree->ReadBlockFileInfo(nFile, info))
  2070. return state.Abort(_("Failed to read block info"));
  2071. pos.nPos = info.nUndoSize;
  2072. nNewSize = (info.nUndoSize += nAddSize);
  2073. if (!pblocktree->WriteBlockFileInfo(nFile, info))
  2074. return state.Abort(_("Failed to write block info"));
  2075. }
  2076.  
  2077. unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
  2078. unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
  2079. if (nNewChunks > nOldChunks) {
  2080. if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
  2081. FILE *file = OpenUndoFile(pos);
  2082. if (file) {
  2083. printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
  2084. AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
  2085. fclose(file);
  2086. }
  2087. }
  2088. else
  2089. return state.Error();
  2090. }
  2091.  
  2092. return true;
  2093. }
  2094.  
  2095.  
  2096. bool CBlock::CheckBlock(CValidationState &state, bool fCheckPOW, bool fCheckMerkleRoot) const
  2097. {
  2098. // These are checks that are independent of context
  2099. // that can be verified before saving an orphan block.
  2100.  
  2101. // Size limits
  2102. if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
  2103. return state.DoS(100, error("CheckBlock() : size limits failed"));
  2104.  
  2105. // Shibacoin: Special short-term limits to avoid 10,000 BDB lock limit:
  2106. if (GetBlockTime() < 1376568000) // stop enforcing 15 August 2013 00:00:00
  2107. {
  2108. // Rule is: #unique txids referenced <= 4,500
  2109. // ... to prevent 10,000 BDB lock exhaustion on old clients
  2110. set<uint256> setTxIn;
  2111. for (size_t i = 0; i < vtx.size(); i++)
  2112. {
  2113. setTxIn.insert(vtx[i].GetHash());
  2114. if (i == 0) continue; // skip coinbase txin
  2115. BOOST_FOREACH(const CTxIn& txin, vtx[i].vin)
  2116. setTxIn.insert(txin.prevout.hash);
  2117. }
  2118. size_t nTxids = setTxIn.size();
  2119. if (nTxids > 4500)
  2120. return error("CheckBlock() : 15 August maxlocks violation");
  2121. }
  2122.  
  2123. // Check proof of work matches claimed amount
  2124. if (fCheckPOW && !CheckProofOfWork(GetPoWHash(), nBits))
  2125. return state.DoS(50, error("CheckBlock() : proof of work failed"));
  2126.  
  2127. // Check timestamp
  2128. if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
  2129. return state.Invalid(error("CheckBlock() : block timestamp too far in the future"));
  2130.  
  2131. // First transaction must be coinbase, the rest must not be
  2132. if (vtx.empty() || !vtx[0].IsCoinBase())
  2133. return state.DoS(100, error("CheckBlock() : first tx is not coinbase"));
  2134. for (unsigned int i = 1; i < vtx.size(); i++)
  2135. if (vtx[i].IsCoinBase())
  2136. return state.DoS(100, error("CheckBlock() : more than one coinbase"));
  2137.  
  2138. // Check transactions
  2139. BOOST_FOREACH(const CTransaction& tx, vtx)
  2140. if (!tx.CheckTransaction(state))
  2141. return error("CheckBlock() : CheckTransaction failed");
  2142.  
  2143. // Build the merkle tree already. We need it anyway later, and it makes the
  2144. // block cache the transaction hashes, which means they don't need to be
  2145. // recalculated many times during this block's validation.
  2146. BuildMerkleTree();
  2147.  
  2148. // Check for duplicate txids. This is caught by ConnectInputs(),
  2149. // but catching it earlier avoids a potential DoS attack:
  2150. set<uint256> uniqueTx;
  2151. for (unsigned int i=0; i<vtx.size(); i++) {
  2152. uniqueTx.insert(GetTxHash(i));
  2153. }
  2154. if (uniqueTx.size() != vtx.size())
  2155. return state.DoS(100, error("CheckBlock() : duplicate transaction"), true);
  2156.  
  2157. unsigned int nSigOps = 0;
  2158. BOOST_FOREACH(const CTransaction& tx, vtx)
  2159. {
  2160. nSigOps += tx.GetLegacySigOpCount();
  2161. }
  2162. if (nSigOps > MAX_BLOCK_SIGOPS)
  2163. return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
  2164.  
  2165. // Check merkle root
  2166. if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
  2167. return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
  2168.  
  2169. return true;
  2170. }
  2171.  
  2172. bool CBlock::AcceptBlock(CValidationState &state, CDiskBlockPos *dbp)
  2173. {
  2174. // Check for duplicate
  2175. uint256 hash = GetHash();
  2176. if (mapBlockIndex.count(hash))
  2177. return state.Invalid(error("AcceptBlock() : block already in mapBlockIndex"));
  2178.  
  2179. // Get prev block index
  2180. CBlockIndex* pindexPrev = NULL;
  2181. int nHeight = 0;
  2182. if (hash != hashGenesisBlock) {
  2183. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
  2184. if (mi == mapBlockIndex.end())
  2185. return state.DoS(10, error("AcceptBlock() : prev block not found"));
  2186. pindexPrev = (*mi).second;
  2187. nHeight = pindexPrev->nHeight+1;
  2188.  
  2189. // Check proof of work
  2190. if (nBits != GetNextWorkRequired(pindexPrev, this))
  2191. return state.DoS(100, error("AcceptBlock() : incorrect proof of work"));
  2192.  
  2193. // Check timestamp against prev
  2194. if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
  2195. return state.Invalid(error("AcceptBlock() : block's timestamp is too early"));
  2196.  
  2197. // Check that all transactions are finalized
  2198. BOOST_FOREACH(const CTransaction& tx, vtx)
  2199. if (!tx.IsFinal(nHeight, GetBlockTime()))
  2200. return state.DoS(10, error("AcceptBlock() : contains a non-final transaction"));
  2201.  
  2202. // Check that the block chain matches the known block chain up to a checkpoint
  2203. if (!Checkpoints::CheckBlock(nHeight, hash))
  2204. return state.DoS(100, error("AcceptBlock() : rejected by checkpoint lock-in at %d", nHeight));
  2205.  
  2206. // Don't accept any forks from the main chain prior to last checkpoint
  2207. CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
  2208. if (pcheckpoint && nHeight < pcheckpoint->nHeight)
  2209. return state.DoS(100, error("AcceptBlock() : forked chain older than last checkpoint (height %d)", nHeight));
  2210.  
  2211. // Reject block.nVersion=1 blocks (mainnet >= 710000, testnet >= 400000)
  2212. if (nVersion < 2)
  2213. {
  2214. if ((!fTestNet && nHeight >= 710000) ||
  2215. (fTestNet && nHeight >= 400000))
  2216. {
  2217. return state.Invalid(error("AcceptBlock() : rejected nVersion=1 block"));
  2218. }
  2219. }
  2220. // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height
  2221. if (nVersion >= 2)
  2222. {
  2223. if ((!fTestNet && nHeight >= 710000) ||
  2224. (fTestNet && nHeight >= 400000))
  2225. {
  2226. CScript expect = CScript() << nHeight;
  2227. if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
  2228. !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
  2229. return state.DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
  2230. }
  2231. }
  2232. }
  2233.  
  2234. // Write block to history file
  2235. try {
  2236. unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
  2237. CDiskBlockPos blockPos;
  2238. if (dbp != NULL)
  2239. blockPos = *dbp;
  2240. if (!FindBlockPos(state, blockPos, nBlockSize+8, nHeight, nTime, dbp != NULL))
  2241. return error("AcceptBlock() : FindBlockPos failed");
  2242. if (dbp == NULL)
  2243. if (!WriteToDisk(blockPos))
  2244. return state.Abort(_("Failed to write block"));
  2245. if (!AddToBlockIndex(state, blockPos))
  2246. return error("AcceptBlock() : AddToBlockIndex failed");
  2247. } catch(std::runtime_error &e) {
  2248. return state.Abort(_("System error: ") + e.what());
  2249. }
  2250.  
  2251. // Relay inventory, but don't relay old inventory during initial block download
  2252. int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
  2253. if (hashBestChain == hash)
  2254. {
  2255. LOCK(cs_vNodes);
  2256. BOOST_FOREACH(CNode* pnode, vNodes)
  2257. if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
  2258. pnode->PushInventory(CInv(MSG_BLOCK, hash));
  2259. }
  2260.  
  2261. return true;
  2262. }
  2263.  
  2264. bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
  2265. {
  2266. unsigned int nFound = 0;
  2267. for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
  2268. {
  2269. if (pstart->nVersion >= minVersion)
  2270. ++nFound;
  2271. pstart = pstart->pprev;
  2272. }
  2273. return (nFound >= nRequired);
  2274. }
  2275.  
  2276. bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp)
  2277. {
  2278. // Check for duplicate
  2279. uint256 hash = pblock->GetHash();
  2280. if (mapBlockIndex.count(hash))
  2281. return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().c_str()));
  2282. if (mapOrphanBlocks.count(hash))
  2283. return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", hash.ToString().c_str()));
  2284.  
  2285. // Preliminary checks
  2286. if (!pblock->CheckBlock(state))
  2287. return error("ProcessBlock() : CheckBlock FAILED");
  2288.  
  2289. CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
  2290. if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
  2291. {
  2292. // Extra checks to prevent "fill up memory by spamming with bogus blocks"
  2293. int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
  2294. if (deltaTime < 0)
  2295. {
  2296. return state.DoS(100, error("ProcessBlock() : block with timestamp before last checkpoint"));
  2297. }
  2298. CBigNum bnNewBlock;
  2299. bnNewBlock.SetCompact(pblock->nBits);
  2300. CBigNum bnRequired;
  2301. bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
  2302. if (bnNewBlock > bnRequired)
  2303. {
  2304. return state.DoS(100, error("ProcessBlock() : block with too little proof-of-work"));
  2305. }
  2306. }
  2307.  
  2308.  
  2309. // If we don't already have its previous block, shunt it off to holding area until we get it
  2310. if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
  2311. {
  2312. printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().c_str());
  2313.  
  2314. // Accept orphans as long as there is a node to request its parents from
  2315. if (pfrom) {
  2316. CBlock* pblock2 = new CBlock(*pblock);
  2317. mapOrphanBlocks.insert(make_pair(hash, pblock2));
  2318. mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
  2319.  
  2320. // Ask this guy to fill in what we're missing
  2321. pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
  2322. }
  2323. return true;
  2324. }
  2325.  
  2326. // Store to disk
  2327. if (!pblock->AcceptBlock(state, dbp))
  2328. return error("ProcessBlock() : AcceptBlock FAILED");
  2329.  
  2330. // Recursively process any orphan blocks that depended on this one
  2331. vector<uint256> vWorkQueue;
  2332. vWorkQueue.push_back(hash);
  2333. for (unsigned int i = 0; i < vWorkQueue.size(); i++)
  2334. {
  2335. uint256 hashPrev = vWorkQueue[i];
  2336. for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
  2337. mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
  2338. ++mi)
  2339. {
  2340. CBlock* pblockOrphan = (*mi).second;
  2341. // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan resolution (that is, feeding people an invalid block based on LegitBlockX in order to get anyone relaying LegitBlockX banned)
  2342. CValidationState stateDummy;
  2343. if (pblockOrphan->AcceptBlock(stateDummy))
  2344. vWorkQueue.push_back(pblockOrphan->GetHash());
  2345. mapOrphanBlocks.erase(pblockOrphan->GetHash());
  2346. delete pblockOrphan;
  2347. }
  2348. mapOrphanBlocksByPrev.erase(hashPrev);
  2349. }
  2350.  
  2351. printf("ProcessBlock: ACCEPTED\n");
  2352. return true;
  2353. }
  2354.  
  2355.  
  2356.  
  2357.  
  2358.  
  2359.  
  2360.  
  2361.  
  2362. CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter)
  2363. {
  2364. header = block.GetBlockHeader();
  2365.  
  2366. vector<bool> vMatch;
  2367. vector<uint256> vHashes;
  2368.  
  2369. vMatch.reserve(block.vtx.size());
  2370. vHashes.reserve(block.vtx.size());
  2371.  
  2372. for (unsigned int i = 0; i < block.vtx.size(); i++)
  2373. {
  2374. uint256 hash = block.vtx[i].GetHash();
  2375. if (filter.IsRelevantAndUpdate(block.vtx[i], hash))
  2376. {
  2377. vMatch.push_back(true);
  2378. vMatchedTxn.push_back(make_pair(i, hash));
  2379. }
  2380. else
  2381. vMatch.push_back(false);
  2382. vHashes.push_back(hash);
  2383. }
  2384.  
  2385. txn = CPartialMerkleTree(vHashes, vMatch);
  2386. }
  2387.  
  2388.  
  2389.  
  2390.  
  2391.  
  2392.  
  2393.  
  2394.  
  2395. uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
  2396. if (height == 0) {
  2397. // hash at height 0 is the txids themself
  2398. return vTxid[pos];
  2399. } else {
  2400. // calculate left hash
  2401. uint256 left = CalcHash(height-1, pos*2, vTxid), right;
  2402. // calculate right hash if not beyong the end of the array - copy left hash otherwise1
  2403. if (pos*2+1 < CalcTreeWidth(height-1))
  2404. right = CalcHash(height-1, pos*2+1, vTxid);
  2405. else
  2406. right = left;
  2407. // combine subhashes
  2408. return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
  2409. }
  2410. }
  2411.  
  2412. void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
  2413. // determine whether this node is the parent of at least one matched txid
  2414. bool fParentOfMatch = false;
  2415. for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
  2416. fParentOfMatch |= vMatch[p];
  2417. // store as flag bit
  2418. vBits.push_back(fParentOfMatch);
  2419. if (height==0 || !fParentOfMatch) {
  2420. // if at height 0, or nothing interesting below, store hash and stop
  2421. vHash.push_back(CalcHash(height, pos, vTxid));
  2422. } else {
  2423. // otherwise, don't store any hash, but descend into the subtrees
  2424. TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
  2425. if (pos*2+1 < CalcTreeWidth(height-1))
  2426. TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
  2427. }
  2428. }
  2429.  
  2430. uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch) {
  2431. if (nBitsUsed >= vBits.size()) {
  2432. // overflowed the bits array - failure
  2433. fBad = true;
  2434. return 0;
  2435. }
  2436. bool fParentOfMatch = vBits[nBitsUsed++];
  2437. if (height==0 || !fParentOfMatch) {
  2438. // if at height 0, or nothing interesting below, use stored hash and do not descend
  2439. if (nHashUsed >= vHash.size()) {
  2440. // overflowed the hash array - failure
  2441. fBad = true;
  2442. return 0;
  2443. }
  2444. const uint256 &hash = vHash[nHashUsed++];
  2445. if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid
  2446. vMatch.push_back(hash);
  2447. return hash;
  2448. } else {
  2449. // otherwise, descend into the subtrees to extract matched txids and hashes
  2450. uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right;
  2451. if (pos*2+1 < CalcTreeWidth(height-1))
  2452. right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch);
  2453. else
  2454. right = left;
  2455. // and combine them before returning
  2456. return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
  2457. }
  2458. }
  2459.  
  2460. CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
  2461. // reset state
  2462. vBits.clear();
  2463. vHash.clear();
  2464.  
  2465. // calculate height of tree
  2466. int nHeight = 0;
  2467. while (CalcTreeWidth(nHeight) > 1)
  2468. nHeight++;
  2469.  
  2470. // traverse the partial tree
  2471. TraverseAndBuild(nHeight, 0, vTxid, vMatch);
  2472. }
  2473.  
  2474. CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
  2475.  
  2476. uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
  2477. vMatch.clear();
  2478. // An empty set will not work
  2479. if (nTransactions == 0)
  2480. return 0;
  2481. // check for excessively high numbers of transactions
  2482. if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
  2483. return 0;
  2484. // there can never be more hashes provided than one for every txid
  2485. if (vHash.size() > nTransactions)
  2486. return 0;
  2487. // there must be at least one bit per node in the partial tree, and at least one node per hash
  2488. if (vBits.size() < vHash.size())
  2489. return 0;
  2490. // calculate height of tree
  2491. int nHeight = 0;
  2492. while (CalcTreeWidth(nHeight) > 1)
  2493. nHeight++;
  2494. // traverse the partial tree
  2495. unsigned int nBitsUsed = 0, nHashUsed = 0;
  2496. uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch);
  2497. // verify that no problems occured during the tree traversal
  2498. if (fBad)
  2499. return 0;
  2500. // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
  2501. if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
  2502. return 0;
  2503. // verify that all hashes were consumed
  2504. if (nHashUsed != vHash.size())
  2505. return 0;
  2506. return hashMerkleRoot;
  2507. }
  2508.  
  2509.  
  2510.  
  2511.  
  2512.  
  2513.  
  2514.  
  2515. bool AbortNode(const std::string &strMessage) {
  2516. strMiscWarning = strMessage;
  2517. printf("*** %s\n", strMessage.c_str());
  2518. uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR);
  2519. StartShutdown();
  2520. return false;
  2521. }
  2522.  
  2523. bool CheckDiskSpace(uint64 nAdditionalBytes)
  2524. {
  2525. uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
  2526.  
  2527. // Check for nMinDiskSpace bytes (currently 50MB)
  2528. if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
  2529. return AbortNode(_("Error: Disk space is low!"));
  2530.  
  2531. return true;
  2532. }
  2533.  
  2534. CCriticalSection cs_LastBlockFile;
  2535. CBlockFileInfo infoLastBlockFile;
  2536. int nLastBlockFile = 0;
  2537.  
  2538. FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
  2539. {
  2540. if (pos.IsNull())
  2541. return NULL;
  2542. boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
  2543. boost::filesystem::create_directories(path.parent_path());
  2544. FILE* file = fopen(path.string().c_str(), "rb+");
  2545. if (!file && !fReadOnly)
  2546. file = fopen(path.string().c_str(), "wb+");
  2547. if (!file) {
  2548. printf("Unable to open file %s\n", path.string().c_str());
  2549. return NULL;
  2550. }
  2551. if (pos.nPos) {
  2552. if (fseek(file, pos.nPos, SEEK_SET)) {
  2553. printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
  2554. fclose(file);
  2555. return NULL;
  2556. }
  2557. }
  2558. return file;
  2559. }
  2560.  
  2561. FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
  2562. return OpenDiskFile(pos, "blk", fReadOnly);
  2563. }
  2564.  
  2565. FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
  2566. return OpenDiskFile(pos, "rev", fReadOnly);
  2567. }
  2568.  
  2569. CBlockIndex * InsertBlockIndex(uint256 hash)
  2570. {
  2571. if (hash == 0)
  2572. return NULL;
  2573.  
  2574. // Return existing
  2575. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
  2576. if (mi != mapBlockIndex.end())
  2577. return (*mi).second;
  2578.  
  2579. // Create new
  2580. CBlockIndex* pindexNew = new CBlockIndex();
  2581. if (!pindexNew)
  2582. throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
  2583. mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
  2584. pindexNew->phashBlock = &((*mi).first);
  2585.  
  2586. return pindexNew;
  2587. }
  2588.  
  2589. bool static LoadBlockIndexDB()
  2590. {
  2591. if (!pblocktree->LoadBlockIndexGuts())
  2592. return false;
  2593.  
  2594. boost::this_thread::interruption_point();
  2595.  
  2596. // Calculate nChainWork
  2597. vector<pair<int, CBlockIndex*> > vSortedByHeight;
  2598. vSortedByHeight.reserve(mapBlockIndex.size());
  2599. BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
  2600. {
  2601. CBlockIndex* pindex = item.second;
  2602. vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
  2603. }
  2604. sort(vSortedByHeight.begin(), vSortedByHeight.end());
  2605. BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
  2606. {
  2607. CBlockIndex* pindex = item.second;
  2608. pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + pindex->GetBlockWork().getuint256();
  2609. pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
  2610. if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS && !(pindex->nStatus & BLOCK_FAILED_MASK))
  2611. setBlockIndexValid.insert(pindex);
  2612. }
  2613.  
  2614. // Load block file info
  2615. pblocktree->ReadLastBlockFile(nLastBlockFile);
  2616. printf("LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
  2617. if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
  2618. printf("LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString().c_str());
  2619.  
  2620. // Load nBestInvalidWork, OK if it doesn't exist
  2621. CBigNum bnBestInvalidWork;
  2622. pblocktree->ReadBestInvalidWork(bnBestInvalidWork);
  2623. nBestInvalidWork = bnBestInvalidWork.getuint256();
  2624.  
  2625. // Check whether we need to continue reindexing
  2626. bool fReindexing = false;
  2627. pblocktree->ReadReindexing(fReindexing);
  2628. fReindex |= fReindexing;
  2629.  
  2630. // Check whether we have a transaction index
  2631. pblocktree->ReadFlag("txindex", fTxIndex);
  2632. printf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
  2633.  
  2634. // Load hashBestChain pointer to end of best chain
  2635. pindexBest = pcoinsTip->GetBestBlock();
  2636. if (pindexBest == NULL)
  2637. return true;
  2638. hashBestChain = pindexBest->GetBlockHash();
  2639. nBestHeight = pindexBest->nHeight;
  2640. nBestChainWork = pindexBest->nChainWork;
  2641.  
  2642. // set 'next' pointers in best chain
  2643. CBlockIndex *pindex = pindexBest;
  2644. while(pindex != NULL && pindex->pprev != NULL) {
  2645. CBlockIndex *pindexPrev = pindex->pprev;
  2646. pindexPrev->pnext = pindex;
  2647. pindex = pindexPrev;
  2648. }
  2649. printf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s\n",
  2650. hashBestChain.ToString().c_str(), nBestHeight,
  2651. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexBest->GetBlockTime()).c_str());
  2652.  
  2653. return true;
  2654. }
  2655.  
  2656. bool VerifyDB(int nCheckLevel, int nCheckDepth)
  2657. {
  2658. if (pindexBest == NULL || pindexBest->pprev == NULL)
  2659. return true;
  2660.  
  2661. // Verify blocks in the best chain
  2662. if (nCheckDepth <= 0)
  2663. nCheckDepth = 1000000000; // suffices until the year 19000
  2664. if (nCheckDepth > nBestHeight)
  2665. nCheckDepth = nBestHeight;
  2666. nCheckLevel = std::max(0, std::min(4, nCheckLevel));
  2667. printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
  2668. CCoinsViewCache coins(*pcoinsTip, true);
  2669. CBlockIndex* pindexState = pindexBest;
  2670. CBlockIndex* pindexFailure = NULL;
  2671. int nGoodTransactions = 0;
  2672. CValidationState state;
  2673. for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
  2674. {
  2675. boost::this_thread::interruption_point();
  2676. if (pindex->nHeight < nBestHeight-nCheckDepth)
  2677. break;
  2678. CBlock block;
  2679. // check level 0: read from disk
  2680. if (!block.ReadFromDisk(pindex))
  2681. return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2682. // check level 1: verify block validity
  2683. if (nCheckLevel >= 1 && !block.CheckBlock(state))
  2684. return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2685. // check level 2: verify undo validity
  2686. if (nCheckLevel >= 2 && pindex) {
  2687. CBlockUndo undo;
  2688. CDiskBlockPos pos = pindex->GetUndoPos();
  2689. if (!pos.IsNull()) {
  2690. if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
  2691. return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2692. }
  2693. }
  2694. // check level 3: check for inconsistencies during memory-only disconnect of tip blocks
  2695. if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
  2696. bool fClean = true;
  2697. if (!block.DisconnectBlock(state, pindex, coins, &fClean))
  2698. return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2699. pindexState = pindex->pprev;
  2700. if (!fClean) {
  2701. nGoodTransactions = 0;
  2702. pindexFailure = pindex;
  2703. } else
  2704. nGoodTransactions += block.vtx.size();
  2705. }
  2706. }
  2707. if (pindexFailure)
  2708. return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", pindexBest->nHeight - pindexFailure->nHeight + 1, nGoodTransactions);
  2709.  
  2710. // check level 4: try reconnecting blocks
  2711. if (nCheckLevel >= 4) {
  2712. CBlockIndex *pindex = pindexState;
  2713. while (pindex != pindexBest) {
  2714. boost::this_thread::interruption_point();
  2715. pindex = pindex->pnext;
  2716. CBlock block;
  2717. if (!block.ReadFromDisk(pindex))
  2718. return error("VerifyDB() : *** block.ReadFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2719. if (!block.ConnectBlock(state, pindex, coins))
  2720. return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  2721. }
  2722. }
  2723.  
  2724. printf("No coin database inconsistencies in last %i blocks (%i transactions)\n", pindexBest->nHeight - pindexState->nHeight, nGoodTransactions);
  2725.  
  2726. return true;
  2727. }
  2728.  
  2729. void UnloadBlockIndex()
  2730. {
  2731. mapBlockIndex.clear();
  2732. setBlockIndexValid.clear();
  2733. pindexGenesisBlock = NULL;
  2734. nBestHeight = 0;
  2735. nBestChainWork = 0;
  2736. nBestInvalidWork = 0;
  2737. hashBestChain = 0;
  2738. pindexBest = NULL;
  2739. }
  2740.  
  2741. bool LoadBlockIndex()
  2742. {
  2743. if (fTestNet)
  2744. {
  2745. pchMessageStart[0] = 0xfc;
  2746. pchMessageStart[1] = 0xc4;
  2747. pchMessageStart[2] = 0xb1;
  2748. pchMessageStart[3] = 0xdb;
  2749. hashGenesisBlock = uint256("0xba91c3ad451d1bff3c8330c219520b84fac8123ec797d4cd2a89b43d81145f99");
  2750. }
  2751.  
  2752. //
  2753. // Load block index from databases
  2754. //
  2755. if (!fReindex && !LoadBlockIndexDB())
  2756. return false;
  2757.  
  2758. return true;
  2759. }
  2760.  
  2761.  
  2762. bool InitBlockIndex() {
  2763. // Check whether we're already initialized
  2764. if (pindexGenesisBlock != NULL)
  2765. return true;
  2766.  
  2767. // Use the provided setting for -txindex in the new database
  2768. fTxIndex = GetBoolArg("-txindex", false);
  2769. pblocktree->WriteFlag("txindex", fTxIndex);
  2770. printf("Initializing databases...\n");
  2771.  
  2772. // Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
  2773. if (!fReindex) {
  2774. // Genesis Block:
  2775. // CBlock(hash=12a765e31ffd4059bada, PoW=0000050c34a64b415b6b, ver=1, hashPrevBlock=00000000000000000000, hashMerkleRoot=97ddfbbae6, nTime=1317972665, nBits=1e0ffff0, nNonce=2084524493, vtx=1)
  2776. // CTransaction(hash=97ddfbbae6, ver=1, vin.size=1, vout.size=1, nLockTime=0)
  2777. // CTxIn(COutPoint(0000000000, -1), coinbase 04ffff001d0104404e592054696d65732030352f4f63742f32303131205374657665204a6f62732c204170706c65e280997320566973696f6e6172792c2044696573206174203536)
  2778. // CTxOut(nValue=50.00000000, scriptPubKey=040184710fa689ad5023690c80f3a4)
  2779. // vMerkleTree: 97ddfbbae6
  2780.  
  2781. // Genesis block
  2782. const char* pszTimestamp = "11/Oct/2021 Tyson Fury KOs Deontay Wilder";
  2783. CTransaction txNew;
  2784. txNew.vin.resize(1);
  2785. txNew.vout.resize(1);
  2786. txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
  2787. txNew.vout[0].nValue = 50 * COIN;
  2788. txNew.vout[0].scriptPubKey = CScript() << ParseHex("04902338564fec8a0d9535db20d8cc0961c844706b468510bcf2adedd63414fbb1c9ab91283d87ec48e7e0e63a354f88e6c326b0e33397e8b286fc4ff56f31e694") << OP_CHECKSIG;
  2789. CBlock block;
  2790. block.vtx.push_back(txNew);
  2791. block.hashPrevBlock = 0;
  2792. block.hashMerkleRoot = block.BuildMerkleTree();
  2793. block.nVersion = 1;
  2794. block.nTime = 1637450617;
  2795. block.nBits = 0x1e0ffff0;
  2796. block.nNonce = 2085089403;
  2797.  
  2798. if (fTestNet)
  2799. {
  2800. block.nTime = 1637450528;
  2801. block.nNonce = 385818922;
  2802. }
  2803.  
  2804. if (true && block.GetHash() != hashGenesisBlock)
  2805. {
  2806. printf("Searching for genesis block...\n");
  2807. // This will figure out a valid hash and Nonce if you're
  2808. // creating a different genesis block:
  2809. uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256();
  2810. uint256 thash;
  2811. char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
  2812.  
  2813. loop
  2814. {
  2815. #if defined(USE_SSE2)
  2816. // Detection would work, but in cases where we KNOW it always has SSE2,
  2817. // it is faster to use directly than to use a function pointer or conditional.
  2818. #if defined(_M_X64) || defined(__x86_64__) || defined(_M_AMD64) || (defined(MAC_OSX) && defined(__i386__))
  2819. // Always SSE2: x86_64 or Intel MacOS X
  2820. scrypt_1024_1_1_256_sp_sse2(BEGIN(block.nVersion), BEGIN(thash), scratchpad);
  2821. #else
  2822. // Detect SSE2: 32bit x86 Linux or Windows
  2823. scrypt_1024_1_1_256_sp(BEGIN(block.nVersion), BEGIN(thash), scratchpad);
  2824. #endif
  2825. #else
  2826. // Generic scrypt
  2827. scrypt_1024_1_1_256_sp_generic(BEGIN(block.nVersion), BEGIN(thash), scratchpad);
  2828. #endif
  2829. if (thash <= hashTarget)
  2830. break;
  2831. if ((block.nNonce & 0xFFF) == 0)
  2832. {
  2833. printf("nonce %08X: hash = %s (target = %s)\n", block.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
  2834. }
  2835. ++block.nNonce;
  2836. if (block.nNonce == 0)
  2837. {
  2838. printf("NONCE WRAPPED, incrementing time\n");
  2839. ++block.nTime;
  2840. }
  2841. }
  2842. printf("block.nTime = %u \n", block.nTime);
  2843. printf("block.nNonce = %u \n", block.nNonce);
  2844. printf("block.GetHash = %s\n", block.GetHash().ToString().c_str());
  2845. }
  2846.  
  2847. //// debug print
  2848. uint256 hash = block.GetHash();
  2849. printf("%s\n", hash.ToString().c_str());
  2850. printf("%s\n", hashGenesisBlock.ToString().c_str());
  2851. printf("%s\n", block.hashMerkleRoot.ToString().c_str());
  2852. assert(block.hashMerkleRoot == uint256("0x"));
  2853. block.print();
  2854. assert(hash == hashGenesisBlock);
  2855.  
  2856. // Start new block file
  2857. try {
  2858. unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
  2859. CDiskBlockPos blockPos;
  2860. CValidationState state;
  2861. if (!FindBlockPos(state, blockPos, nBlockSize+8, 0, block.nTime))
  2862. return error("LoadBlockIndex() : FindBlockPos failed");
  2863. if (!block.WriteToDisk(blockPos))
  2864. return error("LoadBlockIndex() : writing genesis block to disk failed");
  2865. if (!block.AddToBlockIndex(state, blockPos))
  2866. return error("LoadBlockIndex() : genesis block not accepted");
  2867. } catch(std::runtime_error &e) {
  2868. return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
  2869. }
  2870. }
  2871.  
  2872. return true;
  2873. }
  2874.  
  2875.  
  2876.  
  2877. void PrintBlockTree()
  2878. {
  2879. // pre-compute tree structure
  2880. map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
  2881. for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
  2882. {
  2883. CBlockIndex* pindex = (*mi).second;
  2884. mapNext[pindex->pprev].push_back(pindex);
  2885. // test
  2886. //while (rand() % 3 == 0)
  2887. // mapNext[pindex->pprev].push_back(pindex);
  2888. }
  2889.  
  2890. vector<pair<int, CBlockIndex*> > vStack;
  2891. vStack.push_back(make_pair(0, pindexGenesisBlock));
  2892.  
  2893. int nPrevCol = 0;
  2894. while (!vStack.empty())
  2895. {
  2896. int nCol = vStack.back().first;
  2897. CBlockIndex* pindex = vStack.back().second;
  2898. vStack.pop_back();
  2899.  
  2900. // print split or gap
  2901. if (nCol > nPrevCol)
  2902. {
  2903. for (int i = 0; i < nCol-1; i++)
  2904. printf("| ");
  2905. printf("|\\\n");
  2906. }
  2907. else if (nCol < nPrevCol)
  2908. {
  2909. for (int i = 0; i < nCol; i++)
  2910. printf("| ");
  2911. printf("|\n");
  2912. }
  2913. nPrevCol = nCol;
  2914.  
  2915. // print columns
  2916. for (int i = 0; i < nCol; i++)
  2917. printf("| ");
  2918.  
  2919. // print item
  2920. CBlock block;
  2921. block.ReadFromDisk(pindex);
  2922. printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
  2923. pindex->nHeight,
  2924. pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
  2925. DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
  2926. block.vtx.size());
  2927.  
  2928. PrintWallets(block);
  2929.  
  2930. // put the main time-chain first
  2931. vector<CBlockIndex*>& vNext = mapNext[pindex];
  2932. for (unsigned int i = 0; i < vNext.size(); i++)
  2933. {
  2934. if (vNext[i]->pnext)
  2935. {
  2936. swap(vNext[0], vNext[i]);
  2937. break;
  2938. }
  2939. }
  2940.  
  2941. // iterate children
  2942. for (unsigned int i = 0; i < vNext.size(); i++)
  2943. vStack.push_back(make_pair(nCol+i, vNext[i]));
  2944. }
  2945. }
  2946.  
  2947. bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
  2948. {
  2949. int64 nStart = GetTimeMillis();
  2950.  
  2951. int nLoaded = 0;
  2952. try {
  2953. CBufferedFile blkdat(fileIn, 2*MAX_BLOCK_SIZE, MAX_BLOCK_SIZE+8, SER_DISK, CLIENT_VERSION);
  2954. uint64 nStartByte = 0;
  2955. if (dbp) {
  2956. // (try to) skip already indexed part
  2957. CBlockFileInfo info;
  2958. if (pblocktree->ReadBlockFileInfo(dbp->nFile, info)) {
  2959. nStartByte = info.nSize;
  2960. blkdat.Seek(info.nSize);
  2961. }
  2962. }
  2963. uint64 nRewind = blkdat.GetPos();
  2964. while (blkdat.good() && !blkdat.eof()) {
  2965. boost::this_thread::interruption_point();
  2966.  
  2967. blkdat.SetPos(nRewind);
  2968. nRewind++; // start one byte further next time, in case of failure
  2969. blkdat.SetLimit(); // remove former limit
  2970. unsigned int nSize = 0;
  2971. try {
  2972. // locate a header
  2973. unsigned char buf[4];
  2974. blkdat.FindByte(pchMessageStart[0]);
  2975. nRewind = blkdat.GetPos()+1;
  2976. blkdat >> FLATDATA(buf);
  2977. if (memcmp(buf, pchMessageStart, 4))
  2978. continue;
  2979. // read size
  2980. blkdat >> nSize;
  2981. if (nSize < 80 || nSize > MAX_BLOCK_SIZE)
  2982. continue;
  2983. } catch (std::exception &e) {
  2984. // no valid block header found; don't complain
  2985. break;
  2986. }
  2987. try {
  2988. // read block
  2989. uint64 nBlockPos = blkdat.GetPos();
  2990. blkdat.SetLimit(nBlockPos + nSize);
  2991. CBlock block;
  2992. blkdat >> block;
  2993. nRewind = blkdat.GetPos();
  2994.  
  2995. // process block
  2996. if (nBlockPos >= nStartByte) {
  2997. LOCK(cs_main);
  2998. if (dbp)
  2999. dbp->nPos = nBlockPos;
  3000. CValidationState state;
  3001. if (ProcessBlock(state, NULL, &block, dbp))
  3002. nLoaded++;
  3003. if (state.IsError())
  3004. break;
  3005. }
  3006. } catch (std::exception &e) {
  3007. printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__);
  3008. }
  3009. }
  3010. fclose(fileIn);
  3011. } catch(std::runtime_error &e) {
  3012. AbortNode(_("Error: system error: ") + e.what());
  3013. }
  3014. if (nLoaded > 0)
  3015. printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
  3016. return nLoaded > 0;
  3017. }
  3018.  
  3019.  
  3020.  
  3021.  
  3022.  
  3023.  
  3024.  
  3025.  
  3026.  
  3027.  
  3028. //////////////////////////////////////////////////////////////////////////////
  3029. //
  3030. // CAlert
  3031. //
  3032.  
  3033. extern map<uint256, CAlert> mapAlerts;
  3034. extern CCriticalSection cs_mapAlerts;
  3035.  
  3036. string GetWarnings(string strFor)
  3037. {
  3038. int nPriority = 0;
  3039. string strStatusBar;
  3040. string strRPC;
  3041.  
  3042. if (GetBoolArg("-testsafemode"))
  3043. strRPC = "test";
  3044.  
  3045. if (!CLIENT_VERSION_IS_RELEASE)
  3046. strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications");
  3047.  
  3048. // Misc warnings like out of disk space and clock is wrong
  3049. if (strMiscWarning != "")
  3050. {
  3051. nPriority = 1000;
  3052. strStatusBar = strMiscWarning;
  3053. }
  3054.  
  3055. // Longer invalid proof-of-work chain
  3056. if (pindexBest && nBestInvalidWork > nBestChainWork + (pindexBest->GetBlockWork() * 6).getuint256())
  3057. {
  3058. nPriority = 2000;
  3059. strStatusBar = strRPC = _("Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.");
  3060. }
  3061.  
  3062. // Alerts
  3063. {
  3064. LOCK(cs_mapAlerts);
  3065. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  3066. {
  3067. const CAlert& alert = item.second;
  3068. if (alert.AppliesToMe() && alert.nPriority > nPriority)
  3069. {
  3070. nPriority = alert.nPriority;
  3071. strStatusBar = alert.strStatusBar;
  3072. }
  3073. }
  3074. }
  3075.  
  3076. if (strFor == "statusbar")
  3077. return strStatusBar;
  3078. else if (strFor == "rpc")
  3079. return strRPC;
  3080. assert(!"GetWarnings() : invalid parameter");
  3081. return "error";
  3082. }
  3083.  
  3084.  
  3085.  
  3086.  
  3087.  
  3088.  
  3089.  
  3090.  
  3091. //////////////////////////////////////////////////////////////////////////////
  3092. //
  3093. // Messages
  3094. //
  3095.  
  3096.  
  3097. bool static AlreadyHave(const CInv& inv)
  3098. {
  3099. switch (inv.type)
  3100. {
  3101. case MSG_TX:
  3102. {
  3103. bool txInMap = false;
  3104. {
  3105. LOCK(mempool.cs);
  3106. txInMap = mempool.exists(inv.hash);
  3107. }
  3108. return txInMap || mapOrphanTransactions.count(inv.hash) ||
  3109. pcoinsTip->HaveCoins(inv.hash);
  3110. }
  3111. case MSG_BLOCK:
  3112. return mapBlockIndex.count(inv.hash) ||
  3113. mapOrphanBlocks.count(inv.hash);
  3114. }
  3115. // Don't know what it is, just say we already got one
  3116. return true;
  3117. }
  3118.  
  3119.  
  3120.  
  3121.  
  3122. // The message start string is designed to be unlikely to occur in normal data.
  3123. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
  3124. // a large 4-byte int at any alignment.
  3125. unsigned char pchMessageStart[4] = { 0xfb, 0xc3, 0xb4, 0xdc }; // Shibacoin: increase each by adding 2 to Shibacoin's value.
  3126.  
  3127.  
  3128. void static ProcessGetData(CNode* pfrom)
  3129. {
  3130. std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
  3131.  
  3132. vector<CInv> vNotFound;
  3133.  
  3134. while (it != pfrom->vRecvGetData.end()) {
  3135. // Don't bother if send buffer is too full to respond anyway
  3136. if (pfrom->nSendSize >= SendBufferSize())
  3137. break;
  3138.  
  3139. // Don't waste work on slow peers until they catch up on the blocks we
  3140. // give them. 80 bytes is just the size of a block header - obviously
  3141. // the minimum we might return.
  3142. if (pfrom->nBlocksRequested * 80 > pfrom->nSendBytes)
  3143. break;
  3144.  
  3145. const CInv &inv = *it;
  3146. {
  3147. boost::this_thread::interruption_point();
  3148. it++;
  3149.  
  3150. if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
  3151. {
  3152. bool send = true;
  3153. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
  3154. pfrom->nBlocksRequested++;
  3155. if (mi != mapBlockIndex.end())
  3156. {
  3157. // If the requested block is at a height below our last
  3158. // checkpoint, only serve it if it's in the checkpointed chain
  3159. int nHeight = ((*mi).second)->nHeight;
  3160. CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
  3161. if (pcheckpoint && nHeight < pcheckpoint->nHeight) {
  3162. if (!((*mi).second)->IsInMainChain())
  3163. {
  3164. printf("ProcessGetData(): ignoring request for old block that isn't in the main chain\n");
  3165. send = false;
  3166. }
  3167. }
  3168. } else {
  3169. send = false;
  3170. }
  3171. if (send)
  3172. {
  3173. // Send block from disk
  3174. CBlock block;
  3175. block.ReadFromDisk((*mi).second);
  3176. if (inv.type == MSG_BLOCK)
  3177. pfrom->PushMessage("block", block);
  3178. else // MSG_FILTERED_BLOCK)
  3179. {
  3180. LOCK(pfrom->cs_filter);
  3181. if (pfrom->pfilter)
  3182. {
  3183. CMerkleBlock merkleBlock(block, *pfrom->pfilter);
  3184. pfrom->PushMessage("merkleblock", merkleBlock);
  3185. // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
  3186. // This avoids hurting performance by pointlessly requiring a round-trip
  3187. // Note that there is currently no way for a node to request any single transactions we didnt send here -
  3188. // they must either disconnect and retry or request the full block.
  3189. // Thus, the protocol spec specified allows for us to provide duplicate txn here,
  3190. // however we MUST always provide at least what the remote peer needs
  3191. typedef std::pair<unsigned int, uint256> PairType;
  3192. BOOST_FOREACH(PairType& pair, merkleBlock.vMatchedTxn)
  3193. if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
  3194. pfrom->PushMessage("tx", block.vtx[pair.first]);
  3195. }
  3196. // else
  3197. // no response
  3198. }
  3199.  
  3200. // Trigger them to send a getblocks request for the next batch of inventory
  3201. if (inv.hash == pfrom->hashContinue)
  3202. {
  3203. // Bypass PushInventory, this must send even if redundant,
  3204. // and we want it right after the last block so they don't
  3205. // wait for other stuff first.
  3206. vector<CInv> vInv;
  3207. vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
  3208. pfrom->PushMessage("inv", vInv);
  3209. pfrom->hashContinue = 0;
  3210. }
  3211. }
  3212. }
  3213. else if (inv.IsKnownType())
  3214. {
  3215. // Send stream from relay memory
  3216. bool pushed = false;
  3217. {
  3218. LOCK(cs_mapRelay);
  3219. map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
  3220. if (mi != mapRelay.end()) {
  3221. pfrom->PushMessage(inv.GetCommand(), (*mi).second);
  3222. pushed = true;
  3223. }
  3224. }
  3225. if (!pushed && inv.type == MSG_TX) {
  3226. LOCK(mempool.cs);
  3227. if (mempool.exists(inv.hash)) {
  3228. CTransaction tx = mempool.lookup(inv.hash);
  3229. CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
  3230. ss.reserve(1000);
  3231. ss << tx;
  3232. pfrom->PushMessage("tx", ss);
  3233. pushed = true;
  3234. }
  3235. }
  3236. if (!pushed) {
  3237. vNotFound.push_back(inv);
  3238. }
  3239. }
  3240.  
  3241. // Track requests for our stuff.
  3242. Inventory(inv.hash);
  3243.  
  3244. if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
  3245. break;
  3246. }
  3247. }
  3248.  
  3249. pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
  3250.  
  3251. if (!vNotFound.empty()) {
  3252. // Let the peer know that we didn't find what it asked for, so it doesn't
  3253. // have to wait around forever. Currently only SPV clients actually care
  3254. // about this message: it's needed when they are recursively walking the
  3255. // dependencies of relevant unconfirmed transactions. SPV clients want to
  3256. // do that because they want to know about (and store and rebroadcast and
  3257. // risk analyze) the dependencies of transactions relevant to them, without
  3258. // having to download the entire memory pool.
  3259. pfrom->PushMessage("notfound", vNotFound);
  3260. }
  3261. }
  3262.  
  3263. bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
  3264. {
  3265. RandAddSeedPerfmon();
  3266. if (fDebug)
  3267. printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
  3268. if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
  3269. {
  3270. printf("dropmessagestest DROPPING RECV MESSAGE\n");
  3271. return true;
  3272. }
  3273.  
  3274.  
  3275.  
  3276.  
  3277.  
  3278. if (strCommand == "version")
  3279. {
  3280. // Each connection can only send one version message
  3281. if (pfrom->nVersion != 0)
  3282. {
  3283. pfrom->Misbehaving(1);
  3284. return false;
  3285. }
  3286.  
  3287. int64 nTime;
  3288. CAddress addrMe;
  3289. CAddress addrFrom;
  3290. uint64 nNonce = 1;
  3291. vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
  3292. if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
  3293. {
  3294. // disconnect from peers older than this proto version
  3295. printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
  3296. pfrom->fDisconnect = true;
  3297. return false;
  3298. }
  3299.  
  3300. if (pfrom->nVersion == 10300)
  3301. pfrom->nVersion = 300;
  3302. if (!vRecv.empty())
  3303. vRecv >> addrFrom >> nNonce;
  3304. if (!vRecv.empty()) {
  3305. vRecv >> pfrom->strSubVer;
  3306. pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
  3307. }
  3308. if (!vRecv.empty())
  3309. vRecv >> pfrom->nStartingHeight;
  3310. if (!vRecv.empty())
  3311. vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
  3312. else
  3313. pfrom->fRelayTxes = true;
  3314.  
  3315. if (pfrom->fInbound && addrMe.IsRoutable())
  3316. {
  3317. pfrom->addrLocal = addrMe;
  3318. SeenLocal(addrMe);
  3319. }
  3320.  
  3321. // Disconnect if we connected to ourself
  3322. if (nNonce == nLocalHostNonce && nNonce > 1)
  3323. {
  3324. printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
  3325. pfrom->fDisconnect = true;
  3326. return true;
  3327. }
  3328.  
  3329. // Be shy and don't send version until we hear
  3330. if (pfrom->fInbound)
  3331. pfrom->PushVersion();
  3332.  
  3333. pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
  3334.  
  3335. AddTimeData(pfrom->addr, nTime);
  3336.  
  3337. // Change version
  3338. pfrom->PushMessage("verack");
  3339. pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
  3340.  
  3341. if (!pfrom->fInbound)
  3342. {
  3343. // Advertise our address
  3344. if (!fNoListen && !IsInitialBlockDownload())
  3345. {
  3346. CAddress addr = GetLocalAddress(&pfrom->addr);
  3347. if (addr.IsRoutable())
  3348. pfrom->PushAddress(addr);
  3349. }
  3350.  
  3351. // Get recent addresses
  3352. if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
  3353. {
  3354. pfrom->PushMessage("getaddr");
  3355. pfrom->fGetAddr = true;
  3356. }
  3357. addrman.Good(pfrom->addr);
  3358. } else {
  3359. if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
  3360. {
  3361. addrman.Add(addrFrom, addrFrom);
  3362. addrman.Good(addrFrom);
  3363. }
  3364. }
  3365.  
  3366. // Relay alerts
  3367. {
  3368. LOCK(cs_mapAlerts);
  3369. BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
  3370. item.second.RelayTo(pfrom);
  3371. }
  3372.  
  3373. pfrom->fSuccessfullyConnected = true;
  3374.  
  3375. printf("receive version message: %s: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->cleanSubVer.c_str(), pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
  3376.  
  3377. cPeerBlockCounts.input(pfrom->nStartingHeight);
  3378. }
  3379.  
  3380.  
  3381. else if (pfrom->nVersion == 0)
  3382. {
  3383. // Must have a version message before anything else
  3384. pfrom->Misbehaving(1);
  3385. return false;
  3386. }
  3387.  
  3388.  
  3389. else if (strCommand == "verack")
  3390. {
  3391. pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
  3392. }
  3393.  
  3394.  
  3395. else if (strCommand == "addr")
  3396. {
  3397. vector<CAddress> vAddr;
  3398. vRecv >> vAddr;
  3399.  
  3400. // Don't want addr from older versions unless seeding
  3401. if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
  3402. return true;
  3403. if (vAddr.size() > 1000)
  3404. {
  3405. pfrom->Misbehaving(20);
  3406. return error("message addr size() = %"PRIszu"", vAddr.size());
  3407. }
  3408.  
  3409. // Store the new addresses
  3410. vector<CAddress> vAddrOk;
  3411. int64 nNow = GetAdjustedTime();
  3412. int64 nSince = nNow - 10 * 60;
  3413. BOOST_FOREACH(CAddress& addr, vAddr)
  3414. {
  3415. boost::this_thread::interruption_point();
  3416.  
  3417. if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
  3418. addr.nTime = nNow - 5 * 24 * 60 * 60;
  3419. pfrom->AddAddressKnown(addr);
  3420. bool fReachable = IsReachable(addr);
  3421. if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
  3422. {
  3423. // Relay to a limited number of other nodes
  3424. {
  3425. LOCK(cs_vNodes);
  3426. // Use deterministic randomness to send to the same nodes for 24 hours
  3427. // at a time so the setAddrKnowns of the chosen nodes prevent repeats
  3428. static uint256 hashSalt;
  3429. if (hashSalt == 0)
  3430. hashSalt = GetRandHash();
  3431. uint64 hashAddr = addr.GetHash();
  3432. uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
  3433. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  3434. multimap<uint256, CNode*> mapMix;
  3435. BOOST_FOREACH(CNode* pnode, vNodes)
  3436. {
  3437. if (pnode->nVersion < CADDR_TIME_VERSION)
  3438. continue;
  3439. unsigned int nPointer;
  3440. memcpy(&nPointer, &pnode, sizeof(nPointer));
  3441. uint256 hashKey = hashRand ^ nPointer;
  3442. hashKey = Hash(BEGIN(hashKey), END(hashKey));
  3443. mapMix.insert(make_pair(hashKey, pnode));
  3444. }
  3445. int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
  3446. for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
  3447. ((*mi).second)->PushAddress(addr);
  3448. }
  3449. }
  3450. // Do not store addresses outside our network
  3451. if (fReachable)
  3452. vAddrOk.push_back(addr);
  3453. }
  3454. addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
  3455. if (vAddr.size() < 1000)
  3456. pfrom->fGetAddr = false;
  3457. if (pfrom->fOneShot)
  3458. pfrom->fDisconnect = true;
  3459. }
  3460.  
  3461.  
  3462. else if (strCommand == "inv")
  3463. {
  3464. vector<CInv> vInv;
  3465. vRecv >> vInv;
  3466. if (vInv.size() > MAX_INV_SZ)
  3467. {
  3468. pfrom->Misbehaving(20);
  3469. return error("message inv size() = %"PRIszu"", vInv.size());
  3470. }
  3471.  
  3472. // find last block in inv vector
  3473. unsigned int nLastBlock = (unsigned int)(-1);
  3474. for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
  3475. if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
  3476. nLastBlock = vInv.size() - 1 - nInv;
  3477. break;
  3478. }
  3479. }
  3480. for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
  3481. {
  3482. const CInv &inv = vInv[nInv];
  3483.  
  3484. boost::this_thread::interruption_point();
  3485. pfrom->AddInventoryKnown(inv);
  3486.  
  3487. bool fAlreadyHave = AlreadyHave(inv);
  3488. if (fDebug)
  3489. printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
  3490.  
  3491. if (!fAlreadyHave) {
  3492. if (!fImporting && !fReindex)
  3493. pfrom->AskFor(inv);
  3494. } else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
  3495. pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
  3496. } else if (nInv == nLastBlock) {
  3497. // In case we are on a very long side-chain, it is possible that we already have
  3498. // the last block in an inv bundle sent in response to getblocks. Try to detect
  3499. // this situation and push another getblocks to continue.
  3500. pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
  3501. if (fDebug)
  3502. printf("force request: %s\n", inv.ToString().c_str());
  3503. }
  3504.  
  3505. // Track requests for our stuff
  3506. Inventory(inv.hash);
  3507.  
  3508. if (pfrom->nSendSize > (SendBufferSize() * 2)) {
  3509. pfrom->Misbehaving(50);
  3510. return error("send buffer size() = %"PRIszu"", pfrom->nSendSize);
  3511. }
  3512. }
  3513. }
  3514.  
  3515.  
  3516. else if (strCommand == "getdata")
  3517. {
  3518. vector<CInv> vInv;
  3519. vRecv >> vInv;
  3520. if (vInv.size() > MAX_INV_SZ)
  3521. {
  3522. pfrom->Misbehaving(20);
  3523. return error("message getdata size() = %"PRIszu"", vInv.size());
  3524. }
  3525.  
  3526. if (fDebugNet || (vInv.size() != 1))
  3527. printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
  3528.  
  3529. if ((fDebugNet && vInv.size() > 0) || (vInv.size() == 1))
  3530. printf("received getdata for: %s\n", vInv[0].ToString().c_str());
  3531.  
  3532. pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
  3533. ProcessGetData(pfrom);
  3534. }
  3535.  
  3536.  
  3537. else if (strCommand == "getblocks")
  3538. {
  3539. CBlockLocator locator;
  3540. uint256 hashStop;
  3541. vRecv >> locator >> hashStop;
  3542.  
  3543. // Find the last block the caller has in the main chain
  3544. CBlockIndex* pindex = locator.GetBlockIndex();
  3545.  
  3546. // Send the rest of the chain
  3547. if (pindex)
  3548. pindex = pindex->pnext;
  3549. int nLimit = 500;
  3550. printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str(), nLimit);
  3551. for (; pindex; pindex = pindex->pnext)
  3552. {
  3553. if (pindex->GetBlockHash() == hashStop)
  3554. {
  3555. printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  3556. break;
  3557. }
  3558. pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
  3559. if (--nLimit <= 0)
  3560. {
  3561. // When this block is requested, we'll send an inv that'll make them
  3562. // getblocks the next batch of inventory.
  3563. printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
  3564. pfrom->hashContinue = pindex->GetBlockHash();
  3565. break;
  3566. }
  3567. }
  3568. }
  3569.  
  3570.  
  3571. else if (strCommand == "getheaders")
  3572. {
  3573. CBlockLocator locator;
  3574. uint256 hashStop;
  3575. vRecv >> locator >> hashStop;
  3576.  
  3577. CBlockIndex* pindex = NULL;
  3578. if (locator.IsNull())
  3579. {
  3580. // If locator is null, return the hashStop block
  3581. map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
  3582. if (mi == mapBlockIndex.end())
  3583. return true;
  3584. pindex = (*mi).second;
  3585. }
  3586. else
  3587. {
  3588. // Find the last block the caller has in the main chain
  3589. pindex = locator.GetBlockIndex();
  3590. if (pindex)
  3591. pindex = pindex->pnext;
  3592. }
  3593.  
  3594. // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
  3595. vector<CBlock> vHeaders;
  3596. int nLimit = 2000;
  3597. printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str());
  3598. for (; pindex; pindex = pindex->pnext)
  3599. {
  3600. vHeaders.push_back(pindex->GetBlockHeader());
  3601. if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
  3602. break;
  3603. }
  3604. pfrom->PushMessage("headers", vHeaders);
  3605. }
  3606.  
  3607.  
  3608. else if (strCommand == "tx")
  3609. {
  3610. vector<uint256> vWorkQueue;
  3611. vector<uint256> vEraseQueue;
  3612. CDataStream vMsg(vRecv);
  3613. CTransaction tx;
  3614. vRecv >> tx;
  3615.  
  3616. CInv inv(MSG_TX, tx.GetHash());
  3617. pfrom->AddInventoryKnown(inv);
  3618.  
  3619. bool fMissingInputs = false;
  3620. CValidationState state;
  3621. if (tx.AcceptToMemoryPool(state, true, true, &fMissingInputs))
  3622. {
  3623. RelayTransaction(tx, inv.hash);
  3624. mapAlreadyAskedFor.erase(inv);
  3625. vWorkQueue.push_back(inv.hash);
  3626. vEraseQueue.push_back(inv.hash);
  3627.  
  3628. printf("AcceptToMemoryPool: %s %s : accepted %s (poolsz %"PRIszu")\n",
  3629. pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
  3630. tx.GetHash().ToString().c_str(),
  3631. mempool.mapTx.size());
  3632.  
  3633. // Recursively process any orphan transactions that depended on this one
  3634. for (unsigned int i = 0; i < vWorkQueue.size(); i++)
  3635. {
  3636. map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
  3637. if (itByPrev == mapOrphanTransactionsByPrev.end())
  3638. continue;
  3639. for (set<uint256>::iterator mi = itByPrev->second.begin();
  3640. mi != itByPrev->second.end();
  3641. ++mi)
  3642. {
  3643. const uint256& orphanHash = *mi;
  3644. const CTransaction& orphanTx = mapOrphanTransactions[orphanHash];
  3645. bool fMissingInputs2 = false;
  3646. // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
  3647. // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
  3648. // anyone relaying LegitTxX banned)
  3649. CValidationState stateDummy;
  3650.  
  3651. if (tx.AcceptToMemoryPool(stateDummy, true, true, &fMissingInputs2))
  3652. {
  3653. printf(" accepted orphan tx %s\n", orphanHash.ToString().c_str());
  3654. RelayTransaction(orphanTx, orphanHash);
  3655. mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanHash));
  3656. vWorkQueue.push_back(orphanHash);
  3657. vEraseQueue.push_back(orphanHash);
  3658. }
  3659. else if (!fMissingInputs2)
  3660. {
  3661. // invalid or too-little-fee orphan
  3662. vEraseQueue.push_back(orphanHash);
  3663. printf(" removed orphan tx %s\n", orphanHash.ToString().c_str());
  3664. }
  3665. }
  3666. }
  3667.  
  3668. BOOST_FOREACH(uint256 hash, vEraseQueue)
  3669. EraseOrphanTx(hash);
  3670. }
  3671. else if (fMissingInputs)
  3672. {
  3673. AddOrphanTx(tx);
  3674.  
  3675. // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
  3676. unsigned int nMaxOrphanTx = (unsigned int)std::max((int64)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
  3677. unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
  3678. if (nEvicted > 0)
  3679. printf("mapOrphan overflow, removed %u tx\n", nEvicted);
  3680. }
  3681. int nDoS = 0;
  3682. if (state.IsInvalid(nDoS))
  3683. {
  3684. printf("%s from %s %s was not accepted into the memory pool\n", tx.GetHash().ToString().c_str(),
  3685. pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str());
  3686. if (nDoS > 0)
  3687. pfrom->Misbehaving(nDoS);
  3688. }
  3689. }
  3690.  
  3691.  
  3692. else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
  3693. {
  3694. CBlock block;
  3695. vRecv >> block;
  3696.  
  3697. printf("received block %s\n", block.GetHash().ToString().c_str());
  3698. // block.print();
  3699.  
  3700. CInv inv(MSG_BLOCK, block.GetHash());
  3701. pfrom->AddInventoryKnown(inv);
  3702.  
  3703. CValidationState state;
  3704. if (ProcessBlock(state, pfrom, &block) || state.CorruptionPossible())
  3705. mapAlreadyAskedFor.erase(inv);
  3706. int nDoS = 0;
  3707. if (state.IsInvalid(nDoS))
  3708. if (nDoS > 0)
  3709. pfrom->Misbehaving(nDoS);
  3710. }
  3711.  
  3712.  
  3713. else if (strCommand == "getaddr")
  3714. {
  3715. pfrom->vAddrToSend.clear();
  3716. vector<CAddress> vAddr = addrman.GetAddr();
  3717. BOOST_FOREACH(const CAddress &addr, vAddr)
  3718. pfrom->PushAddress(addr);
  3719. }
  3720.  
  3721.  
  3722. else if (strCommand == "mempool")
  3723. {
  3724. std::vector<uint256> vtxid;
  3725. LOCK2(mempool.cs, pfrom->cs_filter);
  3726. mempool.queryHashes(vtxid);
  3727. vector<CInv> vInv;
  3728. BOOST_FOREACH(uint256& hash, vtxid) {
  3729. CInv inv(MSG_TX, hash);
  3730. if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(mempool.lookup(hash), hash)) ||
  3731. (!pfrom->pfilter))
  3732. vInv.push_back(inv);
  3733. if (vInv.size() == MAX_INV_SZ)
  3734. break;
  3735. }
  3736. if (vInv.size() > 0)
  3737. pfrom->PushMessage("inv", vInv);
  3738. }
  3739.  
  3740.  
  3741. else if (strCommand == "ping")
  3742. {
  3743. if (pfrom->nVersion > BIP0031_VERSION)
  3744. {
  3745. uint64 nonce = 0;
  3746. vRecv >> nonce;
  3747. // Echo the message back with the nonce. This allows for two useful features:
  3748. //
  3749. // 1) A remote node can quickly check if the connection is operational
  3750. // 2) Remote nodes can measure the latency of the network thread. If this node
  3751. // is overloaded it won't respond to pings quickly and the remote node can
  3752. // avoid sending us more work, like chain download requests.
  3753. //
  3754. // The nonce stops the remote getting confused between different pings: without
  3755. // it, if the remote node sends a ping once per second and this node takes 5
  3756. // seconds to respond to each, the 5th ping the remote sends would appear to
  3757. // return very quickly.
  3758. pfrom->PushMessage("pong", nonce);
  3759. }
  3760. }
  3761.  
  3762.  
  3763. else if (strCommand == "alert")
  3764. {
  3765. CAlert alert;
  3766. vRecv >> alert;
  3767.  
  3768. uint256 alertHash = alert.GetHash();
  3769. if (pfrom->setKnown.count(alertHash) == 0)
  3770. {
  3771. if (alert.ProcessAlert())
  3772. {
  3773. // Relay
  3774. pfrom->setKnown.insert(alertHash);
  3775. {
  3776. LOCK(cs_vNodes);
  3777. BOOST_FOREACH(CNode* pnode, vNodes)
  3778. alert.RelayTo(pnode);
  3779. }
  3780. }
  3781. else {
  3782. // Small DoS penalty so peers that send us lots of
  3783. // duplicate/expired/invalid-signature/whatever alerts
  3784. // eventually get banned.
  3785. // This isn't a Misbehaving(100) (immediate ban) because the
  3786. // peer might be an older or different implementation with
  3787. // a different signature key, etc.
  3788. pfrom->Misbehaving(10);
  3789. }
  3790. }
  3791. }
  3792.  
  3793.  
  3794. else if (!fBloomFilters &&
  3795. (strCommand == "filterload" ||
  3796. strCommand == "filteradd" ||
  3797. strCommand == "filterclear"))
  3798. {
  3799. pfrom->CloseSocketDisconnect();
  3800. return error("peer %s attempted to set a bloom filter even though we do not advertise that service",
  3801. pfrom->addr.ToString().c_str());
  3802. }
  3803.  
  3804. else if (strCommand == "filterload")
  3805. {
  3806. CBloomFilter filter;
  3807. vRecv >> filter;
  3808.  
  3809. if (!filter.IsWithinSizeConstraints())
  3810. // There is no excuse for sending a too-large filter
  3811. pfrom->Misbehaving(100);
  3812. else
  3813. {
  3814. LOCK(pfrom->cs_filter);
  3815. delete pfrom->pfilter;
  3816. pfrom->pfilter = new CBloomFilter(filter);
  3817. pfrom->pfilter->UpdateEmptyFull();
  3818. }
  3819. pfrom->fRelayTxes = true;
  3820. }
  3821.  
  3822.  
  3823. else if (strCommand == "filteradd")
  3824. {
  3825. vector<unsigned char> vData;
  3826. vRecv >> vData;
  3827.  
  3828. // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
  3829. // and thus, the maximum size any matched object can have) in a filteradd message
  3830. if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE)
  3831. {
  3832. pfrom->Misbehaving(100);
  3833. } else {
  3834. LOCK(pfrom->cs_filter);
  3835. if (pfrom->pfilter)
  3836. pfrom->pfilter->insert(vData);
  3837. else
  3838. pfrom->Misbehaving(100);
  3839. }
  3840. }
  3841.  
  3842.  
  3843. else if (strCommand == "filterclear")
  3844. {
  3845. LOCK(pfrom->cs_filter);
  3846. delete pfrom->pfilter;
  3847. pfrom->pfilter = new CBloomFilter();
  3848. pfrom->fRelayTxes = true;
  3849. }
  3850.  
  3851.  
  3852. else
  3853. {
  3854. // Ignore unknown commands for extensibility
  3855. }
  3856.  
  3857.  
  3858. // Update the last seen time for this node's address
  3859. if (pfrom->fNetworkNode)
  3860. if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
  3861. AddressCurrentlyConnected(pfrom->addr);
  3862.  
  3863.  
  3864. return true;
  3865. }
  3866.  
  3867. // requires LOCK(cs_vRecvMsg)
  3868. bool ProcessMessages(CNode* pfrom)
  3869. {
  3870. //if (fDebug)
  3871. // printf("ProcessMessages(%zu messages)\n", pfrom->vRecvMsg.size());
  3872.  
  3873. //
  3874. // Message format
  3875. // (4) message start
  3876. // (12) command
  3877. // (4) size
  3878. // (4) checksum
  3879. // (x) data
  3880. //
  3881. bool fOk = true;
  3882.  
  3883. if (!pfrom->vRecvGetData.empty())
  3884. ProcessGetData(pfrom);
  3885.  
  3886. // this maintains the order of responses
  3887. if (!pfrom->vRecvGetData.empty()) return fOk;
  3888.  
  3889. std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
  3890. while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
  3891. // Don't bother if send buffer is too full to respond anyway
  3892. if (pfrom->nSendSize >= SendBufferSize())
  3893. break;
  3894.  
  3895. // get next message
  3896. CNetMessage& msg = *it;
  3897.  
  3898. //if (fDebug)
  3899. // printf("ProcessMessages(message %u msgsz, %zu bytes, complete:%s)\n",
  3900. // msg.hdr.nMessageSize, msg.vRecv.size(),
  3901. // msg.complete() ? "Y" : "N");
  3902.  
  3903. // end, if an incomplete message is found
  3904. if (!msg.complete())
  3905. break;
  3906.  
  3907. // at this point, any failure means we can delete the current message
  3908. it++;
  3909.  
  3910. // Scan for message start
  3911. if (memcmp(msg.hdr.pchMessageStart, pchMessageStart, sizeof(pchMessageStart)) != 0) {
  3912. printf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n");
  3913. fOk = false;
  3914. break;
  3915. }
  3916.  
  3917. // Read header
  3918. CMessageHeader& hdr = msg.hdr;
  3919. if (!hdr.IsValid())
  3920. {
  3921. printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
  3922. continue;
  3923. }
  3924. string strCommand = hdr.GetCommand();
  3925.  
  3926. // Message size
  3927. unsigned int nMessageSize = hdr.nMessageSize;
  3928.  
  3929. // Checksum
  3930. CDataStream& vRecv = msg.vRecv;
  3931. uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
  3932. unsigned int nChecksum = 0;
  3933. memcpy(&nChecksum, &hash, sizeof(nChecksum));
  3934. if (nChecksum != hdr.nChecksum)
  3935. {
  3936. printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
  3937. strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
  3938. continue;
  3939. }
  3940.  
  3941. // Process message
  3942. bool fRet = false;
  3943. try
  3944. {
  3945. {
  3946. LOCK(cs_main);
  3947. fRet = ProcessMessage(pfrom, strCommand, vRecv);
  3948. }
  3949. boost::this_thread::interruption_point();
  3950. }
  3951. catch (std::ios_base::failure& e)
  3952. {
  3953. if (strstr(e.what(), "end of data"))
  3954. {
  3955. // Allow exceptions from under-length message on vRecv
  3956. 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());
  3957. }
  3958. else if (strstr(e.what(), "size too large"))
  3959. {
  3960. // Allow exceptions from over-long size
  3961. printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
  3962. }
  3963. else
  3964. {
  3965. PrintExceptionContinue(&e, "ProcessMessages()");
  3966. }
  3967. }
  3968. catch (boost::thread_interrupted) {
  3969. throw;
  3970. }
  3971. catch (std::exception& e) {
  3972. PrintExceptionContinue(&e, "ProcessMessages()");
  3973. } catch (...) {
  3974. PrintExceptionContinue(NULL, "ProcessMessages()");
  3975. }
  3976.  
  3977. if (!fRet)
  3978. printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
  3979.  
  3980. break;
  3981. }
  3982.  
  3983. // In case the connection got shut down, its receive buffer was wiped
  3984. if (!pfrom->fDisconnect)
  3985. pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
  3986.  
  3987. return fOk;
  3988. }
  3989.  
  3990.  
  3991. bool SendMessages(CNode* pto, bool fSendTrickle)
  3992. {
  3993. TRY_LOCK(cs_main, lockMain);
  3994. if (lockMain) {
  3995. // Don't send anything until we get their version message
  3996. if (pto->nVersion == 0)
  3997. return true;
  3998.  
  3999. // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
  4000. // right now.
  4001. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSendMsg.empty()) {
  4002. uint64 nonce = 0;
  4003. if (pto->nVersion > BIP0031_VERSION)
  4004. pto->PushMessage("ping", nonce);
  4005. else
  4006. pto->PushMessage("ping");
  4007. }
  4008.  
  4009. // Start block sync
  4010. if (pto->fStartSync && !fImporting && !fReindex) {
  4011. pto->fStartSync = false;
  4012. pto->PushGetBlocks(pindexBest, uint256(0));
  4013. }
  4014.  
  4015. // Resend wallet transactions that haven't gotten in a block yet
  4016. // Except during reindex, importing and IBD, when old wallet
  4017. // transactions become unconfirmed and spams other nodes.
  4018. if (!fReindex && !fImporting && !IsInitialBlockDownload())
  4019. {
  4020. ResendWalletTransactions();
  4021. }
  4022.  
  4023. // Address refresh broadcast
  4024. static int64 nLastRebroadcast;
  4025. if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
  4026. {
  4027. {
  4028. LOCK(cs_vNodes);
  4029. BOOST_FOREACH(CNode* pnode, vNodes)
  4030. {
  4031. // Periodically clear setAddrKnown to allow refresh broadcasts
  4032. if (nLastRebroadcast)
  4033. pnode->setAddrKnown.clear();
  4034.  
  4035. // Rebroadcast our address
  4036. if (!fNoListen)
  4037. {
  4038. CAddress addr = GetLocalAddress(&pnode->addr);
  4039. if (addr.IsRoutable())
  4040. pnode->PushAddress(addr);
  4041. }
  4042. }
  4043. }
  4044. nLastRebroadcast = GetTime();
  4045. }
  4046.  
  4047. //
  4048. // Message: addr
  4049. //
  4050. if (fSendTrickle)
  4051. {
  4052. vector<CAddress> vAddr;
  4053. vAddr.reserve(pto->vAddrToSend.size());
  4054. BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
  4055. {
  4056. // returns true if wasn't already contained in the set
  4057. if (pto->setAddrKnown.insert(addr).second)
  4058. {
  4059. vAddr.push_back(addr);
  4060. // receiver rejects addr messages larger than 1000
  4061. if (vAddr.size() >= 1000)
  4062. {
  4063. pto->PushMessage("addr", vAddr);
  4064. vAddr.clear();
  4065. }
  4066. }
  4067. }
  4068. pto->vAddrToSend.clear();
  4069. if (!vAddr.empty())
  4070. pto->PushMessage("addr", vAddr);
  4071. }
  4072.  
  4073.  
  4074. //
  4075. // Message: inventory
  4076. //
  4077. vector<CInv> vInv;
  4078. vector<CInv> vInvWait;
  4079. {
  4080. LOCK(pto->cs_inventory);
  4081. vInv.reserve(pto->vInventoryToSend.size());
  4082. vInvWait.reserve(pto->vInventoryToSend.size());
  4083. BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
  4084. {
  4085. if (pto->setInventoryKnown.count(inv))
  4086. continue;
  4087.  
  4088. // trickle out tx inv to protect privacy
  4089. if (inv.type == MSG_TX && !fSendTrickle)
  4090. {
  4091. // 1/4 of tx invs blast to all immediately
  4092. static uint256 hashSalt;
  4093. if (hashSalt == 0)
  4094. hashSalt = GetRandHash();
  4095. uint256 hashRand = inv.hash ^ hashSalt;
  4096. hashRand = Hash(BEGIN(hashRand), END(hashRand));
  4097. bool fTrickleWait = ((hashRand & 3) != 0);
  4098.  
  4099. // always trickle our own transactions
  4100. if (!fTrickleWait)
  4101. {
  4102. CWalletTx wtx;
  4103. if (GetTransaction(inv.hash, wtx))
  4104. if (wtx.fFromMe)
  4105. fTrickleWait = true;
  4106. }
  4107.  
  4108. if (fTrickleWait)
  4109. {
  4110. vInvWait.push_back(inv);
  4111. continue;
  4112. }
  4113. }
  4114.  
  4115. // returns true if wasn't already contained in the set
  4116. if (pto->setInventoryKnown.insert(inv).second)
  4117. {
  4118. vInv.push_back(inv);
  4119. if (vInv.size() >= 1000)
  4120. {
  4121. pto->PushMessage("inv", vInv);
  4122. vInv.clear();
  4123. }
  4124. }
  4125. }
  4126. pto->vInventoryToSend = vInvWait;
  4127. }
  4128. if (!vInv.empty())
  4129. pto->PushMessage("inv", vInv);
  4130.  
  4131.  
  4132. //
  4133. // Message: getdata
  4134. //
  4135. vector<CInv> vGetData;
  4136. int64 nNow = GetTime() * 1000000;
  4137. while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
  4138. {
  4139. const CInv& inv = (*pto->mapAskFor.begin()).second;
  4140. if (!AlreadyHave(inv))
  4141. {
  4142. if (fDebugNet)
  4143. printf("sending getdata: %s\n", inv.ToString().c_str());
  4144. vGetData.push_back(inv);
  4145. if (vGetData.size() >= 1000)
  4146. {
  4147. pto->PushMessage("getdata", vGetData);
  4148. vGetData.clear();
  4149. }
  4150. }
  4151. pto->mapAskFor.erase(pto->mapAskFor.begin());
  4152. }
  4153. if (!vGetData.empty())
  4154. pto->PushMessage("getdata", vGetData);
  4155.  
  4156. }
  4157. return true;
  4158. }
  4159.  
  4160.  
  4161.  
  4162.  
  4163.  
  4164.  
  4165.  
  4166.  
  4167.  
  4168.  
  4169.  
  4170.  
  4171.  
  4172.  
  4173. //////////////////////////////////////////////////////////////////////////////
  4174. //
  4175. // ShibacoinMiner
  4176. //
  4177.  
  4178. int static FormatHashBlocks(void* pbuffer, unsigned int len)
  4179. {
  4180. unsigned char* pdata = (unsigned char*)pbuffer;
  4181. unsigned int blocks = 1 + ((len + 8) / 64);
  4182. unsigned char* pend = pdata + 64 * blocks;
  4183. memset(pdata + len, 0, 64 * blocks - len);
  4184. pdata[len] = 0x80;
  4185. unsigned int bits = len * 8;
  4186. pend[-1] = (bits >> 0) & 0xff;
  4187. pend[-2] = (bits >> 8) & 0xff;
  4188. pend[-3] = (bits >> 16) & 0xff;
  4189. pend[-4] = (bits >> 24) & 0xff;
  4190. return blocks;
  4191. }
  4192.  
  4193. static const unsigned int pSHA256InitState[8] =
  4194. {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
  4195.  
  4196. void SHA256Transform(void* pstate, void* pinput, const void* pinit)
  4197. {
  4198. SHA256_CTX ctx;
  4199. unsigned char data[64];
  4200.  
  4201. SHA256_Init(&ctx);
  4202.  
  4203. for (int i = 0; i < 16; i++)
  4204. ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
  4205.  
  4206. for (int i = 0; i < 8; i++)
  4207. ctx.h[i] = ((uint32_t*)pinit)[i];
  4208.  
  4209. SHA256_Update(&ctx, data, sizeof(data));
  4210. for (int i = 0; i < 8; i++)
  4211. ((uint32_t*)pstate)[i] = ctx.h[i];
  4212. }
  4213.  
  4214. // Some explaining would be appreciated
  4215. class COrphan
  4216. {
  4217. public:
  4218. CTransaction* ptx;
  4219. set<uint256> setDependsOn;
  4220. double dPriority;
  4221. double dFeePerKb;
  4222.  
  4223. COrphan(CTransaction* ptxIn)
  4224. {
  4225. ptx = ptxIn;
  4226. dPriority = dFeePerKb = 0;
  4227. }
  4228.  
  4229. void print() const
  4230. {
  4231. printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
  4232. ptx->GetHash().ToString().c_str(), dPriority, dFeePerKb);
  4233. BOOST_FOREACH(uint256 hash, setDependsOn)
  4234. printf(" setDependsOn %s\n", hash.ToString().c_str());
  4235. }
  4236. };
  4237.  
  4238.  
  4239. uint64 nLastBlockTx = 0;
  4240. uint64 nLastBlockSize = 0;
  4241.  
  4242. // We want to sort transactions by priority and fee, so:
  4243. typedef boost::tuple<double, double, CTransaction*> TxPriority;
  4244. class TxPriorityCompare
  4245. {
  4246. bool byFee;
  4247. public:
  4248. TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
  4249. bool operator()(const TxPriority& a, const TxPriority& b)
  4250. {
  4251. if (byFee)
  4252. {
  4253. if (a.get<1>() == b.get<1>())
  4254. return a.get<0>() < b.get<0>();
  4255. return a.get<1>() < b.get<1>();
  4256. }
  4257. else
  4258. {
  4259. if (a.get<0>() == b.get<0>())
  4260. return a.get<1>() < b.get<1>();
  4261. return a.get<0>() < b.get<0>();
  4262. }
  4263. }
  4264. };
  4265.  
  4266. CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
  4267. {
  4268. // Create new block
  4269. auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
  4270. if(!pblocktemplate.get())
  4271. return NULL;
  4272. CBlock *pblock = &pblocktemplate->block; // pointer for convenience
  4273.  
  4274. // Create coinbase tx
  4275. CTransaction txNew;
  4276. txNew.vin.resize(1);
  4277. txNew.vin[0].prevout.SetNull();
  4278. txNew.vout.resize(1);
  4279. txNew.vout[0].scriptPubKey = scriptPubKeyIn;
  4280.  
  4281. // Add our coinbase tx as first transaction
  4282. pblock->vtx.push_back(txNew);
  4283. pblocktemplate->vTxFees.push_back(-1); // updated at end
  4284. pblocktemplate->vTxSigOps.push_back(-1); // updated at end
  4285.  
  4286. // Largest block you're willing to create:
  4287. unsigned int nBlockMaxSize = GetArg("-blockmaxsize", DEFAULT_BLOCK_MAX_SIZE);
  4288. // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
  4289. nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
  4290.  
  4291. // How much of the block should be dedicated to high-priority transactions,
  4292. // included regardless of the fees they pay
  4293. unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", DEFAULT_BLOCK_PRIORITY_SIZE);
  4294. nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
  4295.  
  4296. // Minimum block size you want to create; block will be filled with free transactions
  4297. // until there are no more or the block reaches this size:
  4298. unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
  4299. nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
  4300.  
  4301. // Collect memory pool transactions into the block
  4302. int64 nFees = 0;
  4303. {
  4304. LOCK2(cs_main, mempool.cs);
  4305. CBlockIndex* pindexPrev = pindexBest;
  4306. CCoinsViewCache view(*pcoinsTip, true);
  4307.  
  4308. // Priority order to process transactions
  4309. list<COrphan> vOrphan; // list memory doesn't move
  4310. map<uint256, vector<COrphan*> > mapDependers;
  4311. bool fPrintPriority = GetBoolArg("-printpriority");
  4312.  
  4313. // This vector will be sorted into a priority queue:
  4314. vector<TxPriority> vecPriority;
  4315. vecPriority.reserve(mempool.mapTx.size());
  4316. for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
  4317. {
  4318. CTransaction& tx = (*mi).second;
  4319. if (tx.IsCoinBase() || !tx.IsFinal())
  4320. continue;
  4321.  
  4322. COrphan* porphan = NULL;
  4323. double dPriority = 0;
  4324. int64 nTotalIn = 0;
  4325. bool fMissingInputs = false;
  4326. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  4327. {
  4328. // Read prev transaction
  4329. if (!view.HaveCoins(txin.prevout.hash))
  4330. {
  4331. // This should never happen; all transactions in the memory
  4332. // pool should connect to either transactions in the chain
  4333. // or other transactions in the memory pool.
  4334. if (!mempool.mapTx.count(txin.prevout.hash))
  4335. {
  4336. printf("ERROR: mempool transaction missing input\n");
  4337. if (fDebug) assert("mempool transaction missing input" == 0);
  4338. fMissingInputs = true;
  4339. if (porphan)
  4340. vOrphan.pop_back();
  4341. break;
  4342. }
  4343.  
  4344. // Has to wait for dependencies
  4345. if (!porphan)
  4346. {
  4347. // Use list for automatic deletion
  4348. vOrphan.push_back(COrphan(&tx));
  4349. porphan = &vOrphan.back();
  4350. }
  4351. mapDependers[txin.prevout.hash].push_back(porphan);
  4352. porphan->setDependsOn.insert(txin.prevout.hash);
  4353. nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
  4354. continue;
  4355. }
  4356. const CCoins &coins = view.GetCoins(txin.prevout.hash);
  4357.  
  4358. int64 nValueIn = coins.vout[txin.prevout.n].nValue;
  4359. nTotalIn += nValueIn;
  4360.  
  4361. int nConf = pindexPrev->nHeight - coins.nHeight + 1;
  4362.  
  4363. dPriority += (double)nValueIn * nConf;
  4364. }
  4365. if (fMissingInputs) continue;
  4366.  
  4367. // Priority is sum(valuein * age) / txsize
  4368. unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  4369. dPriority /= nTxSize;
  4370.  
  4371. // This is a more accurate fee-per-kilobyte than is used by the client code, because the
  4372. // client code rounds up the size to the nearest 1K. That's good, because it gives an
  4373. // incentive to create smaller transactions.
  4374. double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
  4375.  
  4376. if (porphan)
  4377. {
  4378. porphan->dPriority = dPriority;
  4379. porphan->dFeePerKb = dFeePerKb;
  4380. }
  4381. else
  4382. vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
  4383. }
  4384.  
  4385. // Collect transactions into block
  4386. uint64 nBlockSize = 1000;
  4387. uint64 nBlockTx = 0;
  4388. int nBlockSigOps = 100;
  4389. bool fSortedByFee = (nBlockPrioritySize <= 0);
  4390.  
  4391. TxPriorityCompare comparer(fSortedByFee);
  4392. std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
  4393.  
  4394. while (!vecPriority.empty())
  4395. {
  4396. // Take highest priority transaction off the priority queue:
  4397. double dPriority = vecPriority.front().get<0>();
  4398. double dFeePerKb = vecPriority.front().get<1>();
  4399. CTransaction& tx = *(vecPriority.front().get<2>());
  4400.  
  4401. std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
  4402. vecPriority.pop_back();
  4403.  
  4404. // Size limits
  4405. unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
  4406. if (nBlockSize + nTxSize >= nBlockMaxSize)
  4407. continue;
  4408.  
  4409. // Legacy limits on sigOps:
  4410. unsigned int nTxSigOps = tx.GetLegacySigOpCount();
  4411. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
  4412. continue;
  4413.  
  4414. // Skip free transactions if we're past the minimum block size:
  4415. if (fSortedByFee && (dFeePerKb < CTransaction::nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
  4416. continue;
  4417.  
  4418. // Prioritize by fee once past the priority size or we run out of high-priority
  4419. // transactions:
  4420. if (!fSortedByFee &&
  4421. ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 576 / 250)))
  4422. {
  4423. fSortedByFee = true;
  4424. comparer = TxPriorityCompare(fSortedByFee);
  4425. std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
  4426. }
  4427.  
  4428. if (!tx.HaveInputs(view))
  4429. continue;
  4430.  
  4431. int64 nTxFees = tx.GetValueIn(view)-tx.GetValueOut();
  4432.  
  4433. nTxSigOps += tx.GetP2SHSigOpCount(view);
  4434. if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
  4435. continue;
  4436.  
  4437. CValidationState state;
  4438. if (!tx.CheckInputs(state, view, true, SCRIPT_VERIFY_P2SH))
  4439. continue;
  4440.  
  4441. CTxUndo txundo;
  4442. uint256 hash = tx.GetHash();
  4443. tx.UpdateCoins(state, view, txundo, pindexPrev->nHeight+1, hash);
  4444.  
  4445. // Added
  4446. pblock->vtx.push_back(tx);
  4447. pblocktemplate->vTxFees.push_back(nTxFees);
  4448. pblocktemplate->vTxSigOps.push_back(nTxSigOps);
  4449. nBlockSize += nTxSize;
  4450. ++nBlockTx;
  4451. nBlockSigOps += nTxSigOps;
  4452. nFees += nTxFees;
  4453.  
  4454. if (fPrintPriority)
  4455. {
  4456. printf("priority %.1f feeperkb %.1f txid %s\n",
  4457. dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
  4458. }
  4459.  
  4460. // Add transactions that depend on this one to the priority queue
  4461. if (mapDependers.count(hash))
  4462. {
  4463. BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
  4464. {
  4465. if (!porphan->setDependsOn.empty())
  4466. {
  4467. porphan->setDependsOn.erase(hash);
  4468. if (porphan->setDependsOn.empty())
  4469. {
  4470. vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
  4471. std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
  4472. }
  4473. }
  4474. }
  4475. }
  4476. }
  4477.  
  4478. nLastBlockTx = nBlockTx;
  4479. nLastBlockSize = nBlockSize;
  4480. printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
  4481.  
  4482. pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
  4483. pblocktemplate->vTxFees[0] = -nFees;
  4484.  
  4485. // Fill in header
  4486. pblock->hashPrevBlock = pindexPrev->GetBlockHash();
  4487. pblock->UpdateTime(pindexPrev);
  4488. pblock->nBits = GetNextWorkRequired(pindexPrev, pblock);
  4489. pblock->nNonce = 0;
  4490. pblock->vtx[0].vin[0].scriptSig = CScript() << OP_0 << OP_0;
  4491. pblocktemplate->vTxSigOps[0] = pblock->vtx[0].GetLegacySigOpCount();
  4492.  
  4493. CBlockIndex indexDummy(*pblock);
  4494. indexDummy.pprev = pindexPrev;
  4495. indexDummy.nHeight = pindexPrev->nHeight + 1;
  4496. CCoinsViewCache viewNew(*pcoinsTip, true);
  4497. CValidationState state;
  4498. if (!pblock->ConnectBlock(state, &indexDummy, viewNew, true))
  4499. throw std::runtime_error("CreateNewBlock() : ConnectBlock failed");
  4500. }
  4501.  
  4502. return pblocktemplate.release();
  4503. }
  4504.  
  4505. CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey)
  4506. {
  4507. CPubKey pubkey;
  4508. if (!reservekey.GetReservedKey(pubkey))
  4509. return NULL;
  4510.  
  4511. CScript scriptPubKey = CScript() << pubkey << OP_CHECKSIG;
  4512. return CreateNewBlock(scriptPubKey);
  4513. }
  4514.  
  4515. void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
  4516. {
  4517. // Update nExtraNonce
  4518. static uint256 hashPrevBlock;
  4519. if (hashPrevBlock != pblock->hashPrevBlock)
  4520. {
  4521. nExtraNonce = 0;
  4522. hashPrevBlock = pblock->hashPrevBlock;
  4523. }
  4524. ++nExtraNonce;
  4525. unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
  4526. pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
  4527. assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
  4528.  
  4529. pblock->hashMerkleRoot = pblock->BuildMerkleTree();
  4530. }
  4531.  
  4532.  
  4533. void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
  4534. {
  4535. //
  4536. // Pre-build hash buffers
  4537. //
  4538. struct
  4539. {
  4540. struct unnamed2
  4541. {
  4542. int nVersion;
  4543. uint256 hashPrevBlock;
  4544. uint256 hashMerkleRoot;
  4545. unsigned int nTime;
  4546. unsigned int nBits;
  4547. unsigned int nNonce;
  4548. }
  4549. block;
  4550. unsigned char pchPadding0[64];
  4551. uint256 hash1;
  4552. unsigned char pchPadding1[64];
  4553. }
  4554. tmp;
  4555. memset(&tmp, 0, sizeof(tmp));
  4556.  
  4557. tmp.block.nVersion = pblock->nVersion;
  4558. tmp.block.hashPrevBlock = pblock->hashPrevBlock;
  4559. tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
  4560. tmp.block.nTime = pblock->nTime;
  4561. tmp.block.nBits = pblock->nBits;
  4562. tmp.block.nNonce = pblock->nNonce;
  4563.  
  4564. FormatHashBlocks(&tmp.block, sizeof(tmp.block));
  4565. FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
  4566.  
  4567. // Byte swap all the input buffer
  4568. for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
  4569. ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
  4570.  
  4571. // Precalc the first half of the first hash, which stays constant
  4572. SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
  4573.  
  4574. memcpy(pdata, &tmp.block, 128);
  4575. memcpy(phash1, &tmp.hash1, 64);
  4576. }
  4577.  
  4578.  
  4579. bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
  4580. {
  4581. uint256 hash = pblock->GetPoWHash();
  4582. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  4583.  
  4584. if (hash > hashTarget)
  4585. return false;
  4586.  
  4587. //// debug print
  4588. printf("ShibacoinMiner:\n");
  4589. printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
  4590. pblock->print();
  4591. printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
  4592.  
  4593. // Found a solution
  4594. {
  4595. LOCK(cs_main);
  4596. if (pblock->hashPrevBlock != hashBestChain)
  4597. return error("ShibacoinMiner : generated block is stale");
  4598.  
  4599. // Remove key from key pool
  4600. reservekey.KeepKey();
  4601.  
  4602. // Track how many getdata requests this block gets
  4603. {
  4604. LOCK(wallet.cs_wallet);
  4605. wallet.mapRequestCount[pblock->GetHash()] = 0;
  4606. }
  4607.  
  4608. // Process this block the same as if we had received it from another node
  4609. CValidationState state;
  4610. if (!ProcessBlock(state, NULL, pblock))
  4611. return error("ShibacoinMiner : ProcessBlock, block not accepted");
  4612. }
  4613.  
  4614. return true;
  4615. }
  4616.  
  4617. void static ShibacoinMiner(CWallet *pwallet)
  4618. {
  4619. printf("ShibacoinMiner started\n");
  4620. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  4621. RenameThread("shibacoin-miner");
  4622.  
  4623. // Each thread has its own key and counter
  4624. CReserveKey reservekey(pwallet);
  4625. unsigned int nExtraNonce = 0;
  4626.  
  4627. try { loop {
  4628. while (vNodes.empty())
  4629. MilliSleep(1000);
  4630.  
  4631. //
  4632. // Create new block
  4633. //
  4634. unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
  4635. CBlockIndex* pindexPrev = pindexBest;
  4636.  
  4637. auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
  4638. if (!pblocktemplate.get())
  4639. return;
  4640. CBlock *pblock = &pblocktemplate->block;
  4641. IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
  4642.  
  4643. printf("Running ShibacoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
  4644. ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
  4645.  
  4646. //
  4647. // Pre-build hash buffers
  4648. //
  4649. char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
  4650. char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
  4651. char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
  4652.  
  4653. FormatHashBuffers(pblock, pmidstate, pdata, phash1);
  4654.  
  4655. unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
  4656. unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
  4657. //unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
  4658.  
  4659.  
  4660. //
  4661. // Search
  4662. //
  4663. int64 nStart = GetTime();
  4664. uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  4665. loop
  4666. {
  4667. unsigned int nHashesDone = 0;
  4668.  
  4669. uint256 thash;
  4670. char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
  4671. loop
  4672. {
  4673. scrypt_1024_1_1_256_sp(BEGIN(pblock->nVersion), BEGIN(thash), scratchpad);
  4674.  
  4675. if (thash <= hashTarget)
  4676. {
  4677. // Found a solution
  4678. SetThreadPriority(THREAD_PRIORITY_NORMAL);
  4679. CheckWork(pblock, *pwallet, reservekey);
  4680. SetThreadPriority(THREAD_PRIORITY_LOWEST);
  4681. break;
  4682. }
  4683. pblock->nNonce += 1;
  4684. nHashesDone += 1;
  4685. if ((pblock->nNonce & 0xFF) == 0)
  4686. break;
  4687. }
  4688.  
  4689. // Meter hashes/sec
  4690. static int64 nHashCounter;
  4691. if (nHPSTimerStart == 0)
  4692. {
  4693. nHPSTimerStart = GetTimeMillis();
  4694. nHashCounter = 0;
  4695. }
  4696. else
  4697. nHashCounter += nHashesDone;
  4698. if (GetTimeMillis() - nHPSTimerStart > 4000)
  4699. {
  4700. static CCriticalSection cs;
  4701. {
  4702. LOCK(cs);
  4703. if (GetTimeMillis() - nHPSTimerStart > 4000)
  4704. {
  4705. dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
  4706. nHPSTimerStart = GetTimeMillis();
  4707. nHashCounter = 0;
  4708. static int64 nLogTime;
  4709. if (GetTime() - nLogTime > 30 * 60)
  4710. {
  4711. nLogTime = GetTime();
  4712. printf("hashmeter %6.0f khash/s\n", dHashesPerSec/1000.0);
  4713. }
  4714. }
  4715. }
  4716. }
  4717.  
  4718. // Check for stop or if block needs to be rebuilt
  4719. boost::this_thread::interruption_point();
  4720. if (vNodes.empty())
  4721. break;
  4722. if (pblock->nNonce >= 0xffff0000)
  4723. break;
  4724. if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
  4725. break;
  4726. if (pindexPrev != pindexBest)
  4727. break;
  4728.  
  4729. // Update nTime every few seconds
  4730. pblock->UpdateTime(pindexPrev);
  4731. nBlockTime = ByteReverse(pblock->nTime);
  4732. if (fTestNet)
  4733. {
  4734. // Changing pblock->nTime can change work required on testnet:
  4735. nBlockBits = ByteReverse(pblock->nBits);
  4736. hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
  4737. }
  4738. }
  4739. } }
  4740. catch (boost::thread_interrupted)
  4741. {
  4742. printf("ShibacoinMiner terminated\n");
  4743. throw;
  4744. }
  4745. }
  4746.  
  4747. void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
  4748. {
  4749. static boost::thread_group* minerThreads = NULL;
  4750.  
  4751. int nThreads = GetArg("-genproclimit", -1);
  4752. if (nThreads < 0)
  4753. nThreads = boost::thread::hardware_concurrency();
  4754.  
  4755. if (minerThreads != NULL)
  4756. {
  4757. minerThreads->interrupt_all();
  4758. delete minerThreads;
  4759. minerThreads = NULL;
  4760. }
  4761.  
  4762. if (nThreads == 0 || !fGenerate)
  4763. return;
  4764.  
  4765. minerThreads = new boost::thread_group();
  4766. for (int i = 0; i < nThreads; i++)
  4767. minerThreads->create_thread(boost::bind(&ShibacoinMiner, pwallet));
  4768. }
  4769.  
  4770. // Amount compression:
  4771. // * If the amount is 0, output 0
  4772. // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
  4773. // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
  4774. // * call the result n
  4775. // * output 1 + 10*(9*n + d - 1) + e
  4776. // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
  4777. // (this is decodable, as d is in [1-9] and e is in [0-9])
  4778.  
  4779. uint64 CTxOutCompressor::CompressAmount(uint64 n)
  4780. {
  4781. if (n == 0)
  4782. return 0;
  4783. int e = 0;
  4784. while (((n % 10) == 0) && e < 9) {
  4785. n /= 10;
  4786. e++;
  4787. }
  4788. if (e < 9) {
  4789. int d = (n % 10);
  4790. assert(d >= 1 && d <= 9);
  4791. n /= 10;
  4792. return 1 + (n*9 + d - 1)*10 + e;
  4793. } else {
  4794. return 1 + (n - 1)*10 + 9;
  4795. }
  4796. }
  4797.  
  4798. uint64 CTxOutCompressor::DecompressAmount(uint64 x)
  4799. {
  4800. // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
  4801. if (x == 0)
  4802. return 0;
  4803. x--;
  4804. // x = 10*(9*n + d - 1) + e
  4805. int e = x % 10;
  4806. x /= 10;
  4807. uint64 n = 0;
  4808. if (e < 9) {
  4809. // x = 9*n + d - 1
  4810. int d = (x % 9) + 1;
  4811. x /= 9;
  4812. // x = n
  4813. n = x*10 + d;
  4814. } else {
  4815. n = x+1;
  4816. }
  4817. while (e) {
  4818. n *= 10;
  4819. e--;
  4820. }
  4821. return n;
  4822. }
  4823.  
  4824.  
  4825. class CMainCleanup
  4826. {
  4827. public:
  4828. CMainCleanup() {}
  4829. ~CMainCleanup() {
  4830. // block headers
  4831. std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
  4832. for (; it1 != mapBlockIndex.end(); it1++)
  4833. delete (*it1).second;
  4834. mapBlockIndex.clear();
  4835.  
  4836. // orphan blocks
  4837. std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
  4838. for (; it2 != mapOrphanBlocks.end(); it2++)
  4839. delete (*it2).second;
  4840. mapOrphanBlocks.clear();
  4841.  
  4842. // orphan transactions
  4843. mapOrphanTransactions.clear();
  4844. }
  4845. } instance_of_cmaincleanup;
  4846.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement