1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 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.
7 #include "checkpoints.h"
11 #include "ui_interface.h"
13 #include "scrypt_mine.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
19 using namespace boost;
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
31 unsigned int nTransactionsUpdated = 0;
33 map<uint256, CBlockIndex*> mapBlockIndex;
34 set<pair<COutPoint, unsigned int> > setStakeSeen;
35 uint256 hashGenesisBlock = hashGenesisBlockOfficial;
36 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20);
37 static CBigNum bnProofOfStakeLimit(~uint256(0) >> 24);
38 static CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30);
39 static CBigNum bnInitialHashTarget(~uint256(0) >> 20);
40 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // minimum age for coin age
41 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // stake age of full weight
42 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute block spacing
43 int nCoinbaseMaturity = 500;
44 CBlockIndex* pindexGenesisBlock = NULL;
46 CBigNum bnBestChainTrust = 0;
47 CBigNum bnBestInvalidTrust = 0;
48 uint256 hashBestChain = 0;
49 CBlockIndex* pindexBest = NULL;
50 int64 nTimeBestReceived = 0;
52 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
54 map<uint256, CBlock*> mapOrphanBlocks;
55 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
56 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
57 map<uint256, uint256> mapProofOfStake;
59 map<uint256, CDataStream*> mapOrphanTransactions;
60 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
62 // Constant stuff for coinbase transactions we create:
63 CScript COINBASE_FLAGS;
65 const string strMessageMagic = "NovaCoin Signed Message:\n";
71 int64 nTransactionFee = MIN_TX_FEE;
74 //////////////////////////////////////////////////////////////////////////////
76 // dispatching functions
79 // These functions dispatch to one or all registered wallets
82 void RegisterWallet(CWallet* pwalletIn)
85 LOCK(cs_setpwalletRegistered);
86 setpwalletRegistered.insert(pwalletIn);
90 void UnregisterWallet(CWallet* pwalletIn)
93 LOCK(cs_setpwalletRegistered);
94 setpwalletRegistered.erase(pwalletIn);
98 // check whether the passed transaction is from us
99 bool static IsFromMe(CTransaction& tx)
101 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
102 if (pwallet->IsFromMe(tx))
107 // get the wallet transaction with the given hash (if it exists)
108 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
110 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
111 if (pwallet->GetTransaction(hashTx,wtx))
116 // erases transaction with the given hash from all wallets
117 void static EraseFromWallets(uint256 hash)
119 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
120 pwallet->EraseFromWallet(hash);
123 // make sure all wallets know about the given transaction, in the given block
124 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
128 // ppcoin: wallets need to refund inputs when disconnecting coinstake
129 if (tx.IsCoinStake())
131 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
132 if (pwallet->IsFromMe(tx))
133 pwallet->DisableTransaction(tx);
138 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
139 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
142 // notify wallets about a new best chain
143 void static SetBestChain(const CBlockLocator& loc)
145 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
146 pwallet->SetBestChain(loc);
149 // notify wallets about an updated transaction
150 void static UpdatedTransaction(const uint256& hashTx)
152 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
153 pwallet->UpdatedTransaction(hashTx);
157 void static PrintWallets(const CBlock& block)
159 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
160 pwallet->PrintWallet(block);
163 // notify wallets about an incoming inventory (for request counts)
164 void static Inventory(const uint256& hash)
166 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
167 pwallet->Inventory(hash);
170 // ask wallets to resend their transactions
171 void ResendWalletTransactions()
173 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
174 pwallet->ResendWalletTransactions();
183 //////////////////////////////////////////////////////////////////////////////
185 // mapOrphanTransactions
188 bool AddOrphanTx(const CDataStream& vMsg)
191 CDataStream(vMsg) >> tx;
192 uint256 hash = tx.GetHash();
193 if (mapOrphanTransactions.count(hash))
196 CDataStream* pvMsg = new CDataStream(vMsg);
198 // Ignore big transactions, to avoid a
199 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
200 // large transaction with a missing parent then we assume
201 // it will rebroadcast it later, after the parent transaction(s)
202 // have been mined or received.
203 // 10,000 orphans, each of which is at most 5,000 bytes big is
204 // at most 500 megabytes of orphans:
205 if (pvMsg->size() > 5000)
207 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
212 mapOrphanTransactions[hash] = pvMsg;
213 BOOST_FOREACH(const CTxIn& txin, tx.vin)
214 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
216 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
217 mapOrphanTransactions.size());
221 void static EraseOrphanTx(uint256 hash)
223 if (!mapOrphanTransactions.count(hash))
225 const CDataStream* pvMsg = mapOrphanTransactions[hash];
227 CDataStream(*pvMsg) >> tx;
228 BOOST_FOREACH(const CTxIn& txin, tx.vin)
230 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
231 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
232 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
235 mapOrphanTransactions.erase(hash);
238 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
240 unsigned int nEvicted = 0;
241 while (mapOrphanTransactions.size() > nMaxOrphans)
243 // Evict a random orphan:
244 uint256 randomhash = GetRandHash();
245 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
246 if (it == mapOrphanTransactions.end())
247 it = mapOrphanTransactions.begin();
248 EraseOrphanTx(it->first);
260 //////////////////////////////////////////////////////////////////////////////
262 // CTransaction and CTxIndex
265 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
268 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
270 if (!ReadFromDisk(txindexRet.pos))
272 if (prevout.n >= vout.size())
280 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
283 return ReadFromDisk(txdb, prevout, txindex);
286 bool CTransaction::ReadFromDisk(COutPoint prevout)
290 return ReadFromDisk(txdb, prevout, txindex);
293 bool CTransaction::IsStandard() const
295 if (nVersion > CTransaction::CURRENT_VERSION)
298 BOOST_FOREACH(const CTxIn& txin, vin)
300 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
301 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
302 // ~65-byte public keys, plus a few script ops.
303 if (txin.scriptSig.size() > 500)
305 if (!txin.scriptSig.IsPushOnly())
308 BOOST_FOREACH(const CTxOut& txout, vout) {
309 if (!::IsStandard(txout.scriptPubKey))
311 if (txout.nValue == 0)
318 // Check transaction inputs, and make sure any
319 // pay-to-script-hash transactions are evaluating IsStandard scripts
321 // Why bother? To avoid denial-of-service attacks; an attacker
322 // can submit a standard HASH... OP_EQUAL transaction,
323 // which will get accepted into blocks. The redemption
324 // script can be anything; an attacker could use a very
325 // expensive-to-check-upon-redemption script like:
326 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
328 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
331 return true; // Coinbases don't use vin normally
333 for (unsigned int i = 0; i < vin.size(); i++)
335 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
337 vector<vector<unsigned char> > vSolutions;
338 txnouttype whichType;
339 // get the scriptPubKey corresponding to this input:
340 const CScript& prevScript = prev.scriptPubKey;
341 if (!Solver(prevScript, whichType, vSolutions))
343 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
344 if (nArgsExpected < 0)
347 // Transactions with extra stuff in their scriptSigs are
348 // non-standard. Note that this EvalScript() call will
349 // be quick, because if there are any operations
350 // beside "push data" in the scriptSig the
351 // IsStandard() call returns false
352 vector<vector<unsigned char> > stack;
353 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
356 if (whichType == TX_SCRIPTHASH)
360 CScript subscript(stack.back().begin(), stack.back().end());
361 vector<vector<unsigned char> > vSolutions2;
362 txnouttype whichType2;
363 if (!Solver(subscript, whichType2, vSolutions2))
365 if (whichType2 == TX_SCRIPTHASH)
369 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
372 nArgsExpected += tmpExpected;
375 if (stack.size() != (unsigned int)nArgsExpected)
383 CTransaction::GetLegacySigOpCount() const
385 unsigned int nSigOps = 0;
386 BOOST_FOREACH(const CTxIn& txin, vin)
388 nSigOps += txin.scriptSig.GetSigOpCount(false);
390 BOOST_FOREACH(const CTxOut& txout, vout)
392 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
398 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
410 // Load the block this tx is in
412 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
414 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
419 // Update the tx's hashBlock
420 hashBlock = pblock->GetHash();
422 // Locate the transaction
423 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
424 if (pblock->vtx[nIndex] == *(CTransaction*)this)
426 if (nIndex == (int)pblock->vtx.size())
428 vMerkleBranch.clear();
430 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
434 // Fill in merkle branch
435 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
438 // Is the tx in a block that's in the main chain
439 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
440 if (mi == mapBlockIndex.end())
442 CBlockIndex* pindex = (*mi).second;
443 if (!pindex || !pindex->IsInMainChain())
446 return pindexBest->nHeight - pindex->nHeight + 1;
455 bool CTransaction::CheckTransaction() const
457 // Basic checks that don't depend on any context
459 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
461 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
463 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
464 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
466 // Check for negative or overflow output values
468 for (unsigned int i = 0; i < vout.size(); i++)
470 const CTxOut& txout = vout[i];
471 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
472 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
473 // ppcoin: enforce minimum output amount
474 if ((!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
475 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
476 if (txout.nValue > MAX_MONEY)
477 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
478 nValueOut += txout.nValue;
479 if (!MoneyRange(nValueOut))
480 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
483 // Check for duplicate inputs
484 set<COutPoint> vInOutPoints;
485 BOOST_FOREACH(const CTxIn& txin, vin)
487 if (vInOutPoints.count(txin.prevout))
489 vInOutPoints.insert(txin.prevout);
494 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
495 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
499 BOOST_FOREACH(const CTxIn& txin, vin)
500 if (txin.prevout.IsNull())
501 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
507 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
508 enum GetMinFee_mode mode) const
510 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
511 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
513 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
514 unsigned int nNewBlockSize = nBlockSize + nBytes;
515 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
521 // Transactions under 10K are free
522 // (about 4500 BTC if made of 50 BTC inputs)
528 // Free transaction area
529 if (nNewBlockSize < 27000)
534 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
535 if (nMinFee < nBaseFee)
537 BOOST_FOREACH(const CTxOut& txout, vout)
538 if (txout.nValue < CENT)
542 // Raise the price as the block approaches full
543 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
545 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
547 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
550 if (!MoneyRange(nMinFee))
556 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
557 bool* pfMissingInputs)
560 *pfMissingInputs = false;
562 if (!tx.CheckTransaction())
563 return error("CTxMemPool::accept() : CheckTransaction failed");
565 // Coinbase is only valid in a block, not as a loose transaction
567 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
569 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
570 if (tx.IsCoinStake())
571 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
573 // To help v0.1.5 clients who would see it as a negative number
574 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
575 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
577 // Rather not work on nonstandard transactions (unless -testnet)
578 if (!fTestNet && !tx.IsStandard())
579 return error("CTxMemPool::accept() : nonstandard transaction type");
581 // Do we already have it?
582 uint256 hash = tx.GetHash();
585 if (mapTx.count(hash))
589 if (txdb.ContainsTx(hash))
592 // Check for conflicts with in-memory transactions
593 CTransaction* ptxOld = NULL;
594 for (unsigned int i = 0; i < tx.vin.size(); i++)
596 COutPoint outpoint = tx.vin[i].prevout;
597 if (mapNextTx.count(outpoint))
599 // Disable replacement feature for now
602 // Allow replacing with a newer version of the same transaction
605 ptxOld = mapNextTx[outpoint].ptx;
606 if (ptxOld->IsFinal())
608 if (!tx.IsNewerThan(*ptxOld))
610 for (unsigned int i = 0; i < tx.vin.size(); i++)
612 COutPoint outpoint = tx.vin[i].prevout;
613 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
623 map<uint256, CTxIndex> mapUnused;
624 bool fInvalid = false;
625 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
628 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
630 *pfMissingInputs = true;
634 // Check for non-standard pay-to-script-hash in inputs
635 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
636 return error("CTxMemPool::accept() : nonstandard transaction input");
638 // Note: if you modify this code to accept non-standard transactions, then
639 // you should add code here to check that the transaction does a
640 // reasonable number of ECDSA signature verifications.
642 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
643 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
645 // Don't accept it if it can't get into a block
646 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY);
647 if (nFees < txMinFee)
648 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
649 hash.ToString().c_str(),
652 // Continuously rate-limit free transactions
653 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
654 // be annoying or make others' transactions take longer to confirm.
655 if (nFees < MIN_RELAY_TX_FEE)
657 static CCriticalSection cs;
658 static double dFreeCount;
659 static int64 nLastTime;
660 int64 nNow = GetTime();
664 // Use an exponentially decaying ~10-minute window:
665 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
667 // -limitfreerelay unit is thousand-bytes-per-minute
668 // At default rate it would take over a month to fill 1GB
669 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
670 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
672 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
677 // Check against previous transactions
678 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
679 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
681 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
685 // Store transaction in memory
690 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
693 addUnchecked(hash, tx);
696 ///// are we sure this is ok when loading transactions or restoring block txes
697 // If updated, erase old tx from wallet
699 EraseFromWallets(ptxOld->GetHash());
701 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
702 hash.ToString().substr(0,10).c_str(),
707 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
709 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
712 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
714 // Add to memory pool without checking anything. Don't call this directly,
715 // call CTxMemPool::accept to properly check the transaction first.
718 for (unsigned int i = 0; i < tx.vin.size(); i++)
719 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
720 nTransactionsUpdated++;
726 bool CTxMemPool::remove(CTransaction &tx)
728 // Remove transaction from memory pool
731 uint256 hash = tx.GetHash();
732 if (mapTx.count(hash))
734 BOOST_FOREACH(const CTxIn& txin, tx.vin)
735 mapNextTx.erase(txin.prevout);
737 nTransactionsUpdated++;
743 void CTxMemPool::clear()
748 ++nTransactionsUpdated;
751 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
756 vtxid.reserve(mapTx.size());
757 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
758 vtxid.push_back((*mi).first);
764 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
766 if (hashBlock == 0 || nIndex == -1)
769 // Find the block it claims to be in
770 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
771 if (mi == mapBlockIndex.end())
773 CBlockIndex* pindex = (*mi).second;
774 if (!pindex || !pindex->IsInMainChain())
777 // Make sure the merkle branch connects to this block
778 if (!fMerkleVerified)
780 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
782 fMerkleVerified = true;
786 return pindexBest->nHeight - pindex->nHeight + 1;
790 int CMerkleTx::GetBlocksToMaturity() const
792 if (!(IsCoinBase() || IsCoinStake()))
794 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
798 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
802 if (!IsInMainChain() && !ClientConnectInputs())
804 return CTransaction::AcceptToMemoryPool(txdb, false);
808 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
812 bool CMerkleTx::AcceptToMemoryPool()
815 return AcceptToMemoryPool(txdb);
820 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
825 // Add previous supporting transactions first
826 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
828 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
830 uint256 hash = tx.GetHash();
831 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
832 tx.AcceptToMemoryPool(txdb, fCheckInputs);
835 return AcceptToMemoryPool(txdb, fCheckInputs);
840 bool CWalletTx::AcceptWalletTransaction()
843 return AcceptWalletTransaction(txdb);
846 int CTxIndex::GetDepthInMainChain() const
850 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
852 // Find the block in the index
853 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
854 if (mi == mapBlockIndex.end())
856 CBlockIndex* pindex = (*mi).second;
857 if (!pindex || !pindex->IsInMainChain())
859 return 1 + nBestHeight - pindex->nHeight;
862 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
863 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
869 if (mempool.exists(hash))
871 tx = mempool.lookup(hash);
877 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
880 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
881 hashBlock = block.GetHash();
895 //////////////////////////////////////////////////////////////////////////////
897 // CBlock and CBlockIndex
900 static CBlockIndex* pblockindexFBBHLast;
901 CBlockIndex* FindBlockByHeight(int nHeight)
903 CBlockIndex *pblockindex;
904 if (nHeight < nBestHeight / 2)
905 pblockindex = pindexGenesisBlock;
907 pblockindex = pindexBest;
908 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
909 pblockindex = pblockindexFBBHLast;
910 while (pblockindex->nHeight > nHeight)
911 pblockindex = pblockindex->pprev;
912 while (pblockindex->nHeight < nHeight)
913 pblockindex = pblockindex->pnext;
914 pblockindexFBBHLast = pblockindex;
918 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
920 if (!fReadTransactions)
922 *this = pindex->GetBlockHeader();
925 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
927 if (GetHash() != pindex->GetBlockHash())
928 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
932 uint256 static GetOrphanRoot(const CBlock* pblock)
934 // Work back to the first block in the orphan chain
935 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
936 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
937 return pblock->GetHash();
940 // ppcoin: find block wanted by given orphan block
941 uint256 WantedByOrphan(const CBlock* pblockOrphan)
943 // Work back to the first block in the orphan chain
944 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
945 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
946 return pblockOrphan->hashPrevBlock;
949 int64 GetProofOfWorkReward(unsigned int nBits)
951 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
953 bnTarget.SetCompact(nBits);
954 CBigNum bnTargetLimit = bnProofOfWorkLimit;
955 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
957 // ppcoin: subsidy is cut in half every 64x multiply of difficulty
958 // A reasonably continuous curve is used to avoid shock to market
959 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
961 // Human readable form:
963 // nSubsidy = 100 / (diff ^ 1/6)
964 CBigNum bnLowerBound = CENT;
965 CBigNum bnUpperBound = bnSubsidyLimit;
966 while (bnLowerBound + CENT <= bnUpperBound)
968 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
969 if (fDebug && GetBoolArg("-printcreation"))
970 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
971 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
972 bnUpperBound = bnMidValue;
974 bnLowerBound = bnMidValue;
977 int64 nSubsidy = bnUpperBound.getuint64();
978 nSubsidy = (nSubsidy / CENT) * CENT;
979 if (fDebug && GetBoolArg("-printcreation"))
980 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
982 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
985 // ppcoin: miner's coin stake is rewarded based on coin age spent (coin-days)
986 int64 GetProofOfStakeReward(int64 nCoinAge)
988 static int64 nRewardCoinYear = 5 * CENT; // creation amount per coin-year
989 int64 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
990 if (fDebug && GetBoolArg("-printcreation"))
991 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nCoinAge);
995 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
996 static const int64 nTargetSpacingWorkMax = 12 * nStakeTargetSpacing; // 2-hour
999 // minimum amount of work that could possibly be required nTime after
1000 // minimum work required was nBase
1002 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1004 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1007 bnResult.SetCompact(nBase);
1009 while (nTime > 0 && bnResult < bnTargetLimit)
1011 // Maximum 200% adjustment per day...
1013 nTime -= 24 * 60 * 60;
1015 if (bnResult > bnTargetLimit)
1016 bnResult = bnTargetLimit;
1017 return bnResult.GetCompact();
1020 // ppcoin: find last block index up to pindex
1021 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1023 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1024 pindex = pindex->pprev;
1028 unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1030 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1034 // Proof-of-Stake blocks has own target limit since nVersion=3 supermajority on mainNet and always on testNet
1036 bnTargetLimit = bnProofOfStakeHardLimit;
1039 if(fTestNet || (pindexLast->nHeight + 1 > 15000))
1040 bnTargetLimit = bnProofOfStakeLimit;
1041 else if(pindexLast->nHeight + 1 > 14060)
1042 bnTargetLimit = bnProofOfStakeHardLimit;
1046 if (pindexLast == NULL)
1047 return bnTargetLimit.GetCompact(); // genesis block
1049 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1050 if (pindexPrev->pprev == NULL)
1051 return bnInitialHashTarget.GetCompact(); // first block
1052 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1053 if (pindexPrevPrev->pprev == NULL)
1054 return bnInitialHashTarget.GetCompact(); // second block
1056 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1058 // ppcoin: target change every block
1059 // ppcoin: retarget with exponential moving toward target spacing
1061 bnNew.SetCompact(pindexPrev->nBits);
1062 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(nTargetSpacingWorkMax, (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1063 int64 nInterval = nTargetTimespan / nTargetSpacing;
1064 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1065 bnNew /= ((nInterval + 1) * nTargetSpacing);
1067 if (bnNew > bnTargetLimit)
1068 bnNew = bnTargetLimit;
1070 return bnNew.GetCompact();
1073 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1076 bnTarget.SetCompact(nBits);
1079 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1080 return error("CheckProofOfWork() : nBits below minimum work");
1082 // Check proof of work matches claimed amount
1083 if (hash > bnTarget.getuint256())
1084 return error("CheckProofOfWork() : hash doesn't match nBits");
1089 // Return maximum amount of blocks that other nodes claim to have
1090 int GetNumBlocksOfPeers()
1092 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1095 bool IsInitialBlockDownload()
1097 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1099 static int64 nLastUpdate;
1100 static CBlockIndex* pindexLastBest;
1101 if (pindexBest != pindexLastBest)
1103 pindexLastBest = pindexBest;
1104 nLastUpdate = GetTime();
1106 return (GetTime() - nLastUpdate < 10 &&
1107 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1110 void static InvalidChainFound(CBlockIndex* pindexNew)
1112 if (pindexNew->bnChainTrust > bnBestInvalidTrust)
1114 bnBestInvalidTrust = pindexNew->bnChainTrust;
1115 CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust);
1116 uiInterface.NotifyBlocksChanged();
1119 printf("InvalidChainFound: invalid block=%s height=%d trust=%s date=%s\n",
1120 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1121 pindexNew->bnChainTrust.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S",
1122 pindexNew->GetBlockTime()).c_str());
1123 printf("InvalidChainFound: current best=%s height=%d trust=%s date=%s\n",
1124 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(),
1125 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1128 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1130 nTime = max(GetBlockTime(), GetAdjustedTime());
1143 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1145 // Relinquish previous transactions' spent pointers
1148 BOOST_FOREACH(const CTxIn& txin, vin)
1150 COutPoint prevout = txin.prevout;
1152 // Get prev txindex from disk
1154 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1155 return error("DisconnectInputs() : ReadTxIndex failed");
1157 if (prevout.n >= txindex.vSpent.size())
1158 return error("DisconnectInputs() : prevout.n out of range");
1160 // Mark outpoint as not spent
1161 txindex.vSpent[prevout.n].SetNull();
1164 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1165 return error("DisconnectInputs() : UpdateTxIndex failed");
1169 // Remove transaction from index
1170 // This can fail if a duplicate of this transaction was in a chain that got
1171 // reorganized away. This is only possible if this transaction was completely
1172 // spent, so erasing it would be a no-op anyway.
1173 txdb.EraseTxIndex(*this);
1179 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1180 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1182 // FetchInputs can return false either because we just haven't seen some inputs
1183 // (in which case the transaction should be stored as an orphan)
1184 // or because the transaction is malformed (in which case the transaction should
1185 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1189 return true; // Coinbase transactions have no inputs to fetch.
1191 for (unsigned int i = 0; i < vin.size(); i++)
1193 COutPoint prevout = vin[i].prevout;
1194 if (inputsRet.count(prevout.hash))
1195 continue; // Got it already
1198 CTxIndex& txindex = inputsRet[prevout.hash].first;
1200 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1202 // Get txindex from current proposed changes
1203 txindex = mapTestPool.find(prevout.hash)->second;
1207 // Read txindex from txdb
1208 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1210 if (!fFound && (fBlock || fMiner))
1211 return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1214 CTransaction& txPrev = inputsRet[prevout.hash].second;
1215 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1217 // Get prev tx from single transactions in memory
1220 if (!mempool.exists(prevout.hash))
1221 return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1222 txPrev = mempool.lookup(prevout.hash);
1225 txindex.vSpent.resize(txPrev.vout.size());
1229 // Get prev tx from disk
1230 if (!txPrev.ReadFromDisk(txindex.pos))
1231 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1235 // Make sure all prevout.n indexes are valid:
1236 for (unsigned int i = 0; i < vin.size(); i++)
1238 const COutPoint prevout = vin[i].prevout;
1239 assert(inputsRet.count(prevout.hash) != 0);
1240 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1241 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1242 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1244 // Revisit this if/when transaction replacement is implemented and allows
1247 return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
1254 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1256 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1257 if (mi == inputs.end())
1258 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1260 const CTransaction& txPrev = (mi->second).second;
1261 if (input.prevout.n >= txPrev.vout.size())
1262 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1264 return txPrev.vout[input.prevout.n];
1267 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1273 for (unsigned int i = 0; i < vin.size(); i++)
1275 nResult += GetOutputFor(vin[i], inputs).nValue;
1281 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1286 unsigned int nSigOps = 0;
1287 for (unsigned int i = 0; i < vin.size(); i++)
1289 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1290 if (prevout.scriptPubKey.IsPayToScriptHash())
1291 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1296 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1297 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1298 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1300 // Take over previous transactions' spent pointers
1301 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1302 // fMiner is true when called from the internal bitcoin miner
1303 // ... both are false when called from CTransaction::AcceptToMemoryPool
1308 for (unsigned int i = 0; i < vin.size(); i++)
1310 COutPoint prevout = vin[i].prevout;
1311 assert(inputs.count(prevout.hash) > 0);
1312 CTxIndex& txindex = inputs[prevout.hash].first;
1313 CTransaction& txPrev = inputs[prevout.hash].second;
1315 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1316 return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
1318 // If prev is coinbase or coinstake, check that it's matured
1319 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1320 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1321 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1322 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1324 // ppcoin: check transaction timestamp
1325 if (txPrev.nTime > nTime)
1326 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1328 // Check for negative or overflow input values
1329 nValueIn += txPrev.vout[prevout.n].nValue;
1330 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1331 return DoS(100, error("ConnectInputs() : txin values out of range"));
1334 // The first loop above does all the inexpensive checks.
1335 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1336 // Helps prevent CPU exhaustion attacks.
1337 for (unsigned int i = 0; i < vin.size(); i++)
1339 COutPoint prevout = vin[i].prevout;
1340 assert(inputs.count(prevout.hash) > 0);
1341 CTxIndex& txindex = inputs[prevout.hash].first;
1342 CTransaction& txPrev = inputs[prevout.hash].second;
1344 // Check for conflicts (double-spend)
1345 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1346 // for an attacker to attempt to split the network.
1347 if (!txindex.vSpent[prevout.n].IsNull())
1348 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
1350 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1351 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1352 // still computed and checked, and any change will be caught at the next checkpoint.
1353 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1356 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1358 // only during transition phase for P2SH: do not invoke anti-DoS code for
1359 // potentially old clients relaying bad P2SH transactions
1360 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1361 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1363 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1367 // Mark outpoints as spent
1368 txindex.vSpent[prevout.n] = posThisTx;
1371 if (fBlock || fMiner)
1373 mapTestPool[prevout.hash] = txindex;
1379 // ppcoin: coin stake tx earns reward instead of paying fee
1381 if (!GetCoinAge(txdb, nCoinAge))
1382 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1383 int64 nStakeReward = GetValueOut() - nValueIn;
1384 if (nStakeReward > GetProofOfStakeReward(nCoinAge) - GetMinFee() + MIN_TX_FEE)
1385 return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
1389 if (nValueIn < GetValueOut())
1390 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1392 // Tally transaction fees
1393 int64 nTxFee = nValueIn - GetValueOut();
1395 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1396 // ppcoin: enforce transaction fees for every block
1397 if (nTxFee < GetMinFee())
1398 return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false;
1401 if (!MoneyRange(nFees))
1402 return DoS(100, error("ConnectInputs() : nFees out of range"));
1410 bool CTransaction::ClientConnectInputs()
1415 // Take over previous transactions' spent pointers
1419 for (unsigned int i = 0; i < vin.size(); i++)
1421 // Get prev tx from single transactions in memory
1422 COutPoint prevout = vin[i].prevout;
1423 if (!mempool.exists(prevout.hash))
1425 CTransaction& txPrev = mempool.lookup(prevout.hash);
1427 if (prevout.n >= txPrev.vout.size())
1431 if (!VerifySignature(txPrev, *this, i, true, 0))
1432 return error("ConnectInputs() : VerifySignature failed");
1434 ///// this is redundant with the mempool.mapNextTx stuff,
1435 ///// not sure which I want to get rid of
1436 ///// this has to go away now that posNext is gone
1437 // // Check for conflicts
1438 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1439 // return error("ConnectInputs() : prev tx already used");
1441 // // Flag outpoints as used
1442 // txPrev.vout[prevout.n].posNext = posThisTx;
1444 nValueIn += txPrev.vout[prevout.n].nValue;
1446 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1447 return error("ClientConnectInputs() : txin values out of range");
1449 if (GetValueOut() > nValueIn)
1459 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1461 // Disconnect in reverse order
1462 for (int i = vtx.size()-1; i >= 0; i--)
1463 if (!vtx[i].DisconnectInputs(txdb))
1466 // Update block index on disk without changing it in memory.
1467 // The memory index structure will be changed after the db commits.
1470 CDiskBlockIndex blockindexPrev(pindex->pprev);
1471 blockindexPrev.hashNext = 0;
1472 if (!txdb.WriteBlockIndex(blockindexPrev))
1473 return error("DisconnectBlock() : WriteBlockIndex failed");
1476 // ppcoin: clean up wallet after disconnecting coinstake
1477 BOOST_FOREACH(CTransaction& tx, vtx)
1478 SyncWithWallets(tx, this, false, false);
1483 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1485 // Check it again in case a previous version let a bad block in
1486 if (!CheckBlock(!fJustCheck, !fJustCheck))
1489 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1490 // unless those are already completely spent.
1491 // If such overwrites are allowed, coinbases and transactions depending upon those
1492 // can be duplicated to remove the ability to spend the first instance -- even after
1493 // being sent to another address.
1494 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1495 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1496 // already refuses previously-known transaction ids entirely.
1497 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1498 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1499 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1500 // initial block download.
1501 bool fEnforceBIP30 = true; // Always active in NovaCoin
1502 bool fStrictPayToScriptHash = true; // Always active in NovaCoin
1504 //// issue here: it doesn't know the version
1505 unsigned int nTxPos;
1507 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1508 // Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from
1511 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1513 map<uint256, CTxIndex> mapQueuedChanges;
1516 int64 nValueOut = 0;
1517 unsigned int nSigOps = 0;
1518 BOOST_FOREACH(CTransaction& tx, vtx)
1520 uint256 hashTx = tx.GetHash();
1522 if (fEnforceBIP30) {
1523 CTxIndex txindexOld;
1524 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1525 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1531 nSigOps += tx.GetLegacySigOpCount();
1532 if (nSigOps > MAX_BLOCK_SIGOPS)
1533 return DoS(100, error("ConnectBlock() : too many sigops"));
1535 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1537 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1539 MapPrevTx mapInputs;
1540 if (tx.IsCoinBase())
1541 nValueOut += tx.GetValueOut();
1545 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1548 if (fStrictPayToScriptHash)
1550 // Add in sigops done by pay-to-script-hash inputs;
1551 // this is to prevent a "rogue miner" from creating
1552 // an incredibly-expensive-to-validate block.
1553 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1554 if (nSigOps > MAX_BLOCK_SIGOPS)
1555 return DoS(100, error("ConnectBlock() : too many sigops"));
1558 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1559 int64 nTxValueOut = tx.GetValueOut();
1560 nValueIn += nTxValueIn;
1561 nValueOut += nTxValueOut;
1562 if (!tx.IsCoinStake())
1563 nFees += nTxValueIn - nTxValueOut;
1565 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1569 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1572 // ppcoin: track money supply and mint amount info
1573 pindex->nMint = nValueOut - nValueIn + nFees;
1574 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1575 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1576 return error("Connect() : WriteBlockIndex for pindex failed");
1578 // ppcoin: fees are not collected by miners as in bitcoin
1579 // ppcoin: fees are destroyed to compensate the entire network
1580 if (fDebug && GetBoolArg("-printcreation"))
1581 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1586 // Write queued txindex changes
1587 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1589 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1590 return error("ConnectBlock() : UpdateTxIndex failed");
1593 // Update block index on disk without changing it in memory.
1594 // The memory index structure will be changed after the db commits.
1597 CDiskBlockIndex blockindexPrev(pindex->pprev);
1598 blockindexPrev.hashNext = pindex->GetBlockHash();
1599 if (!txdb.WriteBlockIndex(blockindexPrev))
1600 return error("ConnectBlock() : WriteBlockIndex failed");
1603 // Watch for transactions paying to me
1604 BOOST_FOREACH(CTransaction& tx, vtx)
1605 SyncWithWallets(tx, this, true);
1610 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1612 printf("REORGANIZE\n");
1615 CBlockIndex* pfork = pindexBest;
1616 CBlockIndex* plonger = pindexNew;
1617 while (pfork != plonger)
1619 while (plonger->nHeight > pfork->nHeight)
1620 if (!(plonger = plonger->pprev))
1621 return error("Reorganize() : plonger->pprev is null");
1622 if (pfork == plonger)
1624 if (!(pfork = pfork->pprev))
1625 return error("Reorganize() : pfork->pprev is null");
1628 // List of what to disconnect
1629 vector<CBlockIndex*> vDisconnect;
1630 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1631 vDisconnect.push_back(pindex);
1633 // List of what to connect
1634 vector<CBlockIndex*> vConnect;
1635 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1636 vConnect.push_back(pindex);
1637 reverse(vConnect.begin(), vConnect.end());
1639 printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
1640 printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
1642 // Disconnect shorter branch
1643 vector<CTransaction> vResurrect;
1644 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1647 if (!block.ReadFromDisk(pindex))
1648 return error("Reorganize() : ReadFromDisk for disconnect failed");
1649 if (!block.DisconnectBlock(txdb, pindex))
1650 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1652 // Queue memory transactions to resurrect
1653 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1654 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1655 vResurrect.push_back(tx);
1658 // Connect longer branch
1659 vector<CTransaction> vDelete;
1660 for (unsigned int i = 0; i < vConnect.size(); i++)
1662 CBlockIndex* pindex = vConnect[i];
1664 if (!block.ReadFromDisk(pindex))
1665 return error("Reorganize() : ReadFromDisk for connect failed");
1666 if (!block.ConnectBlock(txdb, pindex))
1669 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1672 // Queue memory transactions to delete
1673 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1674 vDelete.push_back(tx);
1676 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1677 return error("Reorganize() : WriteHashBestChain failed");
1679 // Make sure it's successfully written to disk before changing memory structure
1680 if (!txdb.TxnCommit())
1681 return error("Reorganize() : TxnCommit failed");
1683 // Disconnect shorter branch
1684 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1686 pindex->pprev->pnext = NULL;
1688 // Connect longer branch
1689 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1691 pindex->pprev->pnext = pindex;
1693 // Resurrect memory transactions that were in the disconnected branch
1694 BOOST_FOREACH(CTransaction& tx, vResurrect)
1695 tx.AcceptToMemoryPool(txdb, false);
1697 // Delete redundant memory transactions that are in the connected branch
1698 BOOST_FOREACH(CTransaction& tx, vDelete)
1701 printf("REORGANIZE: done\n");
1707 // Called from inside SetBestChain: attaches a block to the new best chain being built
1708 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1710 uint256 hash = GetHash();
1712 // Adding to current best branch
1713 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1716 InvalidChainFound(pindexNew);
1719 if (!txdb.TxnCommit())
1720 return error("SetBestChain() : TxnCommit failed");
1722 // Add to current best branch
1723 pindexNew->pprev->pnext = pindexNew;
1725 // Delete redundant memory transactions
1726 BOOST_FOREACH(CTransaction& tx, vtx)
1732 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1734 uint256 hash = GetHash();
1736 if (!txdb.TxnBegin())
1737 return error("SetBestChain() : TxnBegin failed");
1739 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1741 txdb.WriteHashBestChain(hash);
1742 if (!txdb.TxnCommit())
1743 return error("SetBestChain() : TxnCommit failed");
1744 pindexGenesisBlock = pindexNew;
1746 else if (hashPrevBlock == hashBestChain)
1748 if (!SetBestChainInner(txdb, pindexNew))
1749 return error("SetBestChain() : SetBestChainInner failed");
1753 // the first block in the new chain that will cause it to become the new best chain
1754 CBlockIndex *pindexIntermediate = pindexNew;
1756 // list of blocks that need to be connected afterwards
1757 std::vector<CBlockIndex*> vpindexSecondary;
1759 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1760 // Try to limit how much needs to be done inside
1761 while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust)
1763 vpindexSecondary.push_back(pindexIntermediate);
1764 pindexIntermediate = pindexIntermediate->pprev;
1767 if (!vpindexSecondary.empty())
1768 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1770 // Switch to new best branch
1771 if (!Reorganize(txdb, pindexIntermediate))
1774 InvalidChainFound(pindexNew);
1775 return error("SetBestChain() : Reorganize failed");
1778 // Connect further blocks
1779 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1782 if (!block.ReadFromDisk(pindex))
1784 printf("SetBestChain() : ReadFromDisk failed\n");
1787 if (!txdb.TxnBegin()) {
1788 printf("SetBestChain() : TxnBegin 2 failed\n");
1791 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1792 if (!block.SetBestChainInner(txdb, pindex))
1797 // Update best block in wallet (so we can detect restored wallets)
1798 bool fIsInitialDownload = IsInitialBlockDownload();
1799 if (!fIsInitialDownload)
1801 const CBlockLocator locator(pindexNew);
1802 ::SetBestChain(locator);
1806 hashBestChain = hash;
1807 pindexBest = pindexNew;
1808 pblockindexFBBHLast = NULL;
1809 nBestHeight = pindexBest->nHeight;
1810 bnBestChainTrust = pindexNew->bnChainTrust;
1811 nTimeBestReceived = GetTime();
1812 nTransactionsUpdated++;
1813 printf("SetBestChain: new best=%s height=%d trust=%s date=%s\n",
1814 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(),
1815 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1817 // Check the version of the last 100 blocks to see if we need to upgrade:
1818 if (!fIsInitialDownload)
1821 const CBlockIndex* pindex = pindexBest;
1822 for (int i = 0; i < 100 && pindex != NULL; i++)
1824 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1826 pindex = pindex->pprev;
1829 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1830 if (nUpgraded > 100/2)
1831 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1832 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1835 std::string strCmd = GetArg("-blocknotify", "");
1837 if (!fIsInitialDownload && !strCmd.empty())
1839 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1840 boost::thread t(runCommand, strCmd); // thread runs free
1846 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1847 // Only those coins meeting minimum age requirement counts. As those
1848 // transactions not in main chain are not currently indexed so we
1849 // might not find out about their coin age. Older transactions are
1850 // guaranteed to be in main chain by sync-checkpoint. This rule is
1851 // introduced to help nodes establish a consistent view of the coin
1852 // age (trust score) of competing branches.
1853 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1855 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1861 BOOST_FOREACH(const CTxIn& txin, vin)
1863 // First try finding the previous transaction in database
1864 CTransaction txPrev;
1866 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1867 continue; // previous transaction not in main chain
1868 if (nTime < txPrev.nTime)
1869 return false; // Transaction timestamp violation
1871 // Read block header
1873 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1874 return false; // unable to read block of previous transaction
1875 if (block.GetBlockTime() + nStakeMinAge > nTime)
1876 continue; // only count coins meeting min age requirement
1878 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1879 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1881 if (fDebug && GetBoolArg("-printcoinage"))
1882 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1885 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1886 if (fDebug && GetBoolArg("-printcoinage"))
1887 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1888 nCoinAge = bnCoinDay.getuint64();
1892 // ppcoin: total coin age spent in block, in the unit of coin-days.
1893 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1898 BOOST_FOREACH(const CTransaction& tx, vtx)
1901 if (tx.GetCoinAge(txdb, nTxCoinAge))
1902 nCoinAge += nTxCoinAge;
1907 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1909 if (fDebug && GetBoolArg("-printcoinage"))
1910 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1914 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1916 // Check for duplicate
1917 uint256 hash = GetHash();
1918 if (mapBlockIndex.count(hash))
1919 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1921 // Construct new block index object
1922 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1924 return error("AddToBlockIndex() : new CBlockIndex failed");
1925 pindexNew->phashBlock = &hash;
1926 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1927 if (miPrev != mapBlockIndex.end())
1929 pindexNew->pprev = (*miPrev).second;
1930 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1933 // ppcoin: compute chain trust score
1934 pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
1936 // ppcoin: compute stake entropy bit for stake modifier
1937 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
1938 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
1940 // ppcoin: record proof-of-stake hash value
1941 if (pindexNew->IsProofOfStake())
1943 if (!mapProofOfStake.count(hash))
1944 return error("AddToBlockIndex() : hashProofOfStake not found in map");
1945 pindexNew->hashProofOfStake = mapProofOfStake[hash];
1948 // ppcoin: compute stake modifier
1949 uint64 nStakeModifier = 0;
1950 bool fGeneratedStakeModifier = false;
1951 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
1952 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
1953 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
1954 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
1955 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
1956 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
1958 // Add to mapBlockIndex
1959 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1960 if (pindexNew->IsProofOfStake())
1961 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
1962 pindexNew->phashBlock = &((*mi).first);
1964 // Write to disk block index
1966 if (!txdb.TxnBegin())
1968 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1969 if (!txdb.TxnCommit())
1973 if (pindexNew->bnChainTrust > bnBestChainTrust)
1974 if (!SetBestChain(txdb, pindexNew))
1979 if (pindexNew == pindexBest)
1981 // Notify UI to display prev block's coinbase if it was ours
1982 static uint256 hashPrevBestCoinBase;
1983 UpdatedTransaction(hashPrevBestCoinBase);
1984 hashPrevBestCoinBase = vtx[0].GetHash();
1987 uiInterface.NotifyBlocksChanged();
1994 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
1996 // These are checks that are independent of context
1997 // that can be verified before saving an orphan block.
2000 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2001 return DoS(100, error("CheckBlock() : size limits failed"));
2003 // Check proof of work matches claimed amount
2004 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2005 return DoS(50, error("CheckBlock() : proof of work failed"));
2008 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
2009 return error("CheckBlock() : block timestamp too far in the future");
2011 // First transaction must be coinbase, the rest must not be
2012 if (vtx.empty() || !vtx[0].IsCoinBase())
2013 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2014 for (unsigned int i = 1; i < vtx.size(); i++)
2015 if (vtx[i].IsCoinBase())
2016 return DoS(100, error("CheckBlock() : more than one coinbase"));
2018 // ppcoin: only the second transaction can be the optional coinstake
2019 for (unsigned int i = 2; i < vtx.size(); i++)
2020 if (vtx[i].IsCoinStake())
2021 return DoS(100, error("CheckBlock() : coinstake in wrong position"));
2023 // ppcoin: coinbase output should be empty if proof-of-stake block
2024 if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty()))
2025 return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
2027 // Check coinbase timestamp
2028 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
2029 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2031 // Check coinstake timestamp
2032 if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2033 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2035 // Check coinbase reward
2036 if (vtx[0].GetValueOut() > (IsProofOfWork()? (GetProofOfWorkReward(nBits) - vtx[0].GetMinFee() + MIN_TX_FEE) : 0))
2037 return DoS(50, error("CheckBlock() : coinbase reward exceeded %s > %s",
2038 FormatMoney(vtx[0].GetValueOut()).c_str(),
2039 FormatMoney(IsProofOfWork()? GetProofOfWorkReward(nBits) : 0).c_str()));
2041 // Check transactions
2042 BOOST_FOREACH(const CTransaction& tx, vtx)
2044 if (!tx.CheckTransaction())
2045 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2047 // ppcoin: check transaction timestamp
2048 if (GetBlockTime() < (int64)tx.nTime)
2049 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2052 // Check for duplicate txids. This is caught by ConnectInputs(),
2053 // but catching it earlier avoids a potential DoS attack:
2054 set<uint256> uniqueTx;
2055 BOOST_FOREACH(const CTransaction& tx, vtx)
2057 uniqueTx.insert(tx.GetHash());
2059 if (uniqueTx.size() != vtx.size())
2060 return DoS(100, error("CheckBlock() : duplicate transaction"));
2062 unsigned int nSigOps = 0;
2063 BOOST_FOREACH(const CTransaction& tx, vtx)
2065 nSigOps += tx.GetLegacySigOpCount();
2067 if (nSigOps > MAX_BLOCK_SIGOPS)
2068 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2070 // Check merkle root
2071 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2072 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2074 // ppcoin: check block signature
2075 if (!CheckBlockSignature())
2076 return DoS(100, error("CheckBlock() : bad block signature"));
2081 bool CBlock::AcceptBlock()
2083 // Check for duplicate
2084 uint256 hash = GetHash();
2085 if (mapBlockIndex.count(hash))
2086 return error("AcceptBlock() : block already in mapBlockIndex");
2088 // Get prev block index
2089 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2090 if (mi == mapBlockIndex.end())
2091 return DoS(10, error("AcceptBlock() : prev block not found"));
2092 CBlockIndex* pindexPrev = (*mi).second;
2093 int nHeight = pindexPrev->nHeight+1;
2095 // Check proof-of-work or proof-of-stake
2096 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2097 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2099 // Check timestamp against prev
2100 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
2101 return error("AcceptBlock() : block's timestamp is too early");
2103 // Check that all transactions are finalized
2104 BOOST_FOREACH(const CTransaction& tx, vtx)
2105 if (!tx.IsFinal(nHeight, GetBlockTime()))
2106 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2108 // Check that the block chain matches the known block chain up to a checkpoint
2109 if (!Checkpoints::CheckHardened(nHeight, hash))
2110 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2112 // ppcoin: check that the block satisfies synchronized checkpoint
2113 if (!Checkpoints::CheckSync(hash, pindexPrev))
2114 return error("AcceptBlock() : rejected by synchronized checkpoint");
2116 // Reject block.nVersion < 3 blocks since 95% threshold on mainNet and always on testNet:
2117 if (nVersion < 3 && ((!fTestNet && nHeight > 14060) || (fTestNet && nHeight > 0)))
2118 return error("CheckBlock() : rejected nVersion < 3 block");
2120 // Enforce rule that the coinbase starts with serialized block height
2121 CScript expect = CScript() << nHeight;
2122 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2123 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2125 // Write block to history file
2126 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2127 return error("AcceptBlock() : out of disk space");
2128 unsigned int nFile = -1;
2129 unsigned int nBlockPos = 0;
2130 if (!WriteToDisk(nFile, nBlockPos))
2131 return error("AcceptBlock() : WriteToDisk failed");
2132 if (!AddToBlockIndex(nFile, nBlockPos))
2133 return error("AcceptBlock() : AddToBlockIndex failed");
2135 // Relay inventory, but don't relay old inventory during initial block download
2136 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2137 if (hashBestChain == hash)
2140 BOOST_FOREACH(CNode* pnode, vNodes)
2141 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2142 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2145 // ppcoin: check pending sync-checkpoint
2146 Checkpoints::AcceptPendingSyncCheckpoint();
2151 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2153 unsigned int nFound = 0;
2154 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2156 if (pstart->nVersion >= minVersion)
2158 pstart = pstart->pprev;
2160 return (nFound >= nRequired);
2163 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2165 // Check for duplicate
2166 uint256 hash = pblock->GetHash();
2167 if (mapBlockIndex.count(hash))
2168 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2169 if (mapOrphanBlocks.count(hash))
2170 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2172 // ppcoin: check proof-of-stake
2173 // Limited duplicity on stake: prevents block flood attack
2174 // Duplicate stake allowed only when there is orphan child block
2175 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2176 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
2178 // Preliminary checks
2179 if (!pblock->CheckBlock())
2180 return error("ProcessBlock() : CheckBlock FAILED");
2182 // ppcoin: verify hash target and signature of coinstake tx
2183 if (pblock->IsProofOfStake())
2185 uint256 hashProofOfStake = 0;
2186 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake))
2188 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2189 return false; // do not error here as we expect this during initial block download
2191 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2192 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2195 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2196 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2198 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2199 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2201 bnNewBlock.SetCompact(pblock->nBits);
2203 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime));
2204 if (bnNewBlock > bnRequired)
2207 pfrom->Misbehaving(100);
2208 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2212 // ppcoin: ask for pending sync-checkpoint if any
2213 if (!IsInitialBlockDownload())
2214 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2216 // If don't already have its previous block, shunt it off to holding area until we get it
2217 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2219 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2220 CBlock* pblock2 = new CBlock(*pblock);
2221 // ppcoin: check proof-of-stake
2222 if (pblock2->IsProofOfStake())
2224 // Limited duplicity on stake: prevents block flood attack
2225 // Duplicate stake allowed only when there is orphan child block
2226 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2227 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock2->GetProofOfStake().first.ToString().c_str(), pblock2->GetProofOfStake().second, hash.ToString().c_str());
2229 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2231 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2232 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2234 // Ask this guy to fill in what we're missing
2237 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2238 // ppcoin: getblocks may not obtain the ancestor block rejected
2239 // earlier by duplicate-stake check so we ask for it again directly
2240 if (!IsInitialBlockDownload())
2241 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2247 if (!pblock->AcceptBlock())
2248 return error("ProcessBlock() : AcceptBlock FAILED");
2250 // Recursively process any orphan blocks that depended on this one
2251 vector<uint256> vWorkQueue;
2252 vWorkQueue.push_back(hash);
2253 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2255 uint256 hashPrev = vWorkQueue[i];
2256 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2257 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2260 CBlock* pblockOrphan = (*mi).second;
2261 if (pblockOrphan->AcceptBlock())
2262 vWorkQueue.push_back(pblockOrphan->GetHash());
2263 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2264 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2265 delete pblockOrphan;
2267 mapOrphanBlocksByPrev.erase(hashPrev);
2270 printf("ProcessBlock: ACCEPTED\n");
2272 // ppcoin: if responsible for sync-checkpoint send it
2273 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2274 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2279 // ppcoin: sign block
2280 bool CBlock::SignBlock(const CKeyStore& keystore)
2282 vector<valtype> vSolutions;
2283 txnouttype whichType;
2285 if(!IsProofOfStake())
2287 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2289 const CTxOut& txout = vtx[0].vout[i];
2291 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2294 if (whichType == TX_PUBKEY)
2297 valtype& vchPubKey = vSolutions[0];
2300 if (!keystore.GetKey(Hash160(vchPubKey), key))
2302 if (key.GetPubKey() != vchPubKey)
2304 if(!key.Sign(GetHash(), vchBlockSig))
2313 const CTxOut& txout = vtx[1].vout[1];
2315 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2318 if (whichType == TX_PUBKEY)
2321 valtype& vchPubKey = vSolutions[0];
2324 if (!keystore.GetKey(Hash160(vchPubKey), key))
2326 if (key.GetPubKey() != vchPubKey)
2329 return key.Sign(GetHash(), vchBlockSig);
2333 printf("Sign failed\n");
2337 // ppcoin: check block signature
2338 bool CBlock::CheckBlockSignature() const
2340 if (GetHash() == hashGenesisBlock)
2341 return vchBlockSig.empty();
2343 vector<valtype> vSolutions;
2344 txnouttype whichType;
2346 if(IsProofOfStake())
2348 const CTxOut& txout = vtx[1].vout[1];
2350 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2352 if (whichType == TX_PUBKEY)
2354 valtype& vchPubKey = vSolutions[0];
2356 if (!key.SetPubKey(vchPubKey))
2358 if (vchBlockSig.empty())
2360 return key.Verify(GetHash(), vchBlockSig);
2365 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2367 const CTxOut& txout = vtx[0].vout[i];
2369 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2372 if (whichType == TX_PUBKEY)
2375 valtype& vchPubKey = vSolutions[0];
2377 if (!key.SetPubKey(vchPubKey))
2379 if (vchBlockSig.empty())
2381 if(!key.Verify(GetHash(), vchBlockSig))
2391 bool CheckDiskSpace(uint64 nAdditionalBytes)
2393 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2395 // Check for nMinDiskSpace bytes (currently 50MB)
2396 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2399 string strMessage = _("Warning: Disk space is low!");
2400 strMiscWarning = strMessage;
2401 printf("*** %s\n", strMessage.c_str());
2402 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2409 static filesystem::path BlockFilePath(unsigned int nFile)
2411 string strBlockFn = strprintf("blk%04u.dat", nFile);
2412 return GetDataDir() / strBlockFn;
2415 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2417 if ((nFile < 1) || (nFile == (unsigned int) -1))
2419 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2422 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2424 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2433 static unsigned int nCurrentBlockFile = 1;
2435 FILE* AppendBlockFile(unsigned int& nFileRet)
2440 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2443 if (fseek(file, 0, SEEK_END) != 0)
2445 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2446 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2448 nFileRet = nCurrentBlockFile;
2452 nCurrentBlockFile++;
2456 bool LoadBlockIndex(bool fAllowNew)
2460 pchMessageStart[0] = 0xcd;
2461 pchMessageStart[1] = 0xf2;
2462 pchMessageStart[2] = 0xc0;
2463 pchMessageStart[3] = 0xef;
2466 hashGenesisBlock = hashGenesisBlockTestNet;
2467 nStakeMinAge = 60 * 60 * 24; // test net min age is 1 day
2468 nCoinbaseMaturity = 60;
2475 if (!txdb.LoadBlockIndex())
2480 // Init with genesis block
2482 if (mapBlockIndex.empty())
2488 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
2489 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2490 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
2491 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
2492 // vMerkleTree: 4a5e1e
2495 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2497 txNew.nTime = 1360105017;
2498 txNew.vin.resize(1);
2499 txNew.vout.resize(1);
2500 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2501 txNew.vout[0].SetEmpty();
2503 block.vtx.push_back(txNew);
2504 block.hashPrevBlock = 0;
2505 block.hashMerkleRoot = block.BuildMerkleTree();
2507 block.nTime = 1360105017;
2508 block.nBits = bnProofOfWorkLimit.GetCompact();
2509 block.nNonce = 1575379;
2512 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2514 assert(block.GetHash() == hashGenesisBlock);
2515 assert(block.CheckBlock());
2517 // Start new block file
2519 unsigned int nBlockPos;
2520 if (!block.WriteToDisk(nFile, nBlockPos))
2521 return error("LoadBlockIndex() : writing genesis block to disk failed");
2522 if (!block.AddToBlockIndex(nFile, nBlockPos))
2523 return error("LoadBlockIndex() : genesis block not accepted");
2525 // ppcoin: initialize synchronized checkpoint
2526 if (!Checkpoints::WriteSyncCheckpoint(hashGenesisBlock))
2527 return error("LoadBlockIndex() : failed to init sync checkpoint");
2530 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2533 string strPubKey = "";
2534 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2536 // write checkpoint master key to db
2538 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2539 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2540 if (!txdb.TxnCommit())
2541 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2542 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2543 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2553 void PrintBlockTree()
2555 // pre-compute tree structure
2556 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2557 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2559 CBlockIndex* pindex = (*mi).second;
2560 mapNext[pindex->pprev].push_back(pindex);
2562 //while (rand() % 3 == 0)
2563 // mapNext[pindex->pprev].push_back(pindex);
2566 vector<pair<int, CBlockIndex*> > vStack;
2567 vStack.push_back(make_pair(0, pindexGenesisBlock));
2570 while (!vStack.empty())
2572 int nCol = vStack.back().first;
2573 CBlockIndex* pindex = vStack.back().second;
2576 // print split or gap
2577 if (nCol > nPrevCol)
2579 for (int i = 0; i < nCol-1; i++)
2583 else if (nCol < nPrevCol)
2585 for (int i = 0; i < nCol; i++)
2592 for (int i = 0; i < nCol; i++)
2597 block.ReadFromDisk(pindex);
2598 printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
2602 block.GetHash().ToString().c_str(),
2604 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2605 FormatMoney(pindex->nMint).c_str(),
2608 PrintWallets(block);
2610 // put the main time-chain first
2611 vector<CBlockIndex*>& vNext = mapNext[pindex];
2612 for (unsigned int i = 0; i < vNext.size(); i++)
2614 if (vNext[i]->pnext)
2616 swap(vNext[0], vNext[i]);
2622 for (unsigned int i = 0; i < vNext.size(); i++)
2623 vStack.push_back(make_pair(nCol+i, vNext[i]));
2627 bool LoadExternalBlockFile(FILE* fileIn)
2629 int64 nStart = GetTimeMillis();
2635 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2636 unsigned int nPos = 0;
2637 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2639 unsigned char pchData[65536];
2641 fseek(blkdat, nPos, SEEK_SET);
2642 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2645 nPos = (unsigned int)-1;
2648 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2651 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2653 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2656 nPos += ((unsigned char*)nFind - pchData) + 1;
2659 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2660 } while(!fRequestShutdown);
2661 if (nPos == (unsigned int)-1)
2663 fseek(blkdat, nPos, SEEK_SET);
2666 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2670 if (ProcessBlock(NULL,&block))
2678 catch (std::exception &e) {
2679 printf("%s() : Deserialize or I/O error caught during load\n",
2680 __PRETTY_FUNCTION__);
2683 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2695 //////////////////////////////////////////////////////////////////////////////
2700 extern map<uint256, CAlert> mapAlerts;
2701 extern CCriticalSection cs_mapAlerts;
2703 static string strMintMessage = "Info: Minting suspended due to locked wallet.";
2704 static string strMintWarning;
2706 string GetWarnings(string strFor)
2709 string strStatusBar;
2712 if (GetBoolArg("-testsafemode"))
2715 // ppcoin: wallet lock warning for minting
2716 if (strMintWarning != "")
2719 strStatusBar = strMintWarning;
2723 // Misc warnings like out of disk space and clock is wrong
2724 if (strMiscWarning != "")
2727 strStatusBar = strMiscWarning;
2730 // ppcoin: should not enter safe mode for longer invalid chain
2731 // ppcoin: if sync-checkpoint is too old do not enter safe mode
2732 if (Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) && !fTestNet && !IsInitialBlockDownload())
2735 strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.";
2738 // ppcoin: if detected invalid checkpoint enter safe mode
2739 if (Checkpoints::hashInvalidCheckpoint != 0)
2742 strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.";
2748 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2750 const CAlert& alert = item.second;
2751 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2753 nPriority = alert.nPriority;
2754 strStatusBar = alert.strStatusBar;
2755 if (nPriority > 1000)
2756 strRPC = strStatusBar; // ppcoin: safe mode for high alert
2761 if (strFor == "statusbar")
2762 return strStatusBar;
2763 else if (strFor == "rpc")
2765 assert(!"GetWarnings() : invalid parameter");
2776 //////////////////////////////////////////////////////////////////////////////
2782 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2788 bool txInMap = false;
2791 txInMap = (mempool.exists(inv.hash));
2794 mapOrphanTransactions.count(inv.hash) ||
2795 txdb.ContainsTx(inv.hash);
2799 return mapBlockIndex.count(inv.hash) ||
2800 mapOrphanBlocks.count(inv.hash);
2802 // Don't know what it is, just say we already got one
2809 // The message start string is designed to be unlikely to occur in normal data.
2810 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
2811 // a large 4-byte int at any alignment.
2812 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
2814 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2816 static map<CService, CPubKey> mapReuseKey;
2817 RandAddSeedPerfmon();
2819 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
2820 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2822 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2830 if (strCommand == "version")
2832 // Each connection can only send one version message
2833 if (pfrom->nVersion != 0)
2835 pfrom->Misbehaving(1);
2843 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2844 if (pfrom->nVersion < MIN_PROTO_VERSION)
2846 // Since February 20, 2012, the protocol is initiated at version 209,
2847 // and earlier versions are no longer supported
2848 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2849 pfrom->fDisconnect = true;
2853 if (pfrom->nVersion == 10300)
2854 pfrom->nVersion = 300;
2856 vRecv >> addrFrom >> nNonce;
2858 vRecv >> pfrom->strSubVer;
2860 vRecv >> pfrom->nStartingHeight;
2862 if (pfrom->fInbound && addrMe.IsRoutable())
2864 pfrom->addrLocal = addrMe;
2868 // Disconnect if we connected to ourself
2869 if (nNonce == nLocalHostNonce && nNonce > 1)
2871 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2872 pfrom->fDisconnect = true;
2876 // ppcoin: record my external IP reported by peer
2877 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
2878 addrSeenByPeer = addrMe;
2880 // Be shy and don't send version until we hear
2881 if (pfrom->fInbound)
2882 pfrom->PushVersion();
2884 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2886 AddTimeData(pfrom->addr, nTime);
2889 pfrom->PushMessage("verack");
2890 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2892 if (!pfrom->fInbound)
2894 // Advertise our address
2895 if (!fNoListen && !IsInitialBlockDownload())
2897 CAddress addr = GetLocalAddress(&pfrom->addr);
2898 if (addr.IsRoutable())
2899 pfrom->PushAddress(addr);
2902 // Get recent addresses
2903 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2905 pfrom->PushMessage("getaddr");
2906 pfrom->fGetAddr = true;
2908 addrman.Good(pfrom->addr);
2910 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2912 addrman.Add(addrFrom, addrFrom);
2913 addrman.Good(addrFrom);
2917 // Ask the first connected node for block updates
2918 static int nAskedForBlocks = 0;
2919 if (!pfrom->fClient && !pfrom->fOneShot &&
2920 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
2921 (pfrom->nVersion < NOBLKS_VERSION_START ||
2922 pfrom->nVersion >= NOBLKS_VERSION_END) &&
2923 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2926 pfrom->PushGetBlocks(pindexBest, uint256(0));
2932 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2933 item.second.RelayTo(pfrom);
2936 // ppcoin: relay sync-checkpoint
2938 LOCK(Checkpoints::cs_hashSyncCheckpoint);
2939 if (!Checkpoints::checkpointMessage.IsNull())
2940 Checkpoints::checkpointMessage.RelayTo(pfrom);
2943 pfrom->fSuccessfullyConnected = true;
2945 printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
2947 cPeerBlockCounts.input(pfrom->nStartingHeight);
2949 // ppcoin: ask for pending sync-checkpoint if any
2950 if (!IsInitialBlockDownload())
2951 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2955 else if (pfrom->nVersion == 0)
2957 // Must have a version message before anything else
2958 pfrom->Misbehaving(1);
2963 else if (strCommand == "verack")
2965 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2969 else if (strCommand == "addr")
2971 vector<CAddress> vAddr;
2974 // Don't want addr from older versions unless seeding
2975 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2977 if (vAddr.size() > 1000)
2979 pfrom->Misbehaving(20);
2980 return error("message addr size() = %"PRIszu"", vAddr.size());
2983 // Store the new addresses
2984 vector<CAddress> vAddrOk;
2985 int64 nNow = GetAdjustedTime();
2986 int64 nSince = nNow - 10 * 60;
2987 BOOST_FOREACH(CAddress& addr, vAddr)
2991 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2992 addr.nTime = nNow - 5 * 24 * 60 * 60;
2993 pfrom->AddAddressKnown(addr);
2994 bool fReachable = IsReachable(addr);
2995 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2997 // Relay to a limited number of other nodes
3000 // Use deterministic randomness to send to the same nodes for 24 hours
3001 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3002 static uint256 hashSalt;
3004 hashSalt = GetRandHash();
3005 uint64 hashAddr = addr.GetHash();
3006 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3007 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3008 multimap<uint256, CNode*> mapMix;
3009 BOOST_FOREACH(CNode* pnode, vNodes)
3011 if (pnode->nVersion < CADDR_TIME_VERSION)
3013 unsigned int nPointer;
3014 memcpy(&nPointer, &pnode, sizeof(nPointer));
3015 uint256 hashKey = hashRand ^ nPointer;
3016 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3017 mapMix.insert(make_pair(hashKey, pnode));
3019 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3020 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3021 ((*mi).second)->PushAddress(addr);
3024 // Do not store addresses outside our network
3026 vAddrOk.push_back(addr);
3028 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3029 if (vAddr.size() < 1000)
3030 pfrom->fGetAddr = false;
3031 if (pfrom->fOneShot)
3032 pfrom->fDisconnect = true;
3036 else if (strCommand == "inv")
3040 if (vInv.size() > MAX_INV_SZ)
3042 pfrom->Misbehaving(20);
3043 return error("message inv size() = %"PRIszu"", vInv.size());
3046 // find last block in inv vector
3047 unsigned int nLastBlock = (unsigned int)(-1);
3048 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3049 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3050 nLastBlock = vInv.size() - 1 - nInv;
3055 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3057 const CInv &inv = vInv[nInv];
3061 pfrom->AddInventoryKnown(inv);
3063 bool fAlreadyHave = AlreadyHave(txdb, inv);
3065 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3069 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3070 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3071 } else if (nInv == nLastBlock) {
3072 // In case we are on a very long side-chain, it is possible that we already have
3073 // the last block in an inv bundle sent in response to getblocks. Try to detect
3074 // this situation and push another getblocks to continue.
3075 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3077 printf("force request: %s\n", inv.ToString().c_str());
3080 // Track requests for our stuff
3081 Inventory(inv.hash);
3086 else if (strCommand == "getdata")
3090 if (vInv.size() > MAX_INV_SZ)
3092 pfrom->Misbehaving(20);
3093 return error("message getdata size() = %"PRIszu"", vInv.size());
3096 if (fDebugNet || (vInv.size() != 1))
3097 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3099 BOOST_FOREACH(const CInv& inv, vInv)
3103 if (fDebugNet || (vInv.size() == 1))
3104 printf("received getdata for: %s\n", inv.ToString().c_str());
3106 if (inv.type == MSG_BLOCK)
3108 // Send block from disk
3109 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3110 if (mi != mapBlockIndex.end())
3113 block.ReadFromDisk((*mi).second);
3114 pfrom->PushMessage("block", block);
3116 // Trigger them to send a getblocks request for the next batch of inventory
3117 if (inv.hash == pfrom->hashContinue)
3119 // ppcoin: send latest proof-of-work block to allow the
3120 // download node to accept as orphan (proof-of-stake
3121 // block might be rejected by stake connection check)
3123 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3124 pfrom->PushMessage("inv", vInv);
3125 pfrom->hashContinue = 0;
3129 else if (inv.IsKnownType())
3131 // Send stream from relay memory
3132 bool pushed = false;
3135 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3136 if (mi != mapRelay.end()) {
3137 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3141 if (!pushed && inv.type == MSG_TX) {
3143 if (mempool.exists(inv.hash)) {
3144 CTransaction tx = mempool.lookup(inv.hash);
3145 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3148 pfrom->PushMessage("tx", ss);
3153 // Track requests for our stuff
3154 Inventory(inv.hash);
3159 else if (strCommand == "getblocks")
3161 CBlockLocator locator;
3163 vRecv >> locator >> hashStop;
3165 // Find the last block the caller has in the main chain
3166 CBlockIndex* pindex = locator.GetBlockIndex();
3168 // Send the rest of the chain
3170 pindex = pindex->pnext;
3172 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3173 for (; pindex; pindex = pindex->pnext)
3175 if (pindex->GetBlockHash() == hashStop)
3177 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3178 // ppcoin: tell downloading node about the latest block if it's
3179 // without risk being rejected due to stake connection check
3180 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3181 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3184 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3187 // When this block is requested, we'll send an inv that'll make them
3188 // getblocks the next batch of inventory.
3189 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3190 pfrom->hashContinue = pindex->GetBlockHash();
3195 else if (strCommand == "checkpoint")
3197 CSyncCheckpoint checkpoint;
3198 vRecv >> checkpoint;
3200 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3203 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3205 BOOST_FOREACH(CNode* pnode, vNodes)
3206 checkpoint.RelayTo(pnode);
3210 else if (strCommand == "getheaders")
3212 CBlockLocator locator;
3214 vRecv >> locator >> hashStop;
3216 CBlockIndex* pindex = NULL;
3217 if (locator.IsNull())
3219 // If locator is null, return the hashStop block
3220 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3221 if (mi == mapBlockIndex.end())
3223 pindex = (*mi).second;
3227 // Find the last block the caller has in the main chain
3228 pindex = locator.GetBlockIndex();
3230 pindex = pindex->pnext;
3233 vector<CBlock> vHeaders;
3235 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3236 for (; pindex; pindex = pindex->pnext)
3238 vHeaders.push_back(pindex->GetBlockHeader());
3239 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3242 pfrom->PushMessage("headers", vHeaders);
3246 else if (strCommand == "tx")
3248 vector<uint256> vWorkQueue;
3249 vector<uint256> vEraseQueue;
3250 CDataStream vMsg(vRecv);
3255 CInv inv(MSG_TX, tx.GetHash());
3256 pfrom->AddInventoryKnown(inv);
3258 bool fMissingInputs = false;
3259 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3261 SyncWithWallets(tx, NULL, true);
3262 RelayMessage(inv, vMsg);
3263 mapAlreadyAskedFor.erase(inv);
3264 vWorkQueue.push_back(inv.hash);
3265 vEraseQueue.push_back(inv.hash);
3267 // Recursively process any orphan transactions that depended on this one
3268 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3270 uint256 hashPrev = vWorkQueue[i];
3271 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3272 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3275 const CDataStream& vMsg = *((*mi).second);
3277 CDataStream(vMsg) >> tx;
3278 CInv inv(MSG_TX, tx.GetHash());
3279 bool fMissingInputs2 = false;
3281 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3283 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3284 SyncWithWallets(tx, NULL, true);
3285 RelayMessage(inv, vMsg);
3286 mapAlreadyAskedFor.erase(inv);
3287 vWorkQueue.push_back(inv.hash);
3288 vEraseQueue.push_back(inv.hash);
3290 else if (!fMissingInputs2)
3293 vEraseQueue.push_back(inv.hash);
3294 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3299 BOOST_FOREACH(uint256 hash, vEraseQueue)
3300 EraseOrphanTx(hash);
3302 else if (fMissingInputs)
3306 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3307 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3309 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3311 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3315 else if (strCommand == "block")
3320 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3323 CInv inv(MSG_BLOCK, block.GetHash());
3324 pfrom->AddInventoryKnown(inv);
3326 if (ProcessBlock(pfrom, &block))
3327 mapAlreadyAskedFor.erase(inv);
3328 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3332 else if (strCommand == "getaddr")
3334 pfrom->vAddrToSend.clear();
3335 vector<CAddress> vAddr = addrman.GetAddr();
3336 BOOST_FOREACH(const CAddress &addr, vAddr)
3337 pfrom->PushAddress(addr);
3341 else if (strCommand == "mempool")
3343 std::vector<uint256> vtxid;
3344 mempool.queryHashes(vtxid);
3346 for (unsigned int i = 0; i < vtxid.size(); i++) {
3347 CInv inv(MSG_TX, vtxid[i]);
3348 vInv.push_back(inv);
3349 if (i == (MAX_INV_SZ - 1))
3352 if (vInv.size() > 0)
3353 pfrom->PushMessage("inv", vInv);
3357 else if (strCommand == "checkorder")
3362 if (!GetBoolArg("-allowreceivebyip"))
3364 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3371 /// we have a chance to check the order here
3373 // Keep giving the same key to the same ip until they use it
3374 if (!mapReuseKey.count(pfrom->addr))
3375 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3377 // Send back approval of order and pubkey to use
3378 CScript scriptPubKey;
3379 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3380 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3384 else if (strCommand == "reply")
3389 CRequestTracker tracker;
3391 LOCK(pfrom->cs_mapRequests);
3392 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3393 if (mi != pfrom->mapRequests.end())
3395 tracker = (*mi).second;
3396 pfrom->mapRequests.erase(mi);
3399 if (!tracker.IsNull())
3400 tracker.fn(tracker.param1, vRecv);
3404 else if (strCommand == "ping")
3406 if (pfrom->nVersion > BIP0031_VERSION)
3410 // Echo the message back with the nonce. This allows for two useful features:
3412 // 1) A remote node can quickly check if the connection is operational
3413 // 2) Remote nodes can measure the latency of the network thread. If this node
3414 // is overloaded it won't respond to pings quickly and the remote node can
3415 // avoid sending us more work, like chain download requests.
3417 // The nonce stops the remote getting confused between different pings: without
3418 // it, if the remote node sends a ping once per second and this node takes 5
3419 // seconds to respond to each, the 5th ping the remote sends would appear to
3420 // return very quickly.
3421 pfrom->PushMessage("pong", nonce);
3426 else if (strCommand == "alert")
3431 uint256 alertHash = alert.GetHash();
3432 if (pfrom->setKnown.count(alertHash) == 0)
3434 if (alert.ProcessAlert())
3437 pfrom->setKnown.insert(alertHash);
3440 BOOST_FOREACH(CNode* pnode, vNodes)
3441 alert.RelayTo(pnode);
3445 // Small DoS penalty so peers that send us lots of
3446 // duplicate/expired/invalid-signature/whatever alerts
3447 // eventually get banned.
3448 // This isn't a Misbehaving(100) (immediate ban) because the
3449 // peer might be an older or different implementation with
3450 // a different signature key, etc.
3451 pfrom->Misbehaving(10);
3459 // Ignore unknown commands for extensibility
3463 // Update the last seen time for this node's address
3464 if (pfrom->fNetworkNode)
3465 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3466 AddressCurrentlyConnected(pfrom->addr);
3472 bool ProcessMessages(CNode* pfrom)
3474 CDataStream& vRecv = pfrom->vRecv;
3478 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3482 // (4) message start
3491 // Don't bother if send buffer is too full to respond anyway
3492 if (pfrom->vSend.size() >= SendBufferSize())
3495 // Scan for message start
3496 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3497 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3498 if (vRecv.end() - pstart < nHeaderSize)
3500 if ((int)vRecv.size() > nHeaderSize)
3502 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3503 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3507 if (pstart - vRecv.begin() > 0)
3508 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3509 vRecv.erase(vRecv.begin(), pstart);
3512 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3517 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3520 string strCommand = hdr.GetCommand();
3523 unsigned int nMessageSize = hdr.nMessageSize;
3524 if (nMessageSize > MAX_SIZE)
3526 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3529 if (nMessageSize > vRecv.size())
3531 // Rewind and wait for rest of message
3532 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3537 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3538 unsigned int nChecksum = 0;
3539 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3540 if (nChecksum != hdr.nChecksum)
3542 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3543 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3547 // Copy message to its own buffer
3548 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3549 vRecv.ignore(nMessageSize);
3557 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3562 catch (std::ios_base::failure& e)
3564 if (strstr(e.what(), "end of data"))
3566 // Allow exceptions from under-length message on vRecv
3567 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());
3569 else if (strstr(e.what(), "size too large"))
3571 // Allow exceptions from over-long size
3572 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3576 PrintExceptionContinue(&e, "ProcessMessages()");
3579 catch (std::exception& e) {
3580 PrintExceptionContinue(&e, "ProcessMessages()");
3582 PrintExceptionContinue(NULL, "ProcessMessages()");
3586 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3594 bool SendMessages(CNode* pto, bool fSendTrickle)
3596 TRY_LOCK(cs_main, lockMain);
3598 // Don't send anything until we get their version message
3599 if (pto->nVersion == 0)
3602 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3604 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3606 if (pto->nVersion > BIP0031_VERSION)
3607 pto->PushMessage("ping", nonce);
3609 pto->PushMessage("ping");
3612 // Resend wallet transactions that haven't gotten in a block yet
3613 ResendWalletTransactions();
3615 // Address refresh broadcast
3616 static int64 nLastRebroadcast;
3617 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3621 BOOST_FOREACH(CNode* pnode, vNodes)
3623 // Periodically clear setAddrKnown to allow refresh broadcasts
3624 if (nLastRebroadcast)
3625 pnode->setAddrKnown.clear();
3627 // Rebroadcast our address
3630 CAddress addr = GetLocalAddress(&pnode->addr);
3631 if (addr.IsRoutable())
3632 pnode->PushAddress(addr);
3636 nLastRebroadcast = GetTime();
3644 vector<CAddress> vAddr;
3645 vAddr.reserve(pto->vAddrToSend.size());
3646 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3648 // returns true if wasn't already contained in the set
3649 if (pto->setAddrKnown.insert(addr).second)
3651 vAddr.push_back(addr);
3652 // receiver rejects addr messages larger than 1000
3653 if (vAddr.size() >= 1000)
3655 pto->PushMessage("addr", vAddr);
3660 pto->vAddrToSend.clear();
3662 pto->PushMessage("addr", vAddr);
3667 // Message: inventory
3670 vector<CInv> vInvWait;
3672 LOCK(pto->cs_inventory);
3673 vInv.reserve(pto->vInventoryToSend.size());
3674 vInvWait.reserve(pto->vInventoryToSend.size());
3675 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3677 if (pto->setInventoryKnown.count(inv))
3680 // trickle out tx inv to protect privacy
3681 if (inv.type == MSG_TX && !fSendTrickle)
3683 // 1/4 of tx invs blast to all immediately
3684 static uint256 hashSalt;
3686 hashSalt = GetRandHash();
3687 uint256 hashRand = inv.hash ^ hashSalt;
3688 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3689 bool fTrickleWait = ((hashRand & 3) != 0);
3691 // always trickle our own transactions
3695 if (GetTransaction(inv.hash, wtx))
3697 fTrickleWait = true;
3702 vInvWait.push_back(inv);
3707 // returns true if wasn't already contained in the set
3708 if (pto->setInventoryKnown.insert(inv).second)
3710 vInv.push_back(inv);
3711 if (vInv.size() >= 1000)
3713 pto->PushMessage("inv", vInv);
3718 pto->vInventoryToSend = vInvWait;
3721 pto->PushMessage("inv", vInv);
3727 vector<CInv> vGetData;
3728 int64 nNow = GetTime() * 1000000;
3730 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3732 const CInv& inv = (*pto->mapAskFor.begin()).second;
3733 if (!AlreadyHave(txdb, inv))
3736 printf("sending getdata: %s\n", inv.ToString().c_str());
3737 vGetData.push_back(inv);
3738 if (vGetData.size() >= 1000)
3740 pto->PushMessage("getdata", vGetData);
3743 mapAlreadyAskedFor[inv] = nNow;
3745 pto->mapAskFor.erase(pto->mapAskFor.begin());
3747 if (!vGetData.empty())
3748 pto->PushMessage("getdata", vGetData);
3767 //////////////////////////////////////////////////////////////////////////////
3772 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3774 unsigned char* pdata = (unsigned char*)pbuffer;
3775 unsigned int blocks = 1 + ((len + 8) / 64);
3776 unsigned char* pend = pdata + 64 * blocks;
3777 memset(pdata + len, 0, 64 * blocks - len);
3779 unsigned int bits = len * 8;
3780 pend[-1] = (bits >> 0) & 0xff;
3781 pend[-2] = (bits >> 8) & 0xff;
3782 pend[-3] = (bits >> 16) & 0xff;
3783 pend[-4] = (bits >> 24) & 0xff;
3787 static const unsigned int pSHA256InitState[8] =
3788 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3790 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3793 unsigned char data[64];
3797 for (int i = 0; i < 16; i++)
3798 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3800 for (int i = 0; i < 8; i++)
3801 ctx.h[i] = ((uint32_t*)pinit)[i];
3803 SHA256_Update(&ctx, data, sizeof(data));
3804 for (int i = 0; i < 8; i++)
3805 ((uint32_t*)pstate)[i] = ctx.h[i];
3808 // Some explaining would be appreciated
3813 set<uint256> setDependsOn;
3817 COrphan(CTransaction* ptxIn)
3820 dPriority = dFeePerKb = 0;
3825 printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
3826 ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
3827 BOOST_FOREACH(uint256 hash, setDependsOn)
3828 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3833 uint64 nLastBlockTx = 0;
3834 uint64 nLastBlockSize = 0;
3835 int64 nLastCoinStakeSearchInterval = 0;
3837 // We want to sort transactions by priority and fee, so:
3838 typedef boost::tuple<double, double, CTransaction*> TxPriority;
3839 class TxPriorityCompare
3843 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
3844 bool operator()(const TxPriority& a, const TxPriority& b)
3848 if (a.get<1>() == b.get<1>())
3849 return a.get<0>() < b.get<0>();
3850 return a.get<1>() < b.get<1>();
3854 if (a.get<0>() == b.get<0>())
3855 return a.get<1>() < b.get<1>();
3856 return a.get<0>() < b.get<0>();
3862 // fProofOfStake: try (best effort) to make a proof-of-stake block
3863 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
3865 CReserveKey reservekey(pwallet);
3868 auto_ptr<CBlock> pblock(new CBlock());
3872 // Create coinbase tx
3874 txNew.vin.resize(1);
3875 txNew.vin[0].prevout.SetNull();
3876 txNew.vout.resize(1);
3877 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3879 // Add our coinbase tx as first transaction
3880 pblock->vtx.push_back(txNew);
3884 // Largest block you're willing to create:
3885 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
3886 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
3887 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
3889 // How much of the block should be dedicated to high-priority transactions,
3890 // included regardless of the fees they pay
3891 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
3892 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
3894 // Minimum block size you want to create; block will be filled with free transactions
3895 // until there are no more or the block reaches this size:
3896 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
3897 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
3899 // Fee-per-kilobyte amount considered the same as "free"
3900 // Be careful setting this: if you set it to zero then
3901 // a transaction spammer can cheaply fill blocks using
3902 // 1-satoshi-fee transactions. It should be set above the real
3903 // cost to you of processing a transaction.
3904 int64 nMinTxFee = MIN_TX_FEE;
3905 if (mapArgs.count("-mintxfee"))
3906 ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
3908 // ppcoin: if coinstake available add coinstake tx
3909 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
3910 CBlockIndex* pindexPrev = pindexBest;
3912 if (fProofOfStake) // attemp to find a coinstake
3914 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
3915 CTransaction txCoinStake;
3916 int64 nSearchTime = txCoinStake.nTime; // search to current time
3917 if (nSearchTime > nLastCoinStakeSearchTime)
3919 if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
3921 if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
3922 { // make sure coinstake would meet timestamp protocol
3923 // as it would be the same as the block timestamp
3924 pblock->vtx[0].vout[0].SetEmpty();
3925 pblock->vtx[0].nTime = txCoinStake.nTime;
3926 pblock->vtx.push_back(txCoinStake);
3929 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
3930 nLastCoinStakeSearchTime = nSearchTime;
3934 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
3936 // Collect memory pool transactions into the block
3939 LOCK2(cs_main, mempool.cs);
3940 CBlockIndex* pindexPrev = pindexBest;
3943 // Priority order to process transactions
3944 list<COrphan> vOrphan; // list memory doesn't move
3945 map<uint256, vector<COrphan*> > mapDependers;
3947 // This vector will be sorted into a priority queue:
3948 vector<TxPriority> vecPriority;
3949 vecPriority.reserve(mempool.mapTx.size());
3950 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3952 CTransaction& tx = (*mi).second;
3953 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
3956 COrphan* porphan = NULL;
3957 double dPriority = 0;
3959 bool fMissingInputs = false;
3960 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3962 // Read prev transaction
3963 CTransaction txPrev;
3965 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3967 // This should never happen; all transactions in the memory
3968 // pool should connect to either transactions in the chain
3969 // or other transactions in the memory pool.
3970 if (!mempool.mapTx.count(txin.prevout.hash))
3972 printf("ERROR: mempool transaction missing input\n");
3973 if (fDebug) assert("mempool transaction missing input" == 0);
3974 fMissingInputs = true;
3980 // Has to wait for dependencies
3983 // Use list for automatic deletion
3984 vOrphan.push_back(COrphan(&tx));
3985 porphan = &vOrphan.back();
3987 mapDependers[txin.prevout.hash].push_back(porphan);
3988 porphan->setDependsOn.insert(txin.prevout.hash);
3989 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
3992 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3993 nTotalIn += nValueIn;
3995 int nConf = txindex.GetDepthInMainChain();
3996 dPriority += (double)nValueIn * nConf;
3998 if (fMissingInputs) continue;
4000 // Priority is sum(valuein * age) / txsize
4001 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4002 dPriority /= nTxSize;
4004 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
4005 // client code rounds up the size to the nearest 1K. That's good, because it gives an
4006 // incentive to create smaller transactions.
4007 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
4011 porphan->dPriority = dPriority;
4012 porphan->dFeePerKb = dFeePerKb;
4015 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
4018 // Collect transactions into block
4019 map<uint256, CTxIndex> mapTestPool;
4020 uint64 nBlockSize = 1000;
4021 uint64 nBlockTx = 0;
4022 int nBlockSigOps = 100;
4023 bool fSortedByFee = (nBlockPrioritySize <= 0);
4025 TxPriorityCompare comparer(fSortedByFee);
4026 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4028 while (!vecPriority.empty())
4030 // Take highest priority transaction off the priority queue:
4031 double dPriority = vecPriority.front().get<0>();
4032 double dFeePerKb = vecPriority.front().get<1>();
4033 CTransaction& tx = *(vecPriority.front().get<2>());
4035 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
4036 vecPriority.pop_back();
4039 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4040 if (nBlockSize + nTxSize >= nBlockMaxSize)
4043 // Legacy limits on sigOps:
4044 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
4045 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4049 if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
4052 // ppcoin: simplify transaction fee - allow free = false
4053 int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
4055 // Skip free transactions if we're past the minimum block size:
4056 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
4059 // Prioritize by fee once past the priority size or we run out of high-priority
4061 if (!fSortedByFee &&
4062 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
4064 fSortedByFee = true;
4065 comparer = TxPriorityCompare(fSortedByFee);
4066 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4069 // Connecting shouldn't fail due to dependency on other memory pool transactions
4070 // because we're already processing them in order of dependency
4071 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
4072 MapPrevTx mapInputs;
4074 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
4077 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
4078 if (nTxFees < nMinFee)
4081 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
4082 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4085 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
4087 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
4088 swap(mapTestPool, mapTestPoolTmp);
4091 pblock->vtx.push_back(tx);
4092 nBlockSize += nTxSize;
4094 nBlockSigOps += nTxSigOps;
4097 if (fDebug && GetBoolArg("-printpriority"))
4099 printf("priority %.1f feeperkb %.1f txid %s\n",
4100 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
4103 // Add transactions that depend on this one to the priority queue
4104 uint256 hash = tx.GetHash();
4105 if (mapDependers.count(hash))
4107 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
4109 if (!porphan->setDependsOn.empty())
4111 porphan->setDependsOn.erase(hash);
4112 if (porphan->setDependsOn.empty())
4114 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
4115 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
4122 nLastBlockTx = nBlockTx;
4123 nLastBlockSize = nBlockSize;
4124 printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
4126 if (pblock->IsProofOfWork())
4127 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
4130 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
4131 if (pblock->IsProofOfStake())
4132 pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
4133 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
4134 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4135 if (pblock->IsProofOfWork())
4136 pblock->UpdateTime(pindexPrev);
4140 return pblock.release();
4144 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
4146 // Update nExtraNonce
4147 static uint256 hashPrevBlock;
4148 if (hashPrevBlock != pblock->hashPrevBlock)
4151 hashPrevBlock = pblock->hashPrevBlock;
4154 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4155 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4156 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
4158 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
4162 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
4165 // Pre-build hash buffers
4172 uint256 hashPrevBlock;
4173 uint256 hashMerkleRoot;
4176 unsigned int nNonce;
4179 unsigned char pchPadding0[64];
4181 unsigned char pchPadding1[64];
4184 memset(&tmp, 0, sizeof(tmp));
4186 tmp.block.nVersion = pblock->nVersion;
4187 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
4188 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
4189 tmp.block.nTime = pblock->nTime;
4190 tmp.block.nBits = pblock->nBits;
4191 tmp.block.nNonce = pblock->nNonce;
4193 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
4194 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
4196 // Byte swap all the input buffer
4197 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
4198 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
4200 // Precalc the first half of the first hash, which stays constant
4201 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
4203 memcpy(pdata, &tmp.block, 128);
4204 memcpy(phash1, &tmp.hash1, 64);
4208 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
4210 uint256 hash = pblock->GetHash();
4211 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4213 if (hash > hashTarget && pblock->IsProofOfWork())
4214 return error("BitcoinMiner : proof-of-work not meeting target");
4217 printf("BitcoinMiner:\n");
4218 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
4220 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
4225 if (pblock->hashPrevBlock != hashBestChain)
4226 return error("BitcoinMiner : generated block is stale");
4228 // Remove key from key pool
4229 reservekey.KeepKey();
4231 // Track how many getdata requests this block gets
4233 LOCK(wallet.cs_wallet);
4234 wallet.mapRequestCount[pblock->GetHash()] = 0;
4237 // Process this block the same as if we had received it from another node
4238 if (!ProcessBlock(NULL, pblock))
4239 return error("BitcoinMiner : ProcessBlock, block not accepted");
4245 void static ThreadBitcoinMiner(void* parg);
4247 static bool fGenerateBitcoins = false;
4248 static bool fLimitProcessors = false;
4249 static int nLimitProcessors = -1;
4251 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake)
4253 void *scratchbuf = scrypt_buffer_alloc();
4255 printf("CPUMiner started for proof-of-%s\n", fProofOfStake? "stake" : "work");
4256 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4258 // Make this thread recognisable as the mining thread
4259 RenameThread("bitcoin-miner");
4261 // Each thread has its own key and counter
4262 CReserveKey reservekey(pwallet);
4263 unsigned int nExtraNonce = 0;
4265 while (fGenerateBitcoins || fProofOfStake)
4269 while (vNodes.empty() || IsInitialBlockDownload())
4274 if ((!fGenerateBitcoins) && !fProofOfStake)
4278 while (pwallet->IsLocked())
4280 strMintWarning = strMintMessage;
4283 strMintWarning = "";
4288 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
4289 CBlockIndex* pindexPrev = pindexBest;
4291 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
4294 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
4298 // ppcoin: if proof-of-stake block found then process block
4299 if (pblock->IsProofOfStake())
4301 if (!pblock->SignBlock(*pwalletMain))
4303 strMintWarning = strMintMessage;
4306 strMintWarning = "";
4307 printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
4308 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4309 CheckWork(pblock.get(), *pwalletMain, reservekey);
4310 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4316 printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
4317 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
4320 // Pre-build hash buffers
4322 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
4323 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
4324 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
4326 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
4328 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
4329 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
4335 int64 nStart = GetTime();
4336 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4338 unsigned int max_nonce = 0xffff0000;
4339 block_header res_header;
4344 unsigned int nHashesDone = 0;
4345 unsigned int nNonceFound;
4347 nNonceFound = scanhash_scrypt(
4348 (block_header *)&pblock->nVersion,
4356 // Check if something found
4357 if (nNonceFound != (unsigned int) -1)
4359 if (result <= hashTarget)
4362 pblock->nNonce = nNonceFound;
4363 assert(result == pblock->GetHash());
4364 if (!pblock->SignBlock(*pwalletMain))
4366 // strMintWarning = strMintMessage;
4369 strMintWarning = "";
4371 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4372 CheckWork(pblock.get(), *pwalletMain, reservekey);
4373 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4379 static int64 nHashCounter;
4380 if (nHPSTimerStart == 0)
4382 nHPSTimerStart = GetTimeMillis();
4386 nHashCounter += nHashesDone;
4387 if (GetTimeMillis() - nHPSTimerStart > 4000)
4389 static CCriticalSection cs;
4392 if (GetTimeMillis() - nHPSTimerStart > 4000)
4394 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
4395 nHPSTimerStart = GetTimeMillis();
4397 static int64 nLogTime;
4398 if (GetTime() - nLogTime > 30 * 60)
4400 nLogTime = GetTime();
4401 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
4407 // Check for stop or if block needs to be rebuilt
4410 if (!fGenerateBitcoins)
4412 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4416 if (nBlockNonce >= 0xffff0000)
4418 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4420 if (pindexPrev != pindexBest)
4423 // Update nTime every few seconds
4424 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
4425 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4426 pblock->UpdateTime(pindexPrev);
4427 nBlockTime = ByteReverse(pblock->nTime);
4429 if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
4430 break; // need to update coinbase timestamp
4434 scrypt_buffer_free(scratchbuf);
4437 void static ThreadBitcoinMiner(void* parg)
4439 CWallet* pwallet = (CWallet*)parg;
4442 vnThreadsRunning[THREAD_MINER]++;
4443 BitcoinMiner(pwallet, false);
4444 vnThreadsRunning[THREAD_MINER]--;
4446 catch (std::exception& e) {
4447 vnThreadsRunning[THREAD_MINER]--;
4448 PrintException(&e, "ThreadBitcoinMiner()");
4450 vnThreadsRunning[THREAD_MINER]--;
4451 PrintException(NULL, "ThreadBitcoinMiner()");
4454 if (vnThreadsRunning[THREAD_MINER] == 0)
4456 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4460 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4462 fGenerateBitcoins = fGenerate;
4463 nLimitProcessors = GetArg("-genproclimit", -1);
4464 if (nLimitProcessors == 0)
4465 fGenerateBitcoins = false;
4466 fLimitProcessors = (nLimitProcessors != -1);
4470 int nProcessors = boost::thread::hardware_concurrency();
4471 printf("%d processors\n", nProcessors);
4472 if (nProcessors < 1)
4474 if (fLimitProcessors && nProcessors > nLimitProcessors)
4475 nProcessors = nLimitProcessors;
4476 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4477 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4478 for (int i = 0; i < nAddThreads; i++)
4480 if (!NewThread(ThreadBitcoinMiner, pwallet))
4481 printf("Error: NewThread(ThreadBitcoinMiner) failed\n");