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;
36 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
37 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
38 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
39 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
40 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
42 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
44 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as minimum age for coin age
45 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as stake age of full weight
46 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
47 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
49 int nCoinbaseMaturity = 500;
50 CBlockIndex* pindexGenesisBlock = NULL;
53 uint256 nBestChainTrust = 0;
54 uint256 nBestInvalidTrust = 0;
56 uint256 hashBestChain = 0;
57 CBlockIndex* pindexBest = NULL;
58 int64 nTimeBestReceived = 0;
60 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
62 map<uint256, CBlock*> mapOrphanBlocks;
63 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
64 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
65 map<uint256, uint256> mapProofOfStake;
67 map<uint256, CDataStream*> mapOrphanTransactions;
68 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
70 // Constant stuff for coinbase transactions we create:
71 CScript COINBASE_FLAGS;
73 const string strMessageMagic = "NovaCoin Signed Message:\n";
79 int64 nTransactionFee = MIN_TX_FEE;
82 //////////////////////////////////////////////////////////////////////////////
84 // dispatching functions
87 // These functions dispatch to one or all registered wallets
90 void RegisterWallet(CWallet* pwalletIn)
93 LOCK(cs_setpwalletRegistered);
94 setpwalletRegistered.insert(pwalletIn);
98 void UnregisterWallet(CWallet* pwalletIn)
101 LOCK(cs_setpwalletRegistered);
102 setpwalletRegistered.erase(pwalletIn);
106 // check whether the passed transaction is from us
107 bool static IsFromMe(CTransaction& tx)
109 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
110 if (pwallet->IsFromMe(tx))
115 // get the wallet transaction with the given hash (if it exists)
116 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
118 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
119 if (pwallet->GetTransaction(hashTx,wtx))
124 // erases transaction with the given hash from all wallets
125 void static EraseFromWallets(uint256 hash)
127 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
128 pwallet->EraseFromWallet(hash);
131 // make sure all wallets know about the given transaction, in the given block
132 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
136 // ppcoin: wallets need to refund inputs when disconnecting coinstake
137 if (tx.IsCoinStake())
139 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
140 if (pwallet->IsFromMe(tx))
141 pwallet->DisableTransaction(tx);
146 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
147 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
150 // notify wallets about a new best chain
151 void static SetBestChain(const CBlockLocator& loc)
153 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
154 pwallet->SetBestChain(loc);
157 // notify wallets about an updated transaction
158 void static UpdatedTransaction(const uint256& hashTx)
160 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
161 pwallet->UpdatedTransaction(hashTx);
165 void static PrintWallets(const CBlock& block)
167 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
168 pwallet->PrintWallet(block);
171 // notify wallets about an incoming inventory (for request counts)
172 void static Inventory(const uint256& hash)
174 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
175 pwallet->Inventory(hash);
178 // ask wallets to resend their transactions
179 void ResendWalletTransactions()
181 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
182 pwallet->ResendWalletTransactions();
191 //////////////////////////////////////////////////////////////////////////////
193 // mapOrphanTransactions
196 bool AddOrphanTx(const CDataStream& vMsg)
199 CDataStream(vMsg) >> tx;
200 uint256 hash = tx.GetHash();
201 if (mapOrphanTransactions.count(hash))
204 CDataStream* pvMsg = new CDataStream(vMsg);
206 // Ignore big transactions, to avoid a
207 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
208 // large transaction with a missing parent then we assume
209 // it will rebroadcast it later, after the parent transaction(s)
210 // have been mined or received.
211 // 10,000 orphans, each of which is at most 5,000 bytes big is
212 // at most 500 megabytes of orphans:
213 if (pvMsg->size() > 5000)
215 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
220 mapOrphanTransactions[hash] = pvMsg;
221 BOOST_FOREACH(const CTxIn& txin, tx.vin)
222 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
224 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
225 mapOrphanTransactions.size());
229 void static EraseOrphanTx(uint256 hash)
231 if (!mapOrphanTransactions.count(hash))
233 const CDataStream* pvMsg = mapOrphanTransactions[hash];
235 CDataStream(*pvMsg) >> tx;
236 BOOST_FOREACH(const CTxIn& txin, tx.vin)
238 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
239 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
240 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
243 mapOrphanTransactions.erase(hash);
246 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
248 unsigned int nEvicted = 0;
249 while (mapOrphanTransactions.size() > nMaxOrphans)
251 // Evict a random orphan:
252 uint256 randomhash = GetRandHash();
253 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
254 if (it == mapOrphanTransactions.end())
255 it = mapOrphanTransactions.begin();
256 EraseOrphanTx(it->first);
268 //////////////////////////////////////////////////////////////////////////////
270 // CTransaction and CTxIndex
273 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
276 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
278 if (!ReadFromDisk(txindexRet.pos))
280 if (prevout.n >= vout.size())
288 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
291 return ReadFromDisk(txdb, prevout, txindex);
294 bool CTransaction::ReadFromDisk(COutPoint prevout)
298 return ReadFromDisk(txdb, prevout, txindex);
301 bool CTransaction::IsStandard() const
303 if (nVersion > CTransaction::CURRENT_VERSION)
306 BOOST_FOREACH(const CTxIn& txin, vin)
308 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
309 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
310 // ~65-byte public keys, plus a few script ops.
311 if (txin.scriptSig.size() > 500)
313 if (!txin.scriptSig.IsPushOnly())
316 BOOST_FOREACH(const CTxOut& txout, vout) {
317 if (!::IsStandard(txout.scriptPubKey))
319 if (txout.nValue == 0)
326 // Check transaction inputs, and make sure any
327 // pay-to-script-hash transactions are evaluating IsStandard scripts
329 // Why bother? To avoid denial-of-service attacks; an attacker
330 // can submit a standard HASH... OP_EQUAL transaction,
331 // which will get accepted into blocks. The redemption
332 // script can be anything; an attacker could use a very
333 // expensive-to-check-upon-redemption script like:
334 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
336 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
339 return true; // Coinbases don't use vin normally
341 for (unsigned int i = 0; i < vin.size(); i++)
343 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
345 vector<vector<unsigned char> > vSolutions;
346 txnouttype whichType;
347 // get the scriptPubKey corresponding to this input:
348 const CScript& prevScript = prev.scriptPubKey;
349 if (!Solver(prevScript, whichType, vSolutions))
351 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
352 if (nArgsExpected < 0)
355 // Transactions with extra stuff in their scriptSigs are
356 // non-standard. Note that this EvalScript() call will
357 // be quick, because if there are any operations
358 // beside "push data" in the scriptSig the
359 // IsStandard() call returns false
360 vector<vector<unsigned char> > stack;
361 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
364 if (whichType == TX_SCRIPTHASH)
368 CScript subscript(stack.back().begin(), stack.back().end());
369 vector<vector<unsigned char> > vSolutions2;
370 txnouttype whichType2;
371 if (!Solver(subscript, whichType2, vSolutions2))
373 if (whichType2 == TX_SCRIPTHASH)
377 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
380 nArgsExpected += tmpExpected;
383 if (stack.size() != (unsigned int)nArgsExpected)
391 CTransaction::GetLegacySigOpCount() const
393 unsigned int nSigOps = 0;
394 BOOST_FOREACH(const CTxIn& txin, vin)
396 nSigOps += txin.scriptSig.GetSigOpCount(false);
398 BOOST_FOREACH(const CTxOut& txout, vout)
400 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
406 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
418 // Load the block this tx is in
420 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
422 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
427 // Update the tx's hashBlock
428 hashBlock = pblock->GetHash();
430 // Locate the transaction
431 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
432 if (pblock->vtx[nIndex] == *(CTransaction*)this)
434 if (nIndex == (int)pblock->vtx.size())
436 vMerkleBranch.clear();
438 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
442 // Fill in merkle branch
443 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
446 // Is the tx in a block that's in the main chain
447 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
448 if (mi == mapBlockIndex.end())
450 CBlockIndex* pindex = (*mi).second;
451 if (!pindex || !pindex->IsInMainChain())
454 return pindexBest->nHeight - pindex->nHeight + 1;
463 bool CTransaction::CheckTransaction() const
465 // Basic checks that don't depend on any context
467 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
469 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
471 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
472 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
474 // Check for negative or overflow output values
476 for (unsigned int i = 0; i < vout.size(); i++)
478 const CTxOut& txout = vout[i];
479 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
480 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
482 // NovaCoin: enforce minimum output amount for user transactions
483 // (and for all transactions until 20 Sep 2013)
484 if ((!IsCoinBase() || nTime < CHAINCHECKS_SWITCH_TIME)
485 && (!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
486 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
488 if (txout.nValue > MAX_MONEY)
489 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
490 nValueOut += txout.nValue;
491 if (!MoneyRange(nValueOut))
492 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
495 // Check for duplicate inputs
496 set<COutPoint> vInOutPoints;
497 BOOST_FOREACH(const CTxIn& txin, vin)
499 if (vInOutPoints.count(txin.prevout))
501 vInOutPoints.insert(txin.prevout);
506 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
507 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
511 BOOST_FOREACH(const CTxIn& txin, vin)
512 if (txin.prevout.IsNull())
513 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
519 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
520 enum GetMinFee_mode mode) const
522 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
523 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
525 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
526 unsigned int nNewBlockSize = nBlockSize + nBytes;
527 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
529 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
530 if (nMinFee < nBaseFee)
532 BOOST_FOREACH(const CTxOut& txout, vout)
533 if (txout.nValue < CENT)
537 // Raise the price as the block approaches full
538 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
540 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
542 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
545 if (!MoneyRange(nMinFee))
551 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
552 bool* pfMissingInputs)
555 *pfMissingInputs = false;
557 if (!tx.CheckTransaction())
558 return error("CTxMemPool::accept() : CheckTransaction failed");
560 // Coinbase is only valid in a block, not as a loose transaction
562 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
564 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
565 if (tx.IsCoinStake())
566 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
568 // To help v0.1.5 clients who would see it as a negative number
569 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
570 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
572 // Rather not work on nonstandard transactions (unless -testnet)
573 if (!fTestNet && !tx.IsStandard())
574 return error("CTxMemPool::accept() : nonstandard transaction type");
576 // Do we already have it?
577 uint256 hash = tx.GetHash();
580 if (mapTx.count(hash))
584 if (txdb.ContainsTx(hash))
587 // Check for conflicts with in-memory transactions
588 CTransaction* ptxOld = NULL;
589 for (unsigned int i = 0; i < tx.vin.size(); i++)
591 COutPoint outpoint = tx.vin[i].prevout;
592 if (mapNextTx.count(outpoint))
594 // Disable replacement feature for now
597 // Allow replacing with a newer version of the same transaction
600 ptxOld = mapNextTx[outpoint].ptx;
601 if (ptxOld->IsFinal())
603 if (!tx.IsNewerThan(*ptxOld))
605 for (unsigned int i = 0; i < tx.vin.size(); i++)
607 COutPoint outpoint = tx.vin[i].prevout;
608 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
618 map<uint256, CTxIndex> mapUnused;
619 bool fInvalid = false;
620 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
623 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
625 *pfMissingInputs = true;
629 // Check for non-standard pay-to-script-hash in inputs
630 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
631 return error("CTxMemPool::accept() : nonstandard transaction input");
633 // Note: if you modify this code to accept non-standard transactions, then
634 // you should add code here to check that the transaction does a
635 // reasonable number of ECDSA signature verifications.
637 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
638 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
640 // Don't accept it if it can't get into a block
641 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY);
642 if (nFees < txMinFee)
643 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
644 hash.ToString().c_str(),
647 // Continuously rate-limit free transactions
648 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
649 // be annoying or make others' transactions take longer to confirm.
650 if (nFees < MIN_RELAY_TX_FEE)
652 static CCriticalSection cs;
653 static double dFreeCount;
654 static int64 nLastTime;
655 int64 nNow = GetTime();
659 // Use an exponentially decaying ~10-minute window:
660 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
662 // -limitfreerelay unit is thousand-bytes-per-minute
663 // At default rate it would take over a month to fill 1GB
664 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
665 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
667 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
672 // Check against previous transactions
673 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
674 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
676 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
680 // Store transaction in memory
685 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
688 addUnchecked(hash, tx);
691 ///// are we sure this is ok when loading transactions or restoring block txes
692 // If updated, erase old tx from wallet
694 EraseFromWallets(ptxOld->GetHash());
696 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
697 hash.ToString().substr(0,10).c_str(),
702 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
704 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
707 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
709 // Add to memory pool without checking anything. Don't call this directly,
710 // call CTxMemPool::accept to properly check the transaction first.
713 for (unsigned int i = 0; i < tx.vin.size(); i++)
714 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
715 nTransactionsUpdated++;
721 bool CTxMemPool::remove(CTransaction &tx)
723 // Remove transaction from memory pool
726 uint256 hash = tx.GetHash();
727 if (mapTx.count(hash))
729 BOOST_FOREACH(const CTxIn& txin, tx.vin)
730 mapNextTx.erase(txin.prevout);
732 nTransactionsUpdated++;
738 void CTxMemPool::clear()
743 ++nTransactionsUpdated;
746 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
751 vtxid.reserve(mapTx.size());
752 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
753 vtxid.push_back((*mi).first);
759 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
761 if (hashBlock == 0 || nIndex == -1)
764 // Find the block it claims to be in
765 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
766 if (mi == mapBlockIndex.end())
768 CBlockIndex* pindex = (*mi).second;
769 if (!pindex || !pindex->IsInMainChain())
772 // Make sure the merkle branch connects to this block
773 if (!fMerkleVerified)
775 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
777 fMerkleVerified = true;
781 return pindexBest->nHeight - pindex->nHeight + 1;
785 int CMerkleTx::GetBlocksToMaturity() const
787 if (!(IsCoinBase() || IsCoinStake()))
789 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
793 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
797 if (!IsInMainChain() && !ClientConnectInputs())
799 return CTransaction::AcceptToMemoryPool(txdb, false);
803 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
807 bool CMerkleTx::AcceptToMemoryPool()
810 return AcceptToMemoryPool(txdb);
815 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
820 // Add previous supporting transactions first
821 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
823 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
825 uint256 hash = tx.GetHash();
826 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
827 tx.AcceptToMemoryPool(txdb, fCheckInputs);
830 return AcceptToMemoryPool(txdb, fCheckInputs);
835 bool CWalletTx::AcceptWalletTransaction()
838 return AcceptWalletTransaction(txdb);
841 int CTxIndex::GetDepthInMainChain() const
845 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
847 // Find the block in the index
848 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
849 if (mi == mapBlockIndex.end())
851 CBlockIndex* pindex = (*mi).second;
852 if (!pindex || !pindex->IsInMainChain())
854 return 1 + nBestHeight - pindex->nHeight;
857 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
858 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
864 if (mempool.exists(hash))
866 tx = mempool.lookup(hash);
872 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
875 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
876 hashBlock = block.GetHash();
890 //////////////////////////////////////////////////////////////////////////////
892 // CBlock and CBlockIndex
895 static CBlockIndex* pblockindexFBBHLast;
896 CBlockIndex* FindBlockByHeight(int nHeight)
898 CBlockIndex *pblockindex;
899 if (nHeight < nBestHeight / 2)
900 pblockindex = pindexGenesisBlock;
902 pblockindex = pindexBest;
903 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
904 pblockindex = pblockindexFBBHLast;
905 while (pblockindex->nHeight > nHeight)
906 pblockindex = pblockindex->pprev;
907 while (pblockindex->nHeight < nHeight)
908 pblockindex = pblockindex->pnext;
909 pblockindexFBBHLast = pblockindex;
913 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
915 if (!fReadTransactions)
917 *this = pindex->GetBlockHeader();
920 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
922 if (GetHash() != pindex->GetBlockHash())
923 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
927 uint256 static GetOrphanRoot(const CBlock* pblock)
929 // Work back to the first block in the orphan chain
930 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
931 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
932 return pblock->GetHash();
935 // ppcoin: find block wanted by given orphan block
936 uint256 WantedByOrphan(const CBlock* pblockOrphan)
938 // Work back to the first block in the orphan chain
939 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
940 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
941 return pblockOrphan->hashPrevBlock;
944 // select stake target limit according to hard-coded conditions
945 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
947 if(fTestNet) // separate proof of stake target limit for testnet
948 return bnProofOfStakeLimit;
949 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
950 return bnProofOfStakeLimit;
951 if(nHeight + 1 > 15000) // 24 bits since block 15000
952 return bnProofOfStakeLegacyLimit;
953 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
954 return bnProofOfStakeHardLimit;
956 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
959 // miner's coin base reward based on nBits
960 int64 GetProofOfWorkReward(unsigned int nBits)
962 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
965 bnTarget.SetCompact(nBits);
966 CBigNum bnTargetLimit = bnProofOfWorkLimit;
967 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
969 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
970 // A reasonably continuous curve is used to avoid shock to market
971 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
973 // Human readable form:
975 // nSubsidy = 100 / (diff ^ 1/6)
976 CBigNum bnLowerBound = CENT;
977 CBigNum bnUpperBound = bnSubsidyLimit;
978 while (bnLowerBound + CENT <= bnUpperBound)
980 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
981 if (fDebug && GetBoolArg("-printcreation"))
982 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
983 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
984 bnUpperBound = bnMidValue;
986 bnLowerBound = bnMidValue;
989 int64 nSubsidy = bnUpperBound.getuint64();
991 nSubsidy = (nSubsidy / CENT) * CENT;
992 if (fDebug && GetBoolArg("-printcreation"))
993 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
995 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
998 // miner's coin stake reward based on nBits and coin age spent (coin-days)
999 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
1001 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1003 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1005 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1007 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1009 bnTarget.SetCompact(nBits);
1010 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1011 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1013 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1015 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1016 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1017 bnMidPart, bnRewardPart;
1019 while (bnLowerBound + CENT <= bnUpperBound)
1021 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1022 if (fDebug && GetBoolArg("-printcreation"))
1023 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1025 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1028 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1030 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1032 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1035 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1036 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1041 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1043 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1045 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1048 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1049 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1052 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1053 bnUpperBound = bnMidValue;
1055 bnLowerBound = bnMidValue;
1058 nRewardCoinYear = bnUpperBound.getuint64();
1059 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1063 // Old creation amount per coin-year, 5% fixed stake mint rate
1064 nRewardCoinYear = 5 * CENT;
1068 return nRewardCoinYear;
1070 // Fix problem with proof-of-stake rewards calculation since 20 Sep 2013
1071 if(nTime < CHAINCHECKS_SWITCH_TIME)
1072 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
1074 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1076 // Set reasonable reward limit for large inputs since 20 Oct 2013
1078 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1079 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1081 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1082 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1084 nSubsidy = min(nSubsidy, nSubsidyLimit);
1087 if (fDebug && GetBoolArg("-printcreation"))
1088 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1092 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1094 // get proof of work blocks max spacing according to hard-coded conditions
1095 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1097 if(nTime > TARGETS_SWITCH_TIME)
1098 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1101 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1103 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1107 // minimum amount of work that could possibly be required nTime after
1108 // minimum work required was nBase
1110 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1112 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1115 bnResult.SetCompact(nBase);
1117 while (nTime > 0 && bnResult < bnTargetLimit)
1119 // Maximum 200% adjustment per day...
1121 nTime -= 24 * 60 * 60;
1123 if (bnResult > bnTargetLimit)
1124 bnResult = bnTargetLimit;
1125 return bnResult.GetCompact();
1128 // ppcoin: find last block index up to pindex
1129 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1131 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1132 pindex = pindex->pprev;
1136 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1138 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1140 if (pindexLast == NULL)
1141 return bnTargetLimit.GetCompact(); // genesis block
1143 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1144 if (pindexPrev->pprev == NULL)
1145 return bnTargetLimit.GetCompact(); // first block
1146 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1147 if (pindexPrevPrev->pprev == NULL)
1148 return bnTargetLimit.GetCompact(); // second block
1150 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1152 // ppcoin: target change every block
1153 // ppcoin: retarget with exponential moving toward target spacing
1155 bnNew.SetCompact(pindexPrev->nBits);
1156 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1157 int64 nInterval = nTargetTimespan / nTargetSpacing;
1158 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1159 bnNew /= ((nInterval + 1) * nTargetSpacing);
1161 if (bnNew > bnTargetLimit)
1162 bnNew = bnTargetLimit;
1164 return bnNew.GetCompact();
1167 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1170 bnTarget.SetCompact(nBits);
1173 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1174 return error("CheckProofOfWork() : nBits below minimum work");
1176 // Check proof of work matches claimed amount
1177 if (hash > bnTarget.getuint256())
1178 return error("CheckProofOfWork() : hash doesn't match nBits");
1183 // Return maximum amount of blocks that other nodes claim to have
1184 int GetNumBlocksOfPeers()
1186 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1189 bool IsInitialBlockDownload()
1191 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1193 static int64 nLastUpdate;
1194 static CBlockIndex* pindexLastBest;
1195 if (pindexBest != pindexLastBest)
1197 pindexLastBest = pindexBest;
1198 nLastUpdate = GetTime();
1200 return (GetTime() - nLastUpdate < 10 &&
1201 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1204 void static InvalidChainFound(CBlockIndex* pindexNew)
1206 if (pindexNew->nChainTrust > nBestInvalidTrust)
1208 nBestInvalidTrust = pindexNew->nChainTrust;
1209 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1210 uiInterface.NotifyBlocksChanged();
1213 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1214 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1216 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1217 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1218 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1219 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1220 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1221 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1222 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1223 nBestBlockTrust.Get64(),
1224 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1228 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1230 nTime = max(GetBlockTime(), GetAdjustedTime());
1243 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1245 // Relinquish previous transactions' spent pointers
1248 BOOST_FOREACH(const CTxIn& txin, vin)
1250 COutPoint prevout = txin.prevout;
1252 // Get prev txindex from disk
1254 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1255 return error("DisconnectInputs() : ReadTxIndex failed");
1257 if (prevout.n >= txindex.vSpent.size())
1258 return error("DisconnectInputs() : prevout.n out of range");
1260 // Mark outpoint as not spent
1261 txindex.vSpent[prevout.n].SetNull();
1264 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1265 return error("DisconnectInputs() : UpdateTxIndex failed");
1269 // Remove transaction from index
1270 // This can fail if a duplicate of this transaction was in a chain that got
1271 // reorganized away. This is only possible if this transaction was completely
1272 // spent, so erasing it would be a no-op anyway.
1273 txdb.EraseTxIndex(*this);
1279 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1280 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1282 // FetchInputs can return false either because we just haven't seen some inputs
1283 // (in which case the transaction should be stored as an orphan)
1284 // or because the transaction is malformed (in which case the transaction should
1285 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1289 return true; // Coinbase transactions have no inputs to fetch.
1291 for (unsigned int i = 0; i < vin.size(); i++)
1293 COutPoint prevout = vin[i].prevout;
1294 if (inputsRet.count(prevout.hash))
1295 continue; // Got it already
1298 CTxIndex& txindex = inputsRet[prevout.hash].first;
1300 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1302 // Get txindex from current proposed changes
1303 txindex = mapTestPool.find(prevout.hash)->second;
1307 // Read txindex from txdb
1308 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1310 if (!fFound && (fBlock || fMiner))
1311 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());
1314 CTransaction& txPrev = inputsRet[prevout.hash].second;
1315 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1317 // Get prev tx from single transactions in memory
1320 if (!mempool.exists(prevout.hash))
1321 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());
1322 txPrev = mempool.lookup(prevout.hash);
1325 txindex.vSpent.resize(txPrev.vout.size());
1329 // Get prev tx from disk
1330 if (!txPrev.ReadFromDisk(txindex.pos))
1331 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1335 // Make sure all prevout.n indexes are valid:
1336 for (unsigned int i = 0; i < vin.size(); i++)
1338 const COutPoint prevout = vin[i].prevout;
1339 assert(inputsRet.count(prevout.hash) != 0);
1340 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1341 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1342 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1344 // Revisit this if/when transaction replacement is implemented and allows
1347 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()));
1354 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1356 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1357 if (mi == inputs.end())
1358 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1360 const CTransaction& txPrev = (mi->second).second;
1361 if (input.prevout.n >= txPrev.vout.size())
1362 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1364 return txPrev.vout[input.prevout.n];
1367 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1373 for (unsigned int i = 0; i < vin.size(); i++)
1375 nResult += GetOutputFor(vin[i], inputs).nValue;
1381 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1386 unsigned int nSigOps = 0;
1387 for (unsigned int i = 0; i < vin.size(); i++)
1389 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1390 if (prevout.scriptPubKey.IsPayToScriptHash())
1391 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1396 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1397 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1398 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1400 // Take over previous transactions' spent pointers
1401 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1402 // fMiner is true when called from the internal bitcoin miner
1403 // ... both are false when called from CTransaction::AcceptToMemoryPool
1408 for (unsigned int i = 0; i < vin.size(); i++)
1410 COutPoint prevout = vin[i].prevout;
1411 assert(inputs.count(prevout.hash) > 0);
1412 CTxIndex& txindex = inputs[prevout.hash].first;
1413 CTransaction& txPrev = inputs[prevout.hash].second;
1415 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1416 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()));
1418 // If prev is coinbase or coinstake, check that it's matured
1419 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1420 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1421 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1422 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1424 // ppcoin: check transaction timestamp
1425 if (txPrev.nTime > nTime)
1426 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1428 // Check for negative or overflow input values
1429 nValueIn += txPrev.vout[prevout.n].nValue;
1430 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1431 return DoS(100, error("ConnectInputs() : txin values out of range"));
1434 // The first loop above does all the inexpensive checks.
1435 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1436 // Helps prevent CPU exhaustion attacks.
1437 for (unsigned int i = 0; i < vin.size(); i++)
1439 COutPoint prevout = vin[i].prevout;
1440 assert(inputs.count(prevout.hash) > 0);
1441 CTxIndex& txindex = inputs[prevout.hash].first;
1442 CTransaction& txPrev = inputs[prevout.hash].second;
1444 // Check for conflicts (double-spend)
1445 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1446 // for an attacker to attempt to split the network.
1447 if (!txindex.vSpent[prevout.n].IsNull())
1448 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());
1450 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1451 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1452 // still computed and checked, and any change will be caught at the next checkpoint.
1453 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1456 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1458 // only during transition phase for P2SH: do not invoke anti-DoS code for
1459 // potentially old clients relaying bad P2SH transactions
1460 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1461 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1463 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1467 // Mark outpoints as spent
1468 txindex.vSpent[prevout.n] = posThisTx;
1471 if (fBlock || fMiner)
1473 mapTestPool[prevout.hash] = txindex;
1479 // ppcoin: coin stake tx earns reward instead of paying fee
1481 if (!GetCoinAge(txdb, nCoinAge))
1482 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1484 int64 nStakeReward = GetValueOut() - nValueIn;
1485 int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1487 if (nStakeReward > nCalculatedStakeReward)
1488 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1492 if (nValueIn < GetValueOut())
1493 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1495 // Tally transaction fees
1496 int64 nTxFee = nValueIn - GetValueOut();
1498 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1499 // ppcoin: enforce transaction fees for every block
1500 if (nTxFee < GetMinFee())
1501 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;
1504 if (!MoneyRange(nFees))
1505 return DoS(100, error("ConnectInputs() : nFees out of range"));
1513 bool CTransaction::ClientConnectInputs()
1518 // Take over previous transactions' spent pointers
1522 for (unsigned int i = 0; i < vin.size(); i++)
1524 // Get prev tx from single transactions in memory
1525 COutPoint prevout = vin[i].prevout;
1526 if (!mempool.exists(prevout.hash))
1528 CTransaction& txPrev = mempool.lookup(prevout.hash);
1530 if (prevout.n >= txPrev.vout.size())
1534 if (!VerifySignature(txPrev, *this, i, true, 0))
1535 return error("ConnectInputs() : VerifySignature failed");
1537 ///// this is redundant with the mempool.mapNextTx stuff,
1538 ///// not sure which I want to get rid of
1539 ///// this has to go away now that posNext is gone
1540 // // Check for conflicts
1541 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1542 // return error("ConnectInputs() : prev tx already used");
1544 // // Flag outpoints as used
1545 // txPrev.vout[prevout.n].posNext = posThisTx;
1547 nValueIn += txPrev.vout[prevout.n].nValue;
1549 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1550 return error("ClientConnectInputs() : txin values out of range");
1552 if (GetValueOut() > nValueIn)
1562 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1564 // Disconnect in reverse order
1565 for (int i = vtx.size()-1; i >= 0; i--)
1566 if (!vtx[i].DisconnectInputs(txdb))
1569 // Update block index on disk without changing it in memory.
1570 // The memory index structure will be changed after the db commits.
1573 CDiskBlockIndex blockindexPrev(pindex->pprev);
1574 blockindexPrev.hashNext = 0;
1575 if (!txdb.WriteBlockIndex(blockindexPrev))
1576 return error("DisconnectBlock() : WriteBlockIndex failed");
1579 // ppcoin: clean up wallet after disconnecting coinstake
1580 BOOST_FOREACH(CTransaction& tx, vtx)
1581 SyncWithWallets(tx, this, false, false);
1586 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1588 // Check it again in case a previous version let a bad block in
1589 if (!CheckBlock(!fJustCheck, !fJustCheck))
1592 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1593 // unless those are already completely spent.
1594 // If such overwrites are allowed, coinbases and transactions depending upon those
1595 // can be duplicated to remove the ability to spend the first instance -- even after
1596 // being sent to another address.
1597 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1598 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1599 // already refuses previously-known transaction ids entirely.
1600 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1601 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1602 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1603 // initial block download.
1604 bool fEnforceBIP30 = true; // Always active in NovaCoin
1605 bool fStrictPayToScriptHash = true; // Always active in NovaCoin
1607 //// issue here: it doesn't know the version
1608 unsigned int nTxPos;
1610 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1611 // 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
1614 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1616 map<uint256, CTxIndex> mapQueuedChanges;
1619 int64 nValueOut = 0;
1620 unsigned int nSigOps = 0;
1621 BOOST_FOREACH(CTransaction& tx, vtx)
1623 uint256 hashTx = tx.GetHash();
1625 if (fEnforceBIP30) {
1626 CTxIndex txindexOld;
1627 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1628 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1634 nSigOps += tx.GetLegacySigOpCount();
1635 if (nSigOps > MAX_BLOCK_SIGOPS)
1636 return DoS(100, error("ConnectBlock() : too many sigops"));
1638 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1640 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1642 MapPrevTx mapInputs;
1643 if (tx.IsCoinBase())
1644 nValueOut += tx.GetValueOut();
1648 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1651 if (fStrictPayToScriptHash)
1653 // Add in sigops done by pay-to-script-hash inputs;
1654 // this is to prevent a "rogue miner" from creating
1655 // an incredibly-expensive-to-validate block.
1656 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1657 if (nSigOps > MAX_BLOCK_SIGOPS)
1658 return DoS(100, error("ConnectBlock() : too many sigops"));
1661 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1662 int64 nTxValueOut = tx.GetValueOut();
1663 nValueIn += nTxValueIn;
1664 nValueOut += nTxValueOut;
1665 if (!tx.IsCoinStake())
1666 nFees += nTxValueIn - nTxValueOut;
1668 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1672 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1675 // ppcoin: track money supply and mint amount info
1676 pindex->nMint = nValueOut - nValueIn + nFees;
1677 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1678 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1679 return error("Connect() : WriteBlockIndex for pindex failed");
1681 // ppcoin: fees are not collected by miners as in bitcoin
1682 // ppcoin: fees are destroyed to compensate the entire network
1683 if (fDebug && GetBoolArg("-printcreation"))
1684 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1689 // Write queued txindex changes
1690 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1692 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1693 return error("ConnectBlock() : UpdateTxIndex failed");
1696 // Update block index on disk without changing it in memory.
1697 // The memory index structure will be changed after the db commits.
1700 CDiskBlockIndex blockindexPrev(pindex->pprev);
1701 blockindexPrev.hashNext = pindex->GetBlockHash();
1702 if (!txdb.WriteBlockIndex(blockindexPrev))
1703 return error("ConnectBlock() : WriteBlockIndex failed");
1706 // Watch for transactions paying to me
1707 BOOST_FOREACH(CTransaction& tx, vtx)
1708 SyncWithWallets(tx, this, true);
1713 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1715 printf("REORGANIZE\n");
1718 CBlockIndex* pfork = pindexBest;
1719 CBlockIndex* plonger = pindexNew;
1720 while (pfork != plonger)
1722 while (plonger->nHeight > pfork->nHeight)
1723 if (!(plonger = plonger->pprev))
1724 return error("Reorganize() : plonger->pprev is null");
1725 if (pfork == plonger)
1727 if (!(pfork = pfork->pprev))
1728 return error("Reorganize() : pfork->pprev is null");
1731 // List of what to disconnect
1732 vector<CBlockIndex*> vDisconnect;
1733 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1734 vDisconnect.push_back(pindex);
1736 // List of what to connect
1737 vector<CBlockIndex*> vConnect;
1738 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1739 vConnect.push_back(pindex);
1740 reverse(vConnect.begin(), vConnect.end());
1742 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());
1743 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());
1745 // Disconnect shorter branch
1746 vector<CTransaction> vResurrect;
1747 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1750 if (!block.ReadFromDisk(pindex))
1751 return error("Reorganize() : ReadFromDisk for disconnect failed");
1752 if (!block.DisconnectBlock(txdb, pindex))
1753 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1755 // Queue memory transactions to resurrect
1756 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1757 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1758 vResurrect.push_back(tx);
1761 // Connect longer branch
1762 vector<CTransaction> vDelete;
1763 for (unsigned int i = 0; i < vConnect.size(); i++)
1765 CBlockIndex* pindex = vConnect[i];
1767 if (!block.ReadFromDisk(pindex))
1768 return error("Reorganize() : ReadFromDisk for connect failed");
1769 if (!block.ConnectBlock(txdb, pindex))
1772 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1775 // Queue memory transactions to delete
1776 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1777 vDelete.push_back(tx);
1779 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1780 return error("Reorganize() : WriteHashBestChain failed");
1782 // Make sure it's successfully written to disk before changing memory structure
1783 if (!txdb.TxnCommit())
1784 return error("Reorganize() : TxnCommit failed");
1786 // Disconnect shorter branch
1787 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1789 pindex->pprev->pnext = NULL;
1791 // Connect longer branch
1792 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1794 pindex->pprev->pnext = pindex;
1796 // Resurrect memory transactions that were in the disconnected branch
1797 BOOST_FOREACH(CTransaction& tx, vResurrect)
1798 tx.AcceptToMemoryPool(txdb, false);
1800 // Delete redundant memory transactions that are in the connected branch
1801 BOOST_FOREACH(CTransaction& tx, vDelete)
1804 printf("REORGANIZE: done\n");
1810 // Called from inside SetBestChain: attaches a block to the new best chain being built
1811 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1813 uint256 hash = GetHash();
1815 // Adding to current best branch
1816 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1819 InvalidChainFound(pindexNew);
1822 if (!txdb.TxnCommit())
1823 return error("SetBestChain() : TxnCommit failed");
1825 // Add to current best branch
1826 pindexNew->pprev->pnext = pindexNew;
1828 // Delete redundant memory transactions
1829 BOOST_FOREACH(CTransaction& tx, vtx)
1835 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1837 uint256 hash = GetHash();
1839 if (!txdb.TxnBegin())
1840 return error("SetBestChain() : TxnBegin failed");
1842 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1844 txdb.WriteHashBestChain(hash);
1845 if (!txdb.TxnCommit())
1846 return error("SetBestChain() : TxnCommit failed");
1847 pindexGenesisBlock = pindexNew;
1849 else if (hashPrevBlock == hashBestChain)
1851 if (!SetBestChainInner(txdb, pindexNew))
1852 return error("SetBestChain() : SetBestChainInner failed");
1856 // the first block in the new chain that will cause it to become the new best chain
1857 CBlockIndex *pindexIntermediate = pindexNew;
1859 // list of blocks that need to be connected afterwards
1860 std::vector<CBlockIndex*> vpindexSecondary;
1862 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1863 // Try to limit how much needs to be done inside
1864 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1866 vpindexSecondary.push_back(pindexIntermediate);
1867 pindexIntermediate = pindexIntermediate->pprev;
1870 if (!vpindexSecondary.empty())
1871 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1873 // Switch to new best branch
1874 if (!Reorganize(txdb, pindexIntermediate))
1877 InvalidChainFound(pindexNew);
1878 return error("SetBestChain() : Reorganize failed");
1881 // Connect further blocks
1882 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1885 if (!block.ReadFromDisk(pindex))
1887 printf("SetBestChain() : ReadFromDisk failed\n");
1890 if (!txdb.TxnBegin()) {
1891 printf("SetBestChain() : TxnBegin 2 failed\n");
1894 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1895 if (!block.SetBestChainInner(txdb, pindex))
1900 // Update best block in wallet (so we can detect restored wallets)
1901 bool fIsInitialDownload = IsInitialBlockDownload();
1902 if (!fIsInitialDownload)
1904 const CBlockLocator locator(pindexNew);
1905 ::SetBestChain(locator);
1909 hashBestChain = hash;
1910 pindexBest = pindexNew;
1911 pblockindexFBBHLast = NULL;
1912 nBestHeight = pindexBest->nHeight;
1913 nBestChainTrust = pindexNew->nChainTrust;
1914 nTimeBestReceived = GetTime();
1915 nTransactionsUpdated++;
1917 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1919 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1920 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1921 CBigNum(nBestChainTrust).ToString().c_str(),
1922 nBestBlockTrust.Get64(),
1923 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1925 // Check the version of the last 100 blocks to see if we need to upgrade:
1926 if (!fIsInitialDownload)
1929 const CBlockIndex* pindex = pindexBest;
1930 for (int i = 0; i < 100 && pindex != NULL; i++)
1932 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1934 pindex = pindex->pprev;
1937 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1938 if (nUpgraded > 100/2)
1939 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1940 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1943 std::string strCmd = GetArg("-blocknotify", "");
1945 if (!fIsInitialDownload && !strCmd.empty())
1947 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1948 boost::thread t(runCommand, strCmd); // thread runs free
1954 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1955 // Only those coins meeting minimum age requirement counts. As those
1956 // transactions not in main chain are not currently indexed so we
1957 // might not find out about their coin age. Older transactions are
1958 // guaranteed to be in main chain by sync-checkpoint. This rule is
1959 // introduced to help nodes establish a consistent view of the coin
1960 // age (trust score) of competing branches.
1961 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1963 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1969 BOOST_FOREACH(const CTxIn& txin, vin)
1971 // First try finding the previous transaction in database
1972 CTransaction txPrev;
1974 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1975 continue; // previous transaction not in main chain
1976 if (nTime < txPrev.nTime)
1977 return false; // Transaction timestamp violation
1979 // Read block header
1981 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1982 return false; // unable to read block of previous transaction
1983 if (block.GetBlockTime() + nStakeMinAge > nTime)
1984 continue; // only count coins meeting min age requirement
1986 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1987 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1989 if (fDebug && GetBoolArg("-printcoinage"))
1990 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1993 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1994 if (fDebug && GetBoolArg("-printcoinage"))
1995 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1996 nCoinAge = bnCoinDay.getuint64();
2000 // ppcoin: total coin age spent in block, in the unit of coin-days.
2001 bool CBlock::GetCoinAge(uint64& nCoinAge) const
2006 BOOST_FOREACH(const CTransaction& tx, vtx)
2009 if (tx.GetCoinAge(txdb, nTxCoinAge))
2010 nCoinAge += nTxCoinAge;
2015 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2017 if (fDebug && GetBoolArg("-printcoinage"))
2018 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
2022 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2024 // Check for duplicate
2025 uint256 hash = GetHash();
2026 if (mapBlockIndex.count(hash))
2027 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2029 // Construct new block index object
2030 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
2032 return error("AddToBlockIndex() : new CBlockIndex failed");
2033 pindexNew->phashBlock = &hash;
2034 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2035 if (miPrev != mapBlockIndex.end())
2037 pindexNew->pprev = (*miPrev).second;
2038 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2041 // ppcoin: compute chain trust score
2042 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2044 // ppcoin: compute stake entropy bit for stake modifier
2045 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2046 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2048 // ppcoin: record proof-of-stake hash value
2049 if (pindexNew->IsProofOfStake())
2051 if (!mapProofOfStake.count(hash))
2052 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2053 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2056 // ppcoin: compute stake modifier
2057 uint64 nStakeModifier = 0;
2058 bool fGeneratedStakeModifier = false;
2059 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2060 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2061 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2062 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2063 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2064 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2066 // Add to mapBlockIndex
2067 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2068 if (pindexNew->IsProofOfStake())
2069 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2070 pindexNew->phashBlock = &((*mi).first);
2072 // Write to disk block index
2074 if (!txdb.TxnBegin())
2076 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2077 if (!txdb.TxnCommit())
2081 if (pindexNew->nChainTrust > nBestChainTrust)
2082 if (!SetBestChain(txdb, pindexNew))
2087 if (pindexNew == pindexBest)
2089 // Notify UI to display prev block's coinbase if it was ours
2090 static uint256 hashPrevBestCoinBase;
2091 UpdatedTransaction(hashPrevBestCoinBase);
2092 hashPrevBestCoinBase = vtx[0].GetHash();
2095 uiInterface.NotifyBlocksChanged();
2102 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
2104 // These are checks that are independent of context
2105 // that can be verified before saving an orphan block.
2108 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2109 return DoS(100, error("CheckBlock() : size limits failed"));
2111 // Special short-term limits to avoid 10,000 BDB lock limit:
2112 if (GetBlockTime() < LOCKS_SWITCH_TIME)
2114 // Rule is: #unique txids referenced <= 4,500
2115 // ... to prevent 10,000 BDB lock exhaustion on old clients
2116 set<uint256> setTxIn;
2117 for (size_t i = 0; i < vtx.size(); i++)
2119 setTxIn.insert(vtx[i].GetHash());
2120 if (i == 0) continue; // skip coinbase txin
2121 BOOST_FOREACH(const CTxIn& txin, vtx[i].vin)
2122 setTxIn.insert(txin.prevout.hash);
2124 size_t nTxids = setTxIn.size();
2126 return error("CheckBlock() : maxlocks violation");
2129 // Check proof of work matches claimed amount
2130 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2131 return DoS(50, error("CheckBlock() : proof of work failed"));
2134 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
2135 return error("CheckBlock() : block timestamp too far in the future");
2137 // First transaction must be coinbase, the rest must not be
2138 if (vtx.empty() || !vtx[0].IsCoinBase())
2139 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2140 for (unsigned int i = 1; i < vtx.size(); i++)
2141 if (vtx[i].IsCoinBase())
2142 return DoS(100, error("CheckBlock() : more than one coinbase"));
2144 // Check coinbase timestamp
2145 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
2146 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2148 if (IsProofOfStake())
2150 // Coinbase output should be empty if proof-of-stake block
2151 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2152 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2154 // Second transaction must be coinstake, the rest must not be
2155 if (vtx.empty() || !vtx[1].IsCoinStake())
2156 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2157 for (unsigned int i = 2; i < vtx.size(); i++)
2158 if (vtx[i].IsCoinStake())
2159 return DoS(100, error("CheckBlock() : more than one coinstake"));
2161 // Check coinstake timestamp
2162 if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2163 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2167 // Coinbase fee paid until 20 Sep 2013
2168 int64 nFee = GetBlockTime() < CHAINCHECKS_SWITCH_TIME ? vtx[0].GetMinFee() - MIN_TX_FEE : 0;
2170 // Check coinbase reward
2171 if (vtx[0].GetValueOut() > (GetProofOfWorkReward(nBits) - nFee))
2172 return DoS(50, error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
2173 vtx[0].GetValueOut(),
2174 GetProofOfWorkReward(nBits) - nFee));
2177 // Check transactions
2178 BOOST_FOREACH(const CTransaction& tx, vtx)
2180 if (!tx.CheckTransaction())
2181 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2183 // ppcoin: check transaction timestamp
2184 if (GetBlockTime() < (int64)tx.nTime)
2185 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2188 // Check for duplicate txids. This is caught by ConnectInputs(),
2189 // but catching it earlier avoids a potential DoS attack:
2190 set<uint256> uniqueTx;
2191 BOOST_FOREACH(const CTransaction& tx, vtx)
2193 uniqueTx.insert(tx.GetHash());
2195 if (uniqueTx.size() != vtx.size())
2196 return DoS(100, error("CheckBlock() : duplicate transaction"));
2198 unsigned int nSigOps = 0;
2199 BOOST_FOREACH(const CTransaction& tx, vtx)
2201 nSigOps += tx.GetLegacySigOpCount();
2203 if (nSigOps > MAX_BLOCK_SIGOPS)
2204 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2206 // Check merkle root
2207 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2208 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2210 // NovaCoin: check proof-of-stake block signature
2211 if (IsProofOfStake() || (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME))
2213 if (!CheckBlockSignature())
2214 return DoS(100, error("CheckBlock() : bad block signature"));
2220 bool CBlock::AcceptBlock()
2222 // Check for duplicate
2223 uint256 hash = GetHash();
2224 if (mapBlockIndex.count(hash))
2225 return error("AcceptBlock() : block already in mapBlockIndex");
2227 // Get prev block index
2228 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2229 if (mi == mapBlockIndex.end())
2230 return DoS(10, error("AcceptBlock() : prev block not found"));
2231 CBlockIndex* pindexPrev = (*mi).second;
2232 int nHeight = pindexPrev->nHeight+1;
2234 // Check proof-of-work or proof-of-stake
2235 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2236 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2238 // Check timestamp against prev
2239 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
2240 return error("AcceptBlock() : block's timestamp is too early");
2242 // Check that all transactions are finalized
2243 BOOST_FOREACH(const CTransaction& tx, vtx)
2244 if (!tx.IsFinal(nHeight, GetBlockTime()))
2245 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2247 // Check that the block chain matches the known block chain up to a checkpoint
2248 if (!Checkpoints::CheckHardened(nHeight, hash))
2249 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2251 // ppcoin: check that the block satisfies synchronized checkpoint
2252 if (!Checkpoints::CheckSync(hash, pindexPrev))
2254 if(!GetBoolArg("-nosynccheckpoints", false))
2256 return error("AcceptBlock() : rejected by synchronized checkpoint");
2260 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2264 // Enforce rule that the coinbase starts with serialized block height
2265 CScript expect = CScript() << nHeight;
2266 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2267 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2269 // Write block to history file
2270 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2271 return error("AcceptBlock() : out of disk space");
2272 unsigned int nFile = -1;
2273 unsigned int nBlockPos = 0;
2274 if (!WriteToDisk(nFile, nBlockPos))
2275 return error("AcceptBlock() : WriteToDisk failed");
2276 if (!AddToBlockIndex(nFile, nBlockPos))
2277 return error("AcceptBlock() : AddToBlockIndex failed");
2279 // Relay inventory, but don't relay old inventory during initial block download
2280 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2281 if (hashBestChain == hash)
2284 BOOST_FOREACH(CNode* pnode, vNodes)
2285 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2286 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2289 // ppcoin: check pending sync-checkpoint
2290 Checkpoints::AcceptPendingSyncCheckpoint();
2295 uint256 CBlockIndex::GetBlockTrust() const
2298 bnTarget.SetCompact(nBits);
2303 /* Old protocol, will be removed later */
2304 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2305 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2309 // Calculate work amount for block
2310 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2312 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2313 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2315 // Return nPoWTrust for the first 12 blocks
2316 if (pprev == NULL || pprev->nHeight < 12)
2319 const CBlockIndex* currentIndex = pprev;
2321 if(IsProofOfStake())
2323 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2325 // Return 1/3 of score if parent block is not the PoW block
2326 if (!pprev->IsProofOfWork())
2327 return (bnNewTrust / 3).getuint256();
2331 // Check last 12 blocks type
2332 while (pprev->nHeight - currentIndex->nHeight < 12)
2334 if (currentIndex->IsProofOfWork())
2336 currentIndex = currentIndex->pprev;
2339 // Return 1/3 of score if less than 3 PoW blocks found
2341 return (bnNewTrust / 3).getuint256();
2343 return bnNewTrust.getuint256();
2347 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2349 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2350 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2351 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2355 // Check last 12 blocks type
2356 while (pprev->nHeight - currentIndex->nHeight < 12)
2358 if (currentIndex->IsProofOfStake())
2360 currentIndex = currentIndex->pprev;
2363 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2365 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2367 bnTarget.SetCompact(pprev->nBits);
2372 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2374 // Return nPoWTrust + full trust score for previous block nBits
2375 return nPoWTrust + bnNewTrust.getuint256();
2379 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2381 unsigned int nFound = 0;
2382 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2384 if (pstart->nVersion >= minVersion)
2386 pstart = pstart->pprev;
2388 return (nFound >= nRequired);
2391 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2393 // Check for duplicate
2394 uint256 hash = pblock->GetHash();
2395 if (mapBlockIndex.count(hash))
2396 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2397 if (mapOrphanBlocks.count(hash))
2398 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2400 // ppcoin: check proof-of-stake
2401 // Limited duplicity on stake: prevents block flood attack
2402 // Duplicate stake allowed only when there is orphan child block
2403 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2404 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());
2406 // Preliminary checks
2407 if (!pblock->CheckBlock())
2408 return error("ProcessBlock() : CheckBlock FAILED");
2410 // ppcoin: verify hash target and signature of coinstake tx
2411 if (pblock->IsProofOfStake())
2413 uint256 hashProofOfStake = 0;
2414 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake))
2416 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2417 return false; // do not error here as we expect this during initial block download
2419 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2420 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2423 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2424 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2426 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2427 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2429 bnNewBlock.SetCompact(pblock->nBits);
2431 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime));
2432 if (bnNewBlock > bnRequired)
2435 pfrom->Misbehaving(100);
2436 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2440 // ppcoin: ask for pending sync-checkpoint if any
2441 if (!IsInitialBlockDownload())
2442 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2444 // If don't already have its previous block, shunt it off to holding area until we get it
2445 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2447 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2448 CBlock* pblock2 = new CBlock(*pblock);
2449 // ppcoin: check proof-of-stake
2450 if (pblock2->IsProofOfStake())
2452 // Limited duplicity on stake: prevents block flood attack
2453 // Duplicate stake allowed only when there is orphan child block
2454 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2455 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());
2457 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2459 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2460 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2462 // Ask this guy to fill in what we're missing
2465 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2466 // ppcoin: getblocks may not obtain the ancestor block rejected
2467 // earlier by duplicate-stake check so we ask for it again directly
2468 if (!IsInitialBlockDownload())
2469 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2475 if (!pblock->AcceptBlock())
2476 return error("ProcessBlock() : AcceptBlock FAILED");
2478 // Recursively process any orphan blocks that depended on this one
2479 vector<uint256> vWorkQueue;
2480 vWorkQueue.push_back(hash);
2481 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2483 uint256 hashPrev = vWorkQueue[i];
2484 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2485 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2488 CBlock* pblockOrphan = (*mi).second;
2489 if (pblockOrphan->AcceptBlock())
2490 vWorkQueue.push_back(pblockOrphan->GetHash());
2491 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2492 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2493 delete pblockOrphan;
2495 mapOrphanBlocksByPrev.erase(hashPrev);
2498 printf("ProcessBlock: ACCEPTED\n");
2500 // ppcoin: if responsible for sync-checkpoint send it
2501 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2502 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2507 // ppcoin: sign block
2508 bool CBlock::SignBlock(const CKeyStore& keystore)
2510 vector<valtype> vSolutions;
2511 txnouttype whichType;
2513 if(!IsProofOfStake())
2515 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2517 const CTxOut& txout = vtx[0].vout[i];
2519 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2522 if (whichType == TX_PUBKEY)
2525 valtype& vchPubKey = vSolutions[0];
2528 if (!keystore.GetKey(Hash160(vchPubKey), key))
2530 if (key.GetPubKey() != vchPubKey)
2532 if(!key.Sign(GetHash(), vchBlockSig))
2541 const CTxOut& txout = vtx[1].vout[1];
2543 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2546 if (whichType == TX_PUBKEY)
2549 valtype& vchPubKey = vSolutions[0];
2552 if (!keystore.GetKey(Hash160(vchPubKey), key))
2554 if (key.GetPubKey() != vchPubKey)
2557 return key.Sign(GetHash(), vchBlockSig);
2561 printf("Sign failed\n");
2565 // ppcoin: check block signature
2566 bool CBlock::CheckBlockSignature() const
2568 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2569 return vchBlockSig.empty();
2571 vector<valtype> vSolutions;
2572 txnouttype whichType;
2574 if(IsProofOfStake())
2576 const CTxOut& txout = vtx[1].vout[1];
2578 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2580 if (whichType == TX_PUBKEY)
2582 valtype& vchPubKey = vSolutions[0];
2584 if (!key.SetPubKey(vchPubKey))
2586 if (vchBlockSig.empty())
2588 return key.Verify(GetHash(), vchBlockSig);
2593 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2595 const CTxOut& txout = vtx[0].vout[i];
2597 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2600 if (whichType == TX_PUBKEY)
2603 valtype& vchPubKey = vSolutions[0];
2605 if (!key.SetPubKey(vchPubKey))
2607 if (vchBlockSig.empty())
2609 if(!key.Verify(GetHash(), vchBlockSig))
2619 bool CheckDiskSpace(uint64 nAdditionalBytes)
2621 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2623 // Check for nMinDiskSpace bytes (currently 50MB)
2624 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2627 string strMessage = _("Warning: Disk space is low!");
2628 strMiscWarning = strMessage;
2629 printf("*** %s\n", strMessage.c_str());
2630 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2637 static filesystem::path BlockFilePath(unsigned int nFile)
2639 string strBlockFn = strprintf("blk%04u.dat", nFile);
2640 return GetDataDir() / strBlockFn;
2643 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2645 if ((nFile < 1) || (nFile == (unsigned int) -1))
2647 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2650 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2652 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2661 static unsigned int nCurrentBlockFile = 1;
2663 FILE* AppendBlockFile(unsigned int& nFileRet)
2668 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2671 if (fseek(file, 0, SEEK_END) != 0)
2673 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2674 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2676 nFileRet = nCurrentBlockFile;
2680 nCurrentBlockFile++;
2684 bool LoadBlockIndex(bool fAllowNew)
2688 pchMessageStart[0] = 0xcd;
2689 pchMessageStart[1] = 0xf2;
2690 pchMessageStart[2] = 0xc0;
2691 pchMessageStart[3] = 0xef;
2693 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2694 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2695 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2696 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2697 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2704 if (!txdb.LoadBlockIndex())
2709 // Init with genesis block
2711 if (mapBlockIndex.empty())
2720 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2721 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2722 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2724 // vMerkleTree: 4cb33b3b6a
2728 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2729 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2730 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2732 // vMerkleTree: 4cb33b3b6a
2734 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2736 txNew.nTime = 1360105017;
2737 txNew.vin.resize(1);
2738 txNew.vout.resize(1);
2739 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2740 txNew.vout[0].SetEmpty();
2742 block.vtx.push_back(txNew);
2743 block.hashPrevBlock = 0;
2744 block.hashMerkleRoot = block.BuildMerkleTree();
2746 block.nTime = 1360105017;
2747 block.nBits = bnProofOfWorkLimit.GetCompact();
2748 block.nNonce = !fTestNet ? 1575379 : 46534;
2751 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2753 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2754 assert(block.CheckBlock());
2756 // Start new block file
2758 unsigned int nBlockPos;
2759 if (!block.WriteToDisk(nFile, nBlockPos))
2760 return error("LoadBlockIndex() : writing genesis block to disk failed");
2761 if (!block.AddToBlockIndex(nFile, nBlockPos))
2762 return error("LoadBlockIndex() : genesis block not accepted");
2764 // ppcoin: initialize synchronized checkpoint
2765 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2766 return error("LoadBlockIndex() : failed to init sync checkpoint");
2769 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2772 string strPubKey = "";
2773 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2775 // write checkpoint master key to db
2777 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2778 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2779 if (!txdb.TxnCommit())
2780 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2781 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2782 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2792 void PrintBlockTree()
2794 // pre-compute tree structure
2795 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2796 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2798 CBlockIndex* pindex = (*mi).second;
2799 mapNext[pindex->pprev].push_back(pindex);
2801 //while (rand() % 3 == 0)
2802 // mapNext[pindex->pprev].push_back(pindex);
2805 vector<pair<int, CBlockIndex*> > vStack;
2806 vStack.push_back(make_pair(0, pindexGenesisBlock));
2809 while (!vStack.empty())
2811 int nCol = vStack.back().first;
2812 CBlockIndex* pindex = vStack.back().second;
2815 // print split or gap
2816 if (nCol > nPrevCol)
2818 for (int i = 0; i < nCol-1; i++)
2822 else if (nCol < nPrevCol)
2824 for (int i = 0; i < nCol; i++)
2831 for (int i = 0; i < nCol; i++)
2836 block.ReadFromDisk(pindex);
2837 printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
2841 block.GetHash().ToString().c_str(),
2843 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2844 FormatMoney(pindex->nMint).c_str(),
2847 PrintWallets(block);
2849 // put the main time-chain first
2850 vector<CBlockIndex*>& vNext = mapNext[pindex];
2851 for (unsigned int i = 0; i < vNext.size(); i++)
2853 if (vNext[i]->pnext)
2855 swap(vNext[0], vNext[i]);
2861 for (unsigned int i = 0; i < vNext.size(); i++)
2862 vStack.push_back(make_pair(nCol+i, vNext[i]));
2866 bool LoadExternalBlockFile(FILE* fileIn)
2868 int64 nStart = GetTimeMillis();
2874 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2875 unsigned int nPos = 0;
2876 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2878 unsigned char pchData[65536];
2880 fseek(blkdat, nPos, SEEK_SET);
2881 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2884 nPos = (unsigned int)-1;
2887 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2890 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2892 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2895 nPos += ((unsigned char*)nFind - pchData) + 1;
2898 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2899 } while(!fRequestShutdown);
2900 if (nPos == (unsigned int)-1)
2902 fseek(blkdat, nPos, SEEK_SET);
2905 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2909 if (ProcessBlock(NULL,&block))
2917 catch (std::exception &e) {
2918 printf("%s() : Deserialize or I/O error caught during load\n",
2919 __PRETTY_FUNCTION__);
2922 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2934 //////////////////////////////////////////////////////////////////////////////
2939 extern map<uint256, CAlert> mapAlerts;
2940 extern CCriticalSection cs_mapAlerts;
2942 static string strMintMessage = "Info: Minting suspended due to locked wallet.";
2943 static string strMintWarning;
2945 string GetWarnings(string strFor)
2948 string strStatusBar;
2951 if (GetBoolArg("-testsafemode"))
2954 // ppcoin: wallet lock warning for minting
2955 if (strMintWarning != "")
2958 strStatusBar = strMintWarning;
2961 // Misc warnings like out of disk space and clock is wrong
2962 if (strMiscWarning != "")
2965 strStatusBar = strMiscWarning;
2968 // ppcoin: should not enter safe mode for longer invalid chain
2969 // ppcoin: if sync-checkpoint is too old do not enter safe mode
2970 if (Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) && !fTestNet && !IsInitialBlockDownload())
2973 strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.";
2976 // ppcoin: if detected invalid checkpoint enter safe mode
2977 if (Checkpoints::hashInvalidCheckpoint != 0)
2980 strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.";
2986 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2988 const CAlert& alert = item.second;
2989 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2991 nPriority = alert.nPriority;
2992 strStatusBar = alert.strStatusBar;
2993 if (nPriority > 1000)
2994 strRPC = strStatusBar; // ppcoin: safe mode for high alert
2999 if (strFor == "statusbar")
3000 return strStatusBar;
3001 else if (strFor == "rpc")
3003 assert(!"GetWarnings() : invalid parameter");
3014 //////////////////////////////////////////////////////////////////////////////
3020 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3026 bool txInMap = false;
3029 txInMap = (mempool.exists(inv.hash));
3032 mapOrphanTransactions.count(inv.hash) ||
3033 txdb.ContainsTx(inv.hash);
3037 return mapBlockIndex.count(inv.hash) ||
3038 mapOrphanBlocks.count(inv.hash);
3040 // Don't know what it is, just say we already got one
3047 // The message start string is designed to be unlikely to occur in normal data.
3048 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3049 // a large 4-byte int at any alignment.
3050 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3052 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3054 static map<CService, CPubKey> mapReuseKey;
3055 RandAddSeedPerfmon();
3057 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3058 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3060 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3068 if (strCommand == "version")
3070 // Each connection can only send one version message
3071 if (pfrom->nVersion != 0)
3073 pfrom->Misbehaving(1);
3081 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3082 if (pfrom->nVersion < MIN_PROTO_VERSION)
3084 // Since February 20, 2012, the protocol is initiated at version 209,
3085 // and earlier versions are no longer supported
3086 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3087 pfrom->fDisconnect = true;
3091 if (pfrom->nVersion == 10300)
3092 pfrom->nVersion = 300;
3094 vRecv >> addrFrom >> nNonce;
3096 vRecv >> pfrom->strSubVer;
3098 vRecv >> pfrom->nStartingHeight;
3100 if (pfrom->fInbound && addrMe.IsRoutable())
3102 pfrom->addrLocal = addrMe;
3106 // Disconnect if we connected to ourself
3107 if (nNonce == nLocalHostNonce && nNonce > 1)
3109 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3110 pfrom->fDisconnect = true;
3114 // ppcoin: record my external IP reported by peer
3115 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3116 addrSeenByPeer = addrMe;
3118 // Be shy and don't send version until we hear
3119 if (pfrom->fInbound)
3120 pfrom->PushVersion();
3122 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3124 AddTimeData(pfrom->addr, nTime);
3127 pfrom->PushMessage("verack");
3128 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3130 if (!pfrom->fInbound)
3132 // Advertise our address
3133 if (!fNoListen && !IsInitialBlockDownload())
3135 CAddress addr = GetLocalAddress(&pfrom->addr);
3136 if (addr.IsRoutable())
3137 pfrom->PushAddress(addr);
3140 // Get recent addresses
3141 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3143 pfrom->PushMessage("getaddr");
3144 pfrom->fGetAddr = true;
3146 addrman.Good(pfrom->addr);
3148 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3150 addrman.Add(addrFrom, addrFrom);
3151 addrman.Good(addrFrom);
3155 // Ask the first connected node for block updates
3156 static int nAskedForBlocks = 0;
3157 if (!pfrom->fClient && !pfrom->fOneShot &&
3158 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3159 (pfrom->nVersion < NOBLKS_VERSION_START ||
3160 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3161 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3164 pfrom->PushGetBlocks(pindexBest, uint256(0));
3170 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3171 item.second.RelayTo(pfrom);
3174 // ppcoin: relay sync-checkpoint
3176 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3177 if (!Checkpoints::checkpointMessage.IsNull())
3178 Checkpoints::checkpointMessage.RelayTo(pfrom);
3181 pfrom->fSuccessfullyConnected = true;
3183 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());
3185 cPeerBlockCounts.input(pfrom->nStartingHeight);
3187 // ppcoin: ask for pending sync-checkpoint if any
3188 if (!IsInitialBlockDownload())
3189 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3193 else if (pfrom->nVersion == 0)
3195 // Must have a version message before anything else
3196 pfrom->Misbehaving(1);
3201 else if (strCommand == "verack")
3203 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3207 else if (strCommand == "addr")
3209 vector<CAddress> vAddr;
3212 // Don't want addr from older versions unless seeding
3213 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3215 if (vAddr.size() > 1000)
3217 pfrom->Misbehaving(20);
3218 return error("message addr size() = %"PRIszu"", vAddr.size());
3221 // Store the new addresses
3222 vector<CAddress> vAddrOk;
3223 int64 nNow = GetAdjustedTime();
3224 int64 nSince = nNow - 10 * 60;
3225 BOOST_FOREACH(CAddress& addr, vAddr)
3229 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3230 addr.nTime = nNow - 5 * 24 * 60 * 60;
3231 pfrom->AddAddressKnown(addr);
3232 bool fReachable = IsReachable(addr);
3233 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3235 // Relay to a limited number of other nodes
3238 // Use deterministic randomness to send to the same nodes for 24 hours
3239 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3240 static uint256 hashSalt;
3242 hashSalt = GetRandHash();
3243 uint64 hashAddr = addr.GetHash();
3244 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3245 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3246 multimap<uint256, CNode*> mapMix;
3247 BOOST_FOREACH(CNode* pnode, vNodes)
3249 if (pnode->nVersion < CADDR_TIME_VERSION)
3251 unsigned int nPointer;
3252 memcpy(&nPointer, &pnode, sizeof(nPointer));
3253 uint256 hashKey = hashRand ^ nPointer;
3254 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3255 mapMix.insert(make_pair(hashKey, pnode));
3257 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3258 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3259 ((*mi).second)->PushAddress(addr);
3262 // Do not store addresses outside our network
3264 vAddrOk.push_back(addr);
3266 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3267 if (vAddr.size() < 1000)
3268 pfrom->fGetAddr = false;
3269 if (pfrom->fOneShot)
3270 pfrom->fDisconnect = true;
3274 else if (strCommand == "inv")
3278 if (vInv.size() > MAX_INV_SZ)
3280 pfrom->Misbehaving(20);
3281 return error("message inv size() = %"PRIszu"", vInv.size());
3284 // find last block in inv vector
3285 unsigned int nLastBlock = (unsigned int)(-1);
3286 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3287 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3288 nLastBlock = vInv.size() - 1 - nInv;
3293 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3295 const CInv &inv = vInv[nInv];
3299 pfrom->AddInventoryKnown(inv);
3301 bool fAlreadyHave = AlreadyHave(txdb, inv);
3303 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3307 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3308 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3309 } else if (nInv == nLastBlock) {
3310 // In case we are on a very long side-chain, it is possible that we already have
3311 // the last block in an inv bundle sent in response to getblocks. Try to detect
3312 // this situation and push another getblocks to continue.
3313 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3315 printf("force request: %s\n", inv.ToString().c_str());
3318 // Track requests for our stuff
3319 Inventory(inv.hash);
3324 else if (strCommand == "getdata")
3328 if (vInv.size() > MAX_INV_SZ)
3330 pfrom->Misbehaving(20);
3331 return error("message getdata size() = %"PRIszu"", vInv.size());
3334 if (fDebugNet || (vInv.size() != 1))
3335 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3337 BOOST_FOREACH(const CInv& inv, vInv)
3341 if (fDebugNet || (vInv.size() == 1))
3342 printf("received getdata for: %s\n", inv.ToString().c_str());
3344 if (inv.type == MSG_BLOCK)
3346 // Send block from disk
3347 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3348 if (mi != mapBlockIndex.end())
3351 block.ReadFromDisk((*mi).second);
3352 pfrom->PushMessage("block", block);
3354 // Trigger them to send a getblocks request for the next batch of inventory
3355 if (inv.hash == pfrom->hashContinue)
3357 // ppcoin: send latest proof-of-work block to allow the
3358 // download node to accept as orphan (proof-of-stake
3359 // block might be rejected by stake connection check)
3361 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3362 pfrom->PushMessage("inv", vInv);
3363 pfrom->hashContinue = 0;
3367 else if (inv.IsKnownType())
3369 // Send stream from relay memory
3370 bool pushed = false;
3373 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3374 if (mi != mapRelay.end()) {
3375 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3379 if (!pushed && inv.type == MSG_TX) {
3381 if (mempool.exists(inv.hash)) {
3382 CTransaction tx = mempool.lookup(inv.hash);
3383 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3386 pfrom->PushMessage("tx", ss);
3391 // Track requests for our stuff
3392 Inventory(inv.hash);
3397 else if (strCommand == "getblocks")
3399 CBlockLocator locator;
3401 vRecv >> locator >> hashStop;
3403 // Find the last block the caller has in the main chain
3404 CBlockIndex* pindex = locator.GetBlockIndex();
3406 // Send the rest of the chain
3408 pindex = pindex->pnext;
3410 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3411 for (; pindex; pindex = pindex->pnext)
3413 if (pindex->GetBlockHash() == hashStop)
3415 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3416 // ppcoin: tell downloading node about the latest block if it's
3417 // without risk being rejected due to stake connection check
3418 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3419 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3422 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3425 // When this block is requested, we'll send an inv that'll make them
3426 // getblocks the next batch of inventory.
3427 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3428 pfrom->hashContinue = pindex->GetBlockHash();
3433 else if (strCommand == "checkpoint")
3435 CSyncCheckpoint checkpoint;
3436 vRecv >> checkpoint;
3438 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3441 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3443 BOOST_FOREACH(CNode* pnode, vNodes)
3444 checkpoint.RelayTo(pnode);
3448 else if (strCommand == "getheaders")
3450 CBlockLocator locator;
3452 vRecv >> locator >> hashStop;
3454 CBlockIndex* pindex = NULL;
3455 if (locator.IsNull())
3457 // If locator is null, return the hashStop block
3458 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3459 if (mi == mapBlockIndex.end())
3461 pindex = (*mi).second;
3465 // Find the last block the caller has in the main chain
3466 pindex = locator.GetBlockIndex();
3468 pindex = pindex->pnext;
3471 vector<CBlock> vHeaders;
3473 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3474 for (; pindex; pindex = pindex->pnext)
3476 vHeaders.push_back(pindex->GetBlockHeader());
3477 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3480 pfrom->PushMessage("headers", vHeaders);
3484 else if (strCommand == "tx")
3486 vector<uint256> vWorkQueue;
3487 vector<uint256> vEraseQueue;
3488 CDataStream vMsg(vRecv);
3493 CInv inv(MSG_TX, tx.GetHash());
3494 pfrom->AddInventoryKnown(inv);
3496 // Truncate messages to the size of the tx in them
3497 unsigned int nSize = ::GetSerializeSize(tx,SER_NETWORK, PROTOCOL_VERSION);
3498 if (nSize < vMsg.size()){
3502 bool fMissingInputs = false;
3503 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3505 SyncWithWallets(tx, NULL, true);
3506 RelayMessage(inv, vMsg);
3507 mapAlreadyAskedFor.erase(inv);
3508 vWorkQueue.push_back(inv.hash);
3509 vEraseQueue.push_back(inv.hash);
3511 // Recursively process any orphan transactions that depended on this one
3512 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3514 uint256 hashPrev = vWorkQueue[i];
3515 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3516 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3519 const CDataStream& vMsg = *((*mi).second);
3521 CDataStream(vMsg) >> tx;
3522 CInv inv(MSG_TX, tx.GetHash());
3523 bool fMissingInputs2 = false;
3525 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3527 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3528 SyncWithWallets(tx, NULL, true);
3529 RelayMessage(inv, vMsg);
3530 mapAlreadyAskedFor.erase(inv);
3531 vWorkQueue.push_back(inv.hash);
3532 vEraseQueue.push_back(inv.hash);
3534 else if (!fMissingInputs2)
3537 vEraseQueue.push_back(inv.hash);
3538 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3543 BOOST_FOREACH(uint256 hash, vEraseQueue)
3544 EraseOrphanTx(hash);
3546 else if (fMissingInputs)
3550 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3551 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3553 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3555 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3559 else if (strCommand == "block")
3564 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3567 CInv inv(MSG_BLOCK, block.GetHash());
3568 pfrom->AddInventoryKnown(inv);
3570 if (ProcessBlock(pfrom, &block))
3571 mapAlreadyAskedFor.erase(inv);
3572 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3576 else if (strCommand == "getaddr")
3578 pfrom->vAddrToSend.clear();
3579 vector<CAddress> vAddr = addrman.GetAddr();
3580 BOOST_FOREACH(const CAddress &addr, vAddr)
3581 pfrom->PushAddress(addr);
3585 else if (strCommand == "mempool")
3587 std::vector<uint256> vtxid;
3588 mempool.queryHashes(vtxid);
3590 for (unsigned int i = 0; i < vtxid.size(); i++) {
3591 CInv inv(MSG_TX, vtxid[i]);
3592 vInv.push_back(inv);
3593 if (i == (MAX_INV_SZ - 1))
3596 if (vInv.size() > 0)
3597 pfrom->PushMessage("inv", vInv);
3601 else if (strCommand == "checkorder")
3606 if (!GetBoolArg("-allowreceivebyip"))
3608 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3615 /// we have a chance to check the order here
3617 // Keep giving the same key to the same ip until they use it
3618 if (!mapReuseKey.count(pfrom->addr))
3619 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3621 // Send back approval of order and pubkey to use
3622 CScript scriptPubKey;
3623 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3624 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3628 else if (strCommand == "reply")
3633 CRequestTracker tracker;
3635 LOCK(pfrom->cs_mapRequests);
3636 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3637 if (mi != pfrom->mapRequests.end())
3639 tracker = (*mi).second;
3640 pfrom->mapRequests.erase(mi);
3643 if (!tracker.IsNull())
3644 tracker.fn(tracker.param1, vRecv);
3648 else if (strCommand == "ping")
3650 if (pfrom->nVersion > BIP0031_VERSION)
3654 // Echo the message back with the nonce. This allows for two useful features:
3656 // 1) A remote node can quickly check if the connection is operational
3657 // 2) Remote nodes can measure the latency of the network thread. If this node
3658 // is overloaded it won't respond to pings quickly and the remote node can
3659 // avoid sending us more work, like chain download requests.
3661 // The nonce stops the remote getting confused between different pings: without
3662 // it, if the remote node sends a ping once per second and this node takes 5
3663 // seconds to respond to each, the 5th ping the remote sends would appear to
3664 // return very quickly.
3665 pfrom->PushMessage("pong", nonce);
3670 else if (strCommand == "alert")
3675 uint256 alertHash = alert.GetHash();
3676 if (pfrom->setKnown.count(alertHash) == 0)
3678 if (alert.ProcessAlert())
3681 pfrom->setKnown.insert(alertHash);
3684 BOOST_FOREACH(CNode* pnode, vNodes)
3685 alert.RelayTo(pnode);
3689 // Small DoS penalty so peers that send us lots of
3690 // duplicate/expired/invalid-signature/whatever alerts
3691 // eventually get banned.
3692 // This isn't a Misbehaving(100) (immediate ban) because the
3693 // peer might be an older or different implementation with
3694 // a different signature key, etc.
3695 pfrom->Misbehaving(10);
3703 // Ignore unknown commands for extensibility
3707 // Update the last seen time for this node's address
3708 if (pfrom->fNetworkNode)
3709 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3710 AddressCurrentlyConnected(pfrom->addr);
3716 bool ProcessMessages(CNode* pfrom)
3718 CDataStream& vRecv = pfrom->vRecv;
3722 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3726 // (4) message start
3735 // Don't bother if send buffer is too full to respond anyway
3736 if (pfrom->vSend.size() >= SendBufferSize())
3739 // Scan for message start
3740 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3741 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3742 if (vRecv.end() - pstart < nHeaderSize)
3744 if ((int)vRecv.size() > nHeaderSize)
3746 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3747 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3751 if (pstart - vRecv.begin() > 0)
3752 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3753 vRecv.erase(vRecv.begin(), pstart);
3756 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3761 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3764 string strCommand = hdr.GetCommand();
3767 unsigned int nMessageSize = hdr.nMessageSize;
3768 if (nMessageSize > MAX_SIZE)
3770 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3773 if (nMessageSize > vRecv.size())
3775 // Rewind and wait for rest of message
3776 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3781 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3782 unsigned int nChecksum = 0;
3783 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3784 if (nChecksum != hdr.nChecksum)
3786 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3787 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3791 // Copy message to its own buffer
3792 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3793 vRecv.ignore(nMessageSize);
3801 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3806 catch (std::ios_base::failure& e)
3808 if (strstr(e.what(), "end of data"))
3810 // Allow exceptions from under-length message on vRecv
3811 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());
3813 else if (strstr(e.what(), "size too large"))
3815 // Allow exceptions from over-long size
3816 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3820 PrintExceptionContinue(&e, "ProcessMessages()");
3823 catch (std::exception& e) {
3824 PrintExceptionContinue(&e, "ProcessMessages()");
3826 PrintExceptionContinue(NULL, "ProcessMessages()");
3830 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3838 bool SendMessages(CNode* pto, bool fSendTrickle)
3840 TRY_LOCK(cs_main, lockMain);
3842 // Don't send anything until we get their version message
3843 if (pto->nVersion == 0)
3846 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3848 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3850 if (pto->nVersion > BIP0031_VERSION)
3851 pto->PushMessage("ping", nonce);
3853 pto->PushMessage("ping");
3856 // Resend wallet transactions that haven't gotten in a block yet
3857 ResendWalletTransactions();
3859 // Address refresh broadcast
3860 static int64 nLastRebroadcast;
3861 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3865 BOOST_FOREACH(CNode* pnode, vNodes)
3867 // Periodically clear setAddrKnown to allow refresh broadcasts
3868 if (nLastRebroadcast)
3869 pnode->setAddrKnown.clear();
3871 // Rebroadcast our address
3874 CAddress addr = GetLocalAddress(&pnode->addr);
3875 if (addr.IsRoutable())
3876 pnode->PushAddress(addr);
3880 nLastRebroadcast = GetTime();
3888 vector<CAddress> vAddr;
3889 vAddr.reserve(pto->vAddrToSend.size());
3890 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3892 // returns true if wasn't already contained in the set
3893 if (pto->setAddrKnown.insert(addr).second)
3895 vAddr.push_back(addr);
3896 // receiver rejects addr messages larger than 1000
3897 if (vAddr.size() >= 1000)
3899 pto->PushMessage("addr", vAddr);
3904 pto->vAddrToSend.clear();
3906 pto->PushMessage("addr", vAddr);
3911 // Message: inventory
3914 vector<CInv> vInvWait;
3916 LOCK(pto->cs_inventory);
3917 vInv.reserve(pto->vInventoryToSend.size());
3918 vInvWait.reserve(pto->vInventoryToSend.size());
3919 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3921 if (pto->setInventoryKnown.count(inv))
3924 // trickle out tx inv to protect privacy
3925 if (inv.type == MSG_TX && !fSendTrickle)
3927 // 1/4 of tx invs blast to all immediately
3928 static uint256 hashSalt;
3930 hashSalt = GetRandHash();
3931 uint256 hashRand = inv.hash ^ hashSalt;
3932 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3933 bool fTrickleWait = ((hashRand & 3) != 0);
3935 // always trickle our own transactions
3939 if (GetTransaction(inv.hash, wtx))
3941 fTrickleWait = true;
3946 vInvWait.push_back(inv);
3951 // returns true if wasn't already contained in the set
3952 if (pto->setInventoryKnown.insert(inv).second)
3954 vInv.push_back(inv);
3955 if (vInv.size() >= 1000)
3957 pto->PushMessage("inv", vInv);
3962 pto->vInventoryToSend = vInvWait;
3965 pto->PushMessage("inv", vInv);
3971 vector<CInv> vGetData;
3972 int64 nNow = GetTime() * 1000000;
3974 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3976 const CInv& inv = (*pto->mapAskFor.begin()).second;
3977 if (!AlreadyHave(txdb, inv))
3980 printf("sending getdata: %s\n", inv.ToString().c_str());
3981 vGetData.push_back(inv);
3982 if (vGetData.size() >= 1000)
3984 pto->PushMessage("getdata", vGetData);
3987 mapAlreadyAskedFor[inv] = nNow;
3989 pto->mapAskFor.erase(pto->mapAskFor.begin());
3991 if (!vGetData.empty())
3992 pto->PushMessage("getdata", vGetData);
4011 //////////////////////////////////////////////////////////////////////////////
4016 int static FormatHashBlocks(void* pbuffer, unsigned int len)
4018 unsigned char* pdata = (unsigned char*)pbuffer;
4019 unsigned int blocks = 1 + ((len + 8) / 64);
4020 unsigned char* pend = pdata + 64 * blocks;
4021 memset(pdata + len, 0, 64 * blocks - len);
4023 unsigned int bits = len * 8;
4024 pend[-1] = (bits >> 0) & 0xff;
4025 pend[-2] = (bits >> 8) & 0xff;
4026 pend[-3] = (bits >> 16) & 0xff;
4027 pend[-4] = (bits >> 24) & 0xff;
4031 static const unsigned int pSHA256InitState[8] =
4032 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
4034 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
4037 unsigned char data[64];
4041 for (int i = 0; i < 16; i++)
4042 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
4044 for (int i = 0; i < 8; i++)
4045 ctx.h[i] = ((uint32_t*)pinit)[i];
4047 SHA256_Update(&ctx, data, sizeof(data));
4048 for (int i = 0; i < 8; i++)
4049 ((uint32_t*)pstate)[i] = ctx.h[i];
4052 // Some explaining would be appreciated
4057 set<uint256> setDependsOn;
4061 COrphan(CTransaction* ptxIn)
4064 dPriority = dFeePerKb = 0;
4069 printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
4070 ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
4071 BOOST_FOREACH(uint256 hash, setDependsOn)
4072 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
4077 uint64 nLastBlockTx = 0;
4078 uint64 nLastBlockSize = 0;
4079 int64 nLastCoinStakeSearchInterval = 0;
4081 // We want to sort transactions by priority and fee, so:
4082 typedef boost::tuple<double, double, CTransaction*> TxPriority;
4083 class TxPriorityCompare
4087 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
4088 bool operator()(const TxPriority& a, const TxPriority& b)
4092 if (a.get<1>() == b.get<1>())
4093 return a.get<0>() < b.get<0>();
4094 return a.get<1>() < b.get<1>();
4098 if (a.get<0>() == b.get<0>())
4099 return a.get<1>() < b.get<1>();
4100 return a.get<0>() < b.get<0>();
4106 // fProofOfStake: try (best effort) to make a proof-of-stake block
4107 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
4109 CReserveKey reservekey(pwallet);
4112 auto_ptr<CBlock> pblock(new CBlock());
4116 // Create coinbase tx
4118 txNew.vin.resize(1);
4119 txNew.vin[0].prevout.SetNull();
4120 txNew.vout.resize(1);
4121 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
4123 // Add our coinbase tx as first transaction
4124 pblock->vtx.push_back(txNew);
4126 // Largest block you're willing to create:
4127 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
4128 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
4129 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
4131 // Special compatibility rule before 20 Aug: limit size to 500,000 bytes:
4132 if (GetAdjustedTime() < LOCKS_SWITCH_TIME)
4133 nBlockMaxSize = std::min(nBlockMaxSize, (unsigned int)(MAX_BLOCK_SIZE_GEN));
4135 // How much of the block should be dedicated to high-priority transactions,
4136 // included regardless of the fees they pay
4137 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
4138 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
4140 // Minimum block size you want to create; block will be filled with free transactions
4141 // until there are no more or the block reaches this size:
4142 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
4143 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
4145 // Fee-per-kilobyte amount considered the same as "free"
4146 // Be careful setting this: if you set it to zero then
4147 // a transaction spammer can cheaply fill blocks using
4148 // 1-satoshi-fee transactions. It should be set above the real
4149 // cost to you of processing a transaction.
4150 int64 nMinTxFee = MIN_TX_FEE;
4151 if (mapArgs.count("-mintxfee"))
4152 ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
4154 // ppcoin: if coinstake available add coinstake tx
4155 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
4156 CBlockIndex* pindexPrev = pindexBest;
4158 if (fProofOfStake) // attempt to find a coinstake
4160 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
4161 CTransaction txCoinStake;
4162 int64 nSearchTime = txCoinStake.nTime; // search to current time
4163 if (nSearchTime > nLastCoinStakeSearchTime)
4165 if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
4167 if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
4168 { // make sure coinstake would meet timestamp protocol
4169 // as it would be the same as the block timestamp
4170 pblock->vtx[0].vout[0].SetEmpty();
4171 pblock->vtx[0].nTime = txCoinStake.nTime;
4172 pblock->vtx.push_back(txCoinStake);
4175 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
4176 nLastCoinStakeSearchTime = nSearchTime;
4180 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
4182 // Collect memory pool transactions into the block
4185 LOCK2(cs_main, mempool.cs);
4186 CBlockIndex* pindexPrev = pindexBest;
4189 // Priority order to process transactions
4190 list<COrphan> vOrphan; // list memory doesn't move
4191 map<uint256, vector<COrphan*> > mapDependers;
4193 // This vector will be sorted into a priority queue:
4194 vector<TxPriority> vecPriority;
4195 vecPriority.reserve(mempool.mapTx.size());
4196 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
4198 CTransaction& tx = (*mi).second;
4199 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
4202 COrphan* porphan = NULL;
4203 double dPriority = 0;
4205 bool fMissingInputs = false;
4206 BOOST_FOREACH(const CTxIn& txin, tx.vin)
4208 // Read prev transaction
4209 CTransaction txPrev;
4211 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
4213 // This should never happen; all transactions in the memory
4214 // pool should connect to either transactions in the chain
4215 // or other transactions in the memory pool.
4216 if (!mempool.mapTx.count(txin.prevout.hash))
4218 printf("ERROR: mempool transaction missing input\n");
4219 if (fDebug) assert("mempool transaction missing input" == 0);
4220 fMissingInputs = true;
4226 // Has to wait for dependencies
4229 // Use list for automatic deletion
4230 vOrphan.push_back(COrphan(&tx));
4231 porphan = &vOrphan.back();
4233 mapDependers[txin.prevout.hash].push_back(porphan);
4234 porphan->setDependsOn.insert(txin.prevout.hash);
4235 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
4238 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
4239 nTotalIn += nValueIn;
4241 int nConf = txindex.GetDepthInMainChain();
4242 dPriority += (double)nValueIn * nConf;
4244 if (fMissingInputs) continue;
4246 // Priority is sum(valuein * age) / txsize
4247 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4248 dPriority /= nTxSize;
4250 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
4251 // client code rounds up the size to the nearest 1K. That's good, because it gives an
4252 // incentive to create smaller transactions.
4253 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
4257 porphan->dPriority = dPriority;
4258 porphan->dFeePerKb = dFeePerKb;
4261 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
4264 // Collect transactions into block
4265 map<uint256, CTxIndex> mapTestPool;
4266 uint64 nBlockSize = 1000;
4267 uint64 nBlockTx = 0;
4268 int nBlockSigOps = 100;
4269 bool fSortedByFee = (nBlockPrioritySize <= 0);
4271 TxPriorityCompare comparer(fSortedByFee);
4272 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4274 while (!vecPriority.empty())
4276 // Take highest priority transaction off the priority queue:
4277 double dPriority = vecPriority.front().get<0>();
4278 double dFeePerKb = vecPriority.front().get<1>();
4279 CTransaction& tx = *(vecPriority.front().get<2>());
4281 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
4282 vecPriority.pop_back();
4285 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4286 if (nBlockSize + nTxSize >= nBlockMaxSize)
4289 // Legacy limits on sigOps:
4290 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
4291 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4295 if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
4298 // ppcoin: simplify transaction fee - allow free = false
4299 int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
4301 // Skip free transactions if we're past the minimum block size:
4302 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
4305 // Prioritize by fee once past the priority size or we run out of high-priority
4307 if (!fSortedByFee &&
4308 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
4310 fSortedByFee = true;
4311 comparer = TxPriorityCompare(fSortedByFee);
4312 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4315 // Connecting shouldn't fail due to dependency on other memory pool transactions
4316 // because we're already processing them in order of dependency
4317 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
4318 MapPrevTx mapInputs;
4320 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
4323 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
4324 if (nTxFees < nMinFee)
4327 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
4328 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4331 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
4333 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
4334 swap(mapTestPool, mapTestPoolTmp);
4337 pblock->vtx.push_back(tx);
4338 nBlockSize += nTxSize;
4340 nBlockSigOps += nTxSigOps;
4343 if (fDebug && GetBoolArg("-printpriority"))
4345 printf("priority %.1f feeperkb %.1f txid %s\n",
4346 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
4349 // Add transactions that depend on this one to the priority queue
4350 uint256 hash = tx.GetHash();
4351 if (mapDependers.count(hash))
4353 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
4355 if (!porphan->setDependsOn.empty())
4357 porphan->setDependsOn.erase(hash);
4358 if (porphan->setDependsOn.empty())
4360 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
4361 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
4368 nLastBlockTx = nBlockTx;
4369 nLastBlockSize = nBlockSize;
4371 if (fDebug && GetBoolArg("-printpriority"))
4372 printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
4374 if (pblock->IsProofOfWork())
4375 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
4378 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
4379 if (pblock->IsProofOfStake())
4380 pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
4381 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
4382 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4383 if (pblock->IsProofOfWork())
4384 pblock->UpdateTime(pindexPrev);
4388 return pblock.release();
4392 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
4394 // Update nExtraNonce
4395 static uint256 hashPrevBlock;
4396 if (hashPrevBlock != pblock->hashPrevBlock)
4399 hashPrevBlock = pblock->hashPrevBlock;
4402 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4403 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4404 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
4406 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
4410 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
4413 // Pre-build hash buffers
4420 uint256 hashPrevBlock;
4421 uint256 hashMerkleRoot;
4424 unsigned int nNonce;
4427 unsigned char pchPadding0[64];
4429 unsigned char pchPadding1[64];
4432 memset(&tmp, 0, sizeof(tmp));
4434 tmp.block.nVersion = pblock->nVersion;
4435 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
4436 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
4437 tmp.block.nTime = pblock->nTime;
4438 tmp.block.nBits = pblock->nBits;
4439 tmp.block.nNonce = pblock->nNonce;
4441 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
4442 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
4444 // Byte swap all the input buffer
4445 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
4446 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
4448 // Precalc the first half of the first hash, which stays constant
4449 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
4451 memcpy(pdata, &tmp.block, 128);
4452 memcpy(phash1, &tmp.hash1, 64);
4456 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
4458 uint256 hash = pblock->GetHash();
4459 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4461 if (hash > hashTarget && pblock->IsProofOfWork())
4462 return error("BitcoinMiner : proof-of-work not meeting target");
4465 printf("BitcoinMiner:\n");
4466 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
4468 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
4473 if (pblock->hashPrevBlock != hashBestChain)
4474 return error("BitcoinMiner : generated block is stale");
4476 // Remove key from key pool
4477 reservekey.KeepKey();
4479 // Track how many getdata requests this block gets
4481 LOCK(wallet.cs_wallet);
4482 wallet.mapRequestCount[pblock->GetHash()] = 0;
4485 // Process this block the same as if we had received it from another node
4486 if (!ProcessBlock(NULL, pblock))
4487 return error("BitcoinMiner : ProcessBlock, block not accepted");
4493 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake)
4495 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4497 // Make this thread recognisable as the mining thread
4498 RenameThread("bitcoin-miner");
4500 // Each thread has its own key and counter
4501 CReserveKey reservekey(pwallet);
4502 unsigned int nExtraNonce = 0;
4504 while (fProofOfStake)
4508 while (vNodes.empty() || IsInitialBlockDownload())
4517 while (pwallet->IsLocked())
4519 strMintWarning = strMintMessage;
4522 strMintWarning = "";
4527 CBlockIndex* pindexPrev = pindexBest;
4529 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
4532 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
4536 // ppcoin: if proof-of-stake block found then process block
4537 if (pblock->IsProofOfStake())
4539 if (!pblock->SignBlock(*pwalletMain))
4541 strMintWarning = strMintMessage;
4544 strMintWarning = "";
4545 printf("StakeMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
4546 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4547 CheckWork(pblock.get(), *pwalletMain, reservekey);
4548 SetThreadPriority(THREAD_PRIORITY_LOWEST);