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
41 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
43 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as minimum age for coin age
44 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as stake age of full weight
45 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
46 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
48 int nCoinbaseMaturity = 500;
49 CBlockIndex* pindexGenesisBlock = NULL;
51 CBigNum bnBestChainTrust = 0;
52 CBigNum bnBestInvalidTrust = 0;
53 uint256 hashBestChain = 0;
54 CBlockIndex* pindexBest = NULL;
55 int64 nTimeBestReceived = 0;
57 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
59 map<uint256, CBlock*> mapOrphanBlocks;
60 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
61 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
62 map<uint256, uint256> mapProofOfStake;
64 map<uint256, CDataStream*> mapOrphanTransactions;
65 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
67 // Constant stuff for coinbase transactions we create:
68 CScript COINBASE_FLAGS;
70 const string strMessageMagic = "NovaCoin Signed Message:\n";
76 int64 nTransactionFee = MIN_TX_FEE;
79 //////////////////////////////////////////////////////////////////////////////
81 // dispatching functions
84 // These functions dispatch to one or all registered wallets
87 void RegisterWallet(CWallet* pwalletIn)
90 LOCK(cs_setpwalletRegistered);
91 setpwalletRegistered.insert(pwalletIn);
95 void UnregisterWallet(CWallet* pwalletIn)
98 LOCK(cs_setpwalletRegistered);
99 setpwalletRegistered.erase(pwalletIn);
103 // check whether the passed transaction is from us
104 bool static IsFromMe(CTransaction& tx)
106 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
107 if (pwallet->IsFromMe(tx))
112 // get the wallet transaction with the given hash (if it exists)
113 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
115 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
116 if (pwallet->GetTransaction(hashTx,wtx))
121 // erases transaction with the given hash from all wallets
122 void static EraseFromWallets(uint256 hash)
124 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
125 pwallet->EraseFromWallet(hash);
128 // make sure all wallets know about the given transaction, in the given block
129 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
133 // ppcoin: wallets need to refund inputs when disconnecting coinstake
134 if (tx.IsCoinStake())
136 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
137 if (pwallet->IsFromMe(tx))
138 pwallet->DisableTransaction(tx);
143 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
144 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
147 // notify wallets about a new best chain
148 void static SetBestChain(const CBlockLocator& loc)
150 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
151 pwallet->SetBestChain(loc);
154 // notify wallets about an updated transaction
155 void static UpdatedTransaction(const uint256& hashTx)
157 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
158 pwallet->UpdatedTransaction(hashTx);
162 void static PrintWallets(const CBlock& block)
164 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
165 pwallet->PrintWallet(block);
168 // notify wallets about an incoming inventory (for request counts)
169 void static Inventory(const uint256& hash)
171 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
172 pwallet->Inventory(hash);
175 // ask wallets to resend their transactions
176 void ResendWalletTransactions()
178 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
179 pwallet->ResendWalletTransactions();
188 //////////////////////////////////////////////////////////////////////////////
190 // mapOrphanTransactions
193 bool AddOrphanTx(const CDataStream& vMsg)
196 CDataStream(vMsg) >> tx;
197 uint256 hash = tx.GetHash();
198 if (mapOrphanTransactions.count(hash))
201 CDataStream* pvMsg = new CDataStream(vMsg);
203 // Ignore big transactions, to avoid a
204 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
205 // large transaction with a missing parent then we assume
206 // it will rebroadcast it later, after the parent transaction(s)
207 // have been mined or received.
208 // 10,000 orphans, each of which is at most 5,000 bytes big is
209 // at most 500 megabytes of orphans:
210 if (pvMsg->size() > 5000)
212 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
217 mapOrphanTransactions[hash] = pvMsg;
218 BOOST_FOREACH(const CTxIn& txin, tx.vin)
219 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
221 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
222 mapOrphanTransactions.size());
226 void static EraseOrphanTx(uint256 hash)
228 if (!mapOrphanTransactions.count(hash))
230 const CDataStream* pvMsg = mapOrphanTransactions[hash];
232 CDataStream(*pvMsg) >> tx;
233 BOOST_FOREACH(const CTxIn& txin, tx.vin)
235 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
236 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
237 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
240 mapOrphanTransactions.erase(hash);
243 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
245 unsigned int nEvicted = 0;
246 while (mapOrphanTransactions.size() > nMaxOrphans)
248 // Evict a random orphan:
249 uint256 randomhash = GetRandHash();
250 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
251 if (it == mapOrphanTransactions.end())
252 it = mapOrphanTransactions.begin();
253 EraseOrphanTx(it->first);
265 //////////////////////////////////////////////////////////////////////////////
267 // CTransaction and CTxIndex
270 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
273 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
275 if (!ReadFromDisk(txindexRet.pos))
277 if (prevout.n >= vout.size())
285 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
288 return ReadFromDisk(txdb, prevout, txindex);
291 bool CTransaction::ReadFromDisk(COutPoint prevout)
295 return ReadFromDisk(txdb, prevout, txindex);
298 bool CTransaction::IsStandard() const
300 if (nVersion > CTransaction::CURRENT_VERSION)
303 BOOST_FOREACH(const CTxIn& txin, vin)
305 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
306 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
307 // ~65-byte public keys, plus a few script ops.
308 if (txin.scriptSig.size() > 500)
310 if (!txin.scriptSig.IsPushOnly())
313 BOOST_FOREACH(const CTxOut& txout, vout) {
314 if (!::IsStandard(txout.scriptPubKey))
316 if (txout.nValue == 0)
323 // Check transaction inputs, and make sure any
324 // pay-to-script-hash transactions are evaluating IsStandard scripts
326 // Why bother? To avoid denial-of-service attacks; an attacker
327 // can submit a standard HASH... OP_EQUAL transaction,
328 // which will get accepted into blocks. The redemption
329 // script can be anything; an attacker could use a very
330 // expensive-to-check-upon-redemption script like:
331 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
333 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
336 return true; // Coinbases don't use vin normally
338 for (unsigned int i = 0; i < vin.size(); i++)
340 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
342 vector<vector<unsigned char> > vSolutions;
343 txnouttype whichType;
344 // get the scriptPubKey corresponding to this input:
345 const CScript& prevScript = prev.scriptPubKey;
346 if (!Solver(prevScript, whichType, vSolutions))
348 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
349 if (nArgsExpected < 0)
352 // Transactions with extra stuff in their scriptSigs are
353 // non-standard. Note that this EvalScript() call will
354 // be quick, because if there are any operations
355 // beside "push data" in the scriptSig the
356 // IsStandard() call returns false
357 vector<vector<unsigned char> > stack;
358 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
361 if (whichType == TX_SCRIPTHASH)
365 CScript subscript(stack.back().begin(), stack.back().end());
366 vector<vector<unsigned char> > vSolutions2;
367 txnouttype whichType2;
368 if (!Solver(subscript, whichType2, vSolutions2))
370 if (whichType2 == TX_SCRIPTHASH)
374 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
377 nArgsExpected += tmpExpected;
380 if (stack.size() != (unsigned int)nArgsExpected)
388 CTransaction::GetLegacySigOpCount() const
390 unsigned int nSigOps = 0;
391 BOOST_FOREACH(const CTxIn& txin, vin)
393 nSigOps += txin.scriptSig.GetSigOpCount(false);
395 BOOST_FOREACH(const CTxOut& txout, vout)
397 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
403 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
415 // Load the block this tx is in
417 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
419 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
424 // Update the tx's hashBlock
425 hashBlock = pblock->GetHash();
427 // Locate the transaction
428 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
429 if (pblock->vtx[nIndex] == *(CTransaction*)this)
431 if (nIndex == (int)pblock->vtx.size())
433 vMerkleBranch.clear();
435 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
439 // Fill in merkle branch
440 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
443 // Is the tx in a block that's in the main chain
444 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
445 if (mi == mapBlockIndex.end())
447 CBlockIndex* pindex = (*mi).second;
448 if (!pindex || !pindex->IsInMainChain())
451 return pindexBest->nHeight - pindex->nHeight + 1;
460 bool CTransaction::CheckTransaction() const
462 // Basic checks that don't depend on any context
464 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
466 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
468 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
469 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
471 // Check for negative or overflow output values
473 for (unsigned int i = 0; i < vout.size(); i++)
475 const CTxOut& txout = vout[i];
476 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
477 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
479 // ppcoin: enforce minimum output amount
480 if ((!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
481 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
483 if (txout.nValue > MAX_MONEY)
484 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
485 nValueOut += txout.nValue;
486 if (!MoneyRange(nValueOut))
487 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
490 // Check for duplicate inputs
491 set<COutPoint> vInOutPoints;
492 BOOST_FOREACH(const CTxIn& txin, vin)
494 if (vInOutPoints.count(txin.prevout))
496 vInOutPoints.insert(txin.prevout);
501 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
502 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
506 BOOST_FOREACH(const CTxIn& txin, vin)
507 if (txin.prevout.IsNull())
508 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
514 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
515 enum GetMinFee_mode mode) const
517 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
518 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
520 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
521 unsigned int nNewBlockSize = nBlockSize + nBytes;
522 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
524 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
525 if (nMinFee < nBaseFee)
527 BOOST_FOREACH(const CTxOut& txout, vout)
528 if (txout.nValue < CENT)
532 // Raise the price as the block approaches full
533 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
535 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
537 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
540 if (!MoneyRange(nMinFee))
546 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
547 bool* pfMissingInputs)
550 *pfMissingInputs = false;
552 if (!tx.CheckTransaction())
553 return error("CTxMemPool::accept() : CheckTransaction failed");
555 // Coinbase is only valid in a block, not as a loose transaction
557 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
559 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
560 if (tx.IsCoinStake())
561 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
563 // To help v0.1.5 clients who would see it as a negative number
564 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
565 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
567 // Rather not work on nonstandard transactions (unless -testnet)
568 if (!fTestNet && !tx.IsStandard())
569 return error("CTxMemPool::accept() : nonstandard transaction type");
571 // Do we already have it?
572 uint256 hash = tx.GetHash();
575 if (mapTx.count(hash))
579 if (txdb.ContainsTx(hash))
582 // Check for conflicts with in-memory transactions
583 CTransaction* ptxOld = NULL;
584 for (unsigned int i = 0; i < tx.vin.size(); i++)
586 COutPoint outpoint = tx.vin[i].prevout;
587 if (mapNextTx.count(outpoint))
589 // Disable replacement feature for now
592 // Allow replacing with a newer version of the same transaction
595 ptxOld = mapNextTx[outpoint].ptx;
596 if (ptxOld->IsFinal())
598 if (!tx.IsNewerThan(*ptxOld))
600 for (unsigned int i = 0; i < tx.vin.size(); i++)
602 COutPoint outpoint = tx.vin[i].prevout;
603 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
613 map<uint256, CTxIndex> mapUnused;
614 bool fInvalid = false;
615 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
618 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
620 *pfMissingInputs = true;
624 // Check for non-standard pay-to-script-hash in inputs
625 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
626 return error("CTxMemPool::accept() : nonstandard transaction input");
628 // Note: if you modify this code to accept non-standard transactions, then
629 // you should add code here to check that the transaction does a
630 // reasonable number of ECDSA signature verifications.
632 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
633 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
635 // Don't accept it if it can't get into a block
636 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY);
637 if (nFees < txMinFee)
638 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
639 hash.ToString().c_str(),
642 // Continuously rate-limit free transactions
643 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
644 // be annoying or make others' transactions take longer to confirm.
645 if (nFees < MIN_RELAY_TX_FEE)
647 static CCriticalSection cs;
648 static double dFreeCount;
649 static int64 nLastTime;
650 int64 nNow = GetTime();
654 // Use an exponentially decaying ~10-minute window:
655 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
657 // -limitfreerelay unit is thousand-bytes-per-minute
658 // At default rate it would take over a month to fill 1GB
659 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
660 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
662 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
667 // Check against previous transactions
668 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
669 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
671 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
675 // Store transaction in memory
680 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
683 addUnchecked(hash, tx);
686 ///// are we sure this is ok when loading transactions or restoring block txes
687 // If updated, erase old tx from wallet
689 EraseFromWallets(ptxOld->GetHash());
691 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
692 hash.ToString().substr(0,10).c_str(),
697 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
699 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
702 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
704 // Add to memory pool without checking anything. Don't call this directly,
705 // call CTxMemPool::accept to properly check the transaction first.
708 for (unsigned int i = 0; i < tx.vin.size(); i++)
709 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
710 nTransactionsUpdated++;
716 bool CTxMemPool::remove(CTransaction &tx)
718 // Remove transaction from memory pool
721 uint256 hash = tx.GetHash();
722 if (mapTx.count(hash))
724 BOOST_FOREACH(const CTxIn& txin, tx.vin)
725 mapNextTx.erase(txin.prevout);
727 nTransactionsUpdated++;
733 void CTxMemPool::clear()
738 ++nTransactionsUpdated;
741 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
746 vtxid.reserve(mapTx.size());
747 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
748 vtxid.push_back((*mi).first);
754 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
756 if (hashBlock == 0 || nIndex == -1)
759 // Find the block it claims to be in
760 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
761 if (mi == mapBlockIndex.end())
763 CBlockIndex* pindex = (*mi).second;
764 if (!pindex || !pindex->IsInMainChain())
767 // Make sure the merkle branch connects to this block
768 if (!fMerkleVerified)
770 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
772 fMerkleVerified = true;
776 return pindexBest->nHeight - pindex->nHeight + 1;
780 int CMerkleTx::GetBlocksToMaturity() const
782 if (!(IsCoinBase() || IsCoinStake()))
784 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
788 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
792 if (!IsInMainChain() && !ClientConnectInputs())
794 return CTransaction::AcceptToMemoryPool(txdb, false);
798 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
802 bool CMerkleTx::AcceptToMemoryPool()
805 return AcceptToMemoryPool(txdb);
810 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
815 // Add previous supporting transactions first
816 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
818 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
820 uint256 hash = tx.GetHash();
821 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
822 tx.AcceptToMemoryPool(txdb, fCheckInputs);
825 return AcceptToMemoryPool(txdb, fCheckInputs);
830 bool CWalletTx::AcceptWalletTransaction()
833 return AcceptWalletTransaction(txdb);
836 int CTxIndex::GetDepthInMainChain() const
840 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
842 // Find the block in the index
843 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
844 if (mi == mapBlockIndex.end())
846 CBlockIndex* pindex = (*mi).second;
847 if (!pindex || !pindex->IsInMainChain())
849 return 1 + nBestHeight - pindex->nHeight;
852 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
853 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
859 if (mempool.exists(hash))
861 tx = mempool.lookup(hash);
867 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
870 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
871 hashBlock = block.GetHash();
885 //////////////////////////////////////////////////////////////////////////////
887 // CBlock and CBlockIndex
890 static CBlockIndex* pblockindexFBBHLast;
891 CBlockIndex* FindBlockByHeight(int nHeight)
893 CBlockIndex *pblockindex;
894 if (nHeight < nBestHeight / 2)
895 pblockindex = pindexGenesisBlock;
897 pblockindex = pindexBest;
898 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
899 pblockindex = pblockindexFBBHLast;
900 while (pblockindex->nHeight > nHeight)
901 pblockindex = pblockindex->pprev;
902 while (pblockindex->nHeight < nHeight)
903 pblockindex = pblockindex->pnext;
904 pblockindexFBBHLast = pblockindex;
908 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
910 if (!fReadTransactions)
912 *this = pindex->GetBlockHeader();
915 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
917 if (GetHash() != pindex->GetBlockHash())
918 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
922 uint256 static GetOrphanRoot(const CBlock* pblock)
924 // Work back to the first block in the orphan chain
925 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
926 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
927 return pblock->GetHash();
930 // ppcoin: find block wanted by given orphan block
931 uint256 WantedByOrphan(const CBlock* pblockOrphan)
933 // Work back to the first block in the orphan chain
934 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
935 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
936 return pblockOrphan->hashPrevBlock;
939 // select stake target limit according to hard-coded conditions
940 CBigNum static GetProofOfStakeLimit(int nHeight, unsigned int nTime)
942 if(fTestNet) // separate proof of stake target limit for testnet
943 return bnProofOfStakeLimit;
944 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
945 return bnProofOfStakeLimit;
946 if(nHeight + 1 > 15000) // 24 bits since block 15000
947 return bnProofOfStakeLegacyLimit;
948 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
949 return bnProofOfStakeHardLimit;
951 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
954 // miner's coin base reward based on nBits
955 int64 GetProofOfWorkReward(unsigned int nBits)
957 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
960 bnTarget.SetCompact(nBits);
961 CBigNum bnTargetLimit = bnProofOfWorkLimit;
962 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
964 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
965 // A reasonably continuous curve is used to avoid shock to market
966 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
968 // Human readable form:
970 // nSubsidy = 100 / (diff ^ 1/6)
971 CBigNum bnLowerBound = CENT;
972 CBigNum bnUpperBound = bnSubsidyLimit;
973 while (bnLowerBound + CENT <= bnUpperBound)
975 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
976 if (fDebug && GetBoolArg("-printcreation"))
977 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
978 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
979 bnUpperBound = bnMidValue;
981 bnLowerBound = bnMidValue;
984 int64 nSubsidy = bnUpperBound.getuint64();
985 nSubsidy = (nSubsidy / CENT) * CENT;
986 if (fDebug && GetBoolArg("-printcreation"))
987 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
989 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
992 // miner's coin stake reward based on nBits and coin age spent (coin-days)
993 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime)
995 int64 nRewardCoinYear;
997 if(fTestNet || nTime > STAKE_SWITCH_TIME)
999 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1001 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1003 bnTarget.SetCompact(nBits);
1004 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1005 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1007 // NovaCoin: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1008 // A reasonably continuous curve is used to avoid shock to market
1009 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1011 // Human readable form:
1013 // nRewardCoinYear = 1 / (posdiff ^ 1/6)
1015 CBigNum bnLowerBound = 1 * CENT; // Lower interest bound is 1% per year
1016 CBigNum bnUpperBound = bnRewardCoinYearLimit;
1017 while (bnLowerBound + CENT <= bnUpperBound)
1019 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1020 if (fDebug && GetBoolArg("-printcreation"))
1021 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1022 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnTarget)
1023 bnUpperBound = bnMidValue;
1025 bnLowerBound = bnMidValue;
1028 nRewardCoinYear = bnUpperBound.getuint64();
1029 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1033 // Old creation amount per coin-year, 5% fixed stake mint rate
1034 nRewardCoinYear = 5 * CENT;
1037 int64 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
1038 if (fDebug && GetBoolArg("-printcreation"))
1039 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1043 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1045 // get proof of work blocks max spacing according to hard-coded conditions
1046 int64 static GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1048 if(nTime > TARGETS_SWITCH_TIME)
1049 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1052 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1054 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1058 // minimum amount of work that could possibly be required nTime after
1059 // minimum work required was nBase
1061 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1063 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1066 bnResult.SetCompact(nBase);
1068 while (nTime > 0 && bnResult < bnTargetLimit)
1070 // Maximum 200% adjustment per day...
1072 nTime -= 24 * 60 * 60;
1074 if (bnResult > bnTargetLimit)
1075 bnResult = bnTargetLimit;
1076 return bnResult.GetCompact();
1079 // ppcoin: find last block index up to pindex
1080 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1082 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1083 pindex = pindex->pprev;
1087 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1089 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1091 if (pindexLast == NULL)
1092 return bnTargetLimit.GetCompact(); // genesis block
1094 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1095 if (pindexPrev->pprev == NULL)
1096 return bnTargetLimit.GetCompact(); // first block
1097 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1098 if (pindexPrevPrev->pprev == NULL)
1099 return bnTargetLimit.GetCompact(); // second block
1101 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1103 // ppcoin: target change every block
1104 // ppcoin: retarget with exponential moving toward target spacing
1106 bnNew.SetCompact(pindexPrev->nBits);
1107 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1108 int64 nInterval = nTargetTimespan / nTargetSpacing;
1109 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1110 bnNew /= ((nInterval + 1) * nTargetSpacing);
1112 if (bnNew > bnTargetLimit)
1113 bnNew = bnTargetLimit;
1115 return bnNew.GetCompact();
1118 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1121 bnTarget.SetCompact(nBits);
1124 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1125 return error("CheckProofOfWork() : nBits below minimum work");
1127 // Check proof of work matches claimed amount
1128 if (hash > bnTarget.getuint256())
1129 return error("CheckProofOfWork() : hash doesn't match nBits");
1134 // Return maximum amount of blocks that other nodes claim to have
1135 int GetNumBlocksOfPeers()
1137 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1140 bool IsInitialBlockDownload()
1142 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1144 static int64 nLastUpdate;
1145 static CBlockIndex* pindexLastBest;
1146 if (pindexBest != pindexLastBest)
1148 pindexLastBest = pindexBest;
1149 nLastUpdate = GetTime();
1151 return (GetTime() - nLastUpdate < 10 &&
1152 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1155 void static InvalidChainFound(CBlockIndex* pindexNew)
1157 if (pindexNew->bnChainTrust > bnBestInvalidTrust)
1159 bnBestInvalidTrust = pindexNew->bnChainTrust;
1160 CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust);
1161 uiInterface.NotifyBlocksChanged();
1164 printf("InvalidChainFound: invalid block=%s height=%d trust=%s date=%s\n",
1165 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1166 pindexNew->bnChainTrust.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S",
1167 pindexNew->GetBlockTime()).c_str());
1168 printf("InvalidChainFound: current best=%s height=%d trust=%s date=%s\n",
1169 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(),
1170 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1173 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1175 nTime = max(GetBlockTime(), GetAdjustedTime());
1188 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1190 // Relinquish previous transactions' spent pointers
1193 BOOST_FOREACH(const CTxIn& txin, vin)
1195 COutPoint prevout = txin.prevout;
1197 // Get prev txindex from disk
1199 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1200 return error("DisconnectInputs() : ReadTxIndex failed");
1202 if (prevout.n >= txindex.vSpent.size())
1203 return error("DisconnectInputs() : prevout.n out of range");
1205 // Mark outpoint as not spent
1206 txindex.vSpent[prevout.n].SetNull();
1209 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1210 return error("DisconnectInputs() : UpdateTxIndex failed");
1214 // Remove transaction from index
1215 // This can fail if a duplicate of this transaction was in a chain that got
1216 // reorganized away. This is only possible if this transaction was completely
1217 // spent, so erasing it would be a no-op anyway.
1218 txdb.EraseTxIndex(*this);
1224 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1225 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1227 // FetchInputs can return false either because we just haven't seen some inputs
1228 // (in which case the transaction should be stored as an orphan)
1229 // or because the transaction is malformed (in which case the transaction should
1230 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1234 return true; // Coinbase transactions have no inputs to fetch.
1236 for (unsigned int i = 0; i < vin.size(); i++)
1238 COutPoint prevout = vin[i].prevout;
1239 if (inputsRet.count(prevout.hash))
1240 continue; // Got it already
1243 CTxIndex& txindex = inputsRet[prevout.hash].first;
1245 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1247 // Get txindex from current proposed changes
1248 txindex = mapTestPool.find(prevout.hash)->second;
1252 // Read txindex from txdb
1253 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1255 if (!fFound && (fBlock || fMiner))
1256 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());
1259 CTransaction& txPrev = inputsRet[prevout.hash].second;
1260 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1262 // Get prev tx from single transactions in memory
1265 if (!mempool.exists(prevout.hash))
1266 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());
1267 txPrev = mempool.lookup(prevout.hash);
1270 txindex.vSpent.resize(txPrev.vout.size());
1274 // Get prev tx from disk
1275 if (!txPrev.ReadFromDisk(txindex.pos))
1276 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1280 // Make sure all prevout.n indexes are valid:
1281 for (unsigned int i = 0; i < vin.size(); i++)
1283 const COutPoint prevout = vin[i].prevout;
1284 assert(inputsRet.count(prevout.hash) != 0);
1285 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1286 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1287 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1289 // Revisit this if/when transaction replacement is implemented and allows
1292 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()));
1299 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1301 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1302 if (mi == inputs.end())
1303 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1305 const CTransaction& txPrev = (mi->second).second;
1306 if (input.prevout.n >= txPrev.vout.size())
1307 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1309 return txPrev.vout[input.prevout.n];
1312 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1318 for (unsigned int i = 0; i < vin.size(); i++)
1320 nResult += GetOutputFor(vin[i], inputs).nValue;
1326 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1331 unsigned int nSigOps = 0;
1332 for (unsigned int i = 0; i < vin.size(); i++)
1334 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1335 if (prevout.scriptPubKey.IsPayToScriptHash())
1336 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1341 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1342 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1343 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1345 // Take over previous transactions' spent pointers
1346 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1347 // fMiner is true when called from the internal bitcoin miner
1348 // ... both are false when called from CTransaction::AcceptToMemoryPool
1353 for (unsigned int i = 0; i < vin.size(); i++)
1355 COutPoint prevout = vin[i].prevout;
1356 assert(inputs.count(prevout.hash) > 0);
1357 CTxIndex& txindex = inputs[prevout.hash].first;
1358 CTransaction& txPrev = inputs[prevout.hash].second;
1360 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1361 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()));
1363 // If prev is coinbase or coinstake, check that it's matured
1364 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1365 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1366 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1367 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1369 // ppcoin: check transaction timestamp
1370 if (txPrev.nTime > nTime)
1371 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1373 // Check for negative or overflow input values
1374 nValueIn += txPrev.vout[prevout.n].nValue;
1375 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1376 return DoS(100, error("ConnectInputs() : txin values out of range"));
1379 // The first loop above does all the inexpensive checks.
1380 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1381 // Helps prevent CPU exhaustion attacks.
1382 for (unsigned int i = 0; i < vin.size(); i++)
1384 COutPoint prevout = vin[i].prevout;
1385 assert(inputs.count(prevout.hash) > 0);
1386 CTxIndex& txindex = inputs[prevout.hash].first;
1387 CTransaction& txPrev = inputs[prevout.hash].second;
1389 // Check for conflicts (double-spend)
1390 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1391 // for an attacker to attempt to split the network.
1392 if (!txindex.vSpent[prevout.n].IsNull())
1393 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());
1395 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1396 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1397 // still computed and checked, and any change will be caught at the next checkpoint.
1398 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1401 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1403 // only during transition phase for P2SH: do not invoke anti-DoS code for
1404 // potentially old clients relaying bad P2SH transactions
1405 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1406 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1408 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1412 // Mark outpoints as spent
1413 txindex.vSpent[prevout.n] = posThisTx;
1416 if (fBlock || fMiner)
1418 mapTestPool[prevout.hash] = txindex;
1424 // ppcoin: coin stake tx earns reward instead of paying fee
1426 if (!GetCoinAge(txdb, nCoinAge))
1427 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1428 int64 nStakeReward = GetValueOut() - nValueIn;
1429 if (nStakeReward > GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee() + MIN_TX_FEE)
1430 return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
1434 if (nValueIn < GetValueOut())
1435 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1437 // Tally transaction fees
1438 int64 nTxFee = nValueIn - GetValueOut();
1440 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1441 // ppcoin: enforce transaction fees for every block
1442 if (nTxFee < GetMinFee())
1443 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;
1446 if (!MoneyRange(nFees))
1447 return DoS(100, error("ConnectInputs() : nFees out of range"));
1455 bool CTransaction::ClientConnectInputs()
1460 // Take over previous transactions' spent pointers
1464 for (unsigned int i = 0; i < vin.size(); i++)
1466 // Get prev tx from single transactions in memory
1467 COutPoint prevout = vin[i].prevout;
1468 if (!mempool.exists(prevout.hash))
1470 CTransaction& txPrev = mempool.lookup(prevout.hash);
1472 if (prevout.n >= txPrev.vout.size())
1476 if (!VerifySignature(txPrev, *this, i, true, 0))
1477 return error("ConnectInputs() : VerifySignature failed");
1479 ///// this is redundant with the mempool.mapNextTx stuff,
1480 ///// not sure which I want to get rid of
1481 ///// this has to go away now that posNext is gone
1482 // // Check for conflicts
1483 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1484 // return error("ConnectInputs() : prev tx already used");
1486 // // Flag outpoints as used
1487 // txPrev.vout[prevout.n].posNext = posThisTx;
1489 nValueIn += txPrev.vout[prevout.n].nValue;
1491 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1492 return error("ClientConnectInputs() : txin values out of range");
1494 if (GetValueOut() > nValueIn)
1504 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1506 // Disconnect in reverse order
1507 for (int i = vtx.size()-1; i >= 0; i--)
1508 if (!vtx[i].DisconnectInputs(txdb))
1511 // Update block index on disk without changing it in memory.
1512 // The memory index structure will be changed after the db commits.
1515 CDiskBlockIndex blockindexPrev(pindex->pprev);
1516 blockindexPrev.hashNext = 0;
1517 if (!txdb.WriteBlockIndex(blockindexPrev))
1518 return error("DisconnectBlock() : WriteBlockIndex failed");
1521 // ppcoin: clean up wallet after disconnecting coinstake
1522 BOOST_FOREACH(CTransaction& tx, vtx)
1523 SyncWithWallets(tx, this, false, false);
1528 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1530 // Check it again in case a previous version let a bad block in
1531 if (!CheckBlock(!fJustCheck, !fJustCheck))
1534 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1535 // unless those are already completely spent.
1536 // If such overwrites are allowed, coinbases and transactions depending upon those
1537 // can be duplicated to remove the ability to spend the first instance -- even after
1538 // being sent to another address.
1539 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1540 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1541 // already refuses previously-known transaction ids entirely.
1542 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1543 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1544 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1545 // initial block download.
1546 bool fEnforceBIP30 = true; // Always active in NovaCoin
1547 bool fStrictPayToScriptHash = true; // Always active in NovaCoin
1549 //// issue here: it doesn't know the version
1550 unsigned int nTxPos;
1552 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1553 // 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
1556 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1558 map<uint256, CTxIndex> mapQueuedChanges;
1561 int64 nValueOut = 0;
1562 unsigned int nSigOps = 0;
1563 BOOST_FOREACH(CTransaction& tx, vtx)
1565 uint256 hashTx = tx.GetHash();
1567 if (fEnforceBIP30) {
1568 CTxIndex txindexOld;
1569 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1570 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1576 nSigOps += tx.GetLegacySigOpCount();
1577 if (nSigOps > MAX_BLOCK_SIGOPS)
1578 return DoS(100, error("ConnectBlock() : too many sigops"));
1580 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1582 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1584 MapPrevTx mapInputs;
1585 if (tx.IsCoinBase())
1586 nValueOut += tx.GetValueOut();
1590 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1593 if (fStrictPayToScriptHash)
1595 // Add in sigops done by pay-to-script-hash inputs;
1596 // this is to prevent a "rogue miner" from creating
1597 // an incredibly-expensive-to-validate block.
1598 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1599 if (nSigOps > MAX_BLOCK_SIGOPS)
1600 return DoS(100, error("ConnectBlock() : too many sigops"));
1603 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1604 int64 nTxValueOut = tx.GetValueOut();
1605 nValueIn += nTxValueIn;
1606 nValueOut += nTxValueOut;
1607 if (!tx.IsCoinStake())
1608 nFees += nTxValueIn - nTxValueOut;
1610 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1614 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1617 // ppcoin: track money supply and mint amount info
1618 pindex->nMint = nValueOut - nValueIn + nFees;
1619 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1620 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1621 return error("Connect() : WriteBlockIndex for pindex failed");
1623 // ppcoin: fees are not collected by miners as in bitcoin
1624 // ppcoin: fees are destroyed to compensate the entire network
1625 if (fDebug && GetBoolArg("-printcreation"))
1626 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1631 // Write queued txindex changes
1632 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1634 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1635 return error("ConnectBlock() : UpdateTxIndex failed");
1638 // Update block index on disk without changing it in memory.
1639 // The memory index structure will be changed after the db commits.
1642 CDiskBlockIndex blockindexPrev(pindex->pprev);
1643 blockindexPrev.hashNext = pindex->GetBlockHash();
1644 if (!txdb.WriteBlockIndex(blockindexPrev))
1645 return error("ConnectBlock() : WriteBlockIndex failed");
1648 // Watch for transactions paying to me
1649 BOOST_FOREACH(CTransaction& tx, vtx)
1650 SyncWithWallets(tx, this, true);
1655 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1657 printf("REORGANIZE\n");
1660 CBlockIndex* pfork = pindexBest;
1661 CBlockIndex* plonger = pindexNew;
1662 while (pfork != plonger)
1664 while (plonger->nHeight > pfork->nHeight)
1665 if (!(plonger = plonger->pprev))
1666 return error("Reorganize() : plonger->pprev is null");
1667 if (pfork == plonger)
1669 if (!(pfork = pfork->pprev))
1670 return error("Reorganize() : pfork->pprev is null");
1673 // List of what to disconnect
1674 vector<CBlockIndex*> vDisconnect;
1675 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1676 vDisconnect.push_back(pindex);
1678 // List of what to connect
1679 vector<CBlockIndex*> vConnect;
1680 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1681 vConnect.push_back(pindex);
1682 reverse(vConnect.begin(), vConnect.end());
1684 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());
1685 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());
1687 // Disconnect shorter branch
1688 vector<CTransaction> vResurrect;
1689 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1692 if (!block.ReadFromDisk(pindex))
1693 return error("Reorganize() : ReadFromDisk for disconnect failed");
1694 if (!block.DisconnectBlock(txdb, pindex))
1695 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1697 // Queue memory transactions to resurrect
1698 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1699 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1700 vResurrect.push_back(tx);
1703 // Connect longer branch
1704 vector<CTransaction> vDelete;
1705 for (unsigned int i = 0; i < vConnect.size(); i++)
1707 CBlockIndex* pindex = vConnect[i];
1709 if (!block.ReadFromDisk(pindex))
1710 return error("Reorganize() : ReadFromDisk for connect failed");
1711 if (!block.ConnectBlock(txdb, pindex))
1714 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1717 // Queue memory transactions to delete
1718 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1719 vDelete.push_back(tx);
1721 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1722 return error("Reorganize() : WriteHashBestChain failed");
1724 // Make sure it's successfully written to disk before changing memory structure
1725 if (!txdb.TxnCommit())
1726 return error("Reorganize() : TxnCommit failed");
1728 // Disconnect shorter branch
1729 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1731 pindex->pprev->pnext = NULL;
1733 // Connect longer branch
1734 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1736 pindex->pprev->pnext = pindex;
1738 // Resurrect memory transactions that were in the disconnected branch
1739 BOOST_FOREACH(CTransaction& tx, vResurrect)
1740 tx.AcceptToMemoryPool(txdb, false);
1742 // Delete redundant memory transactions that are in the connected branch
1743 BOOST_FOREACH(CTransaction& tx, vDelete)
1746 printf("REORGANIZE: done\n");
1752 // Called from inside SetBestChain: attaches a block to the new best chain being built
1753 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1755 uint256 hash = GetHash();
1757 // Adding to current best branch
1758 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1761 InvalidChainFound(pindexNew);
1764 if (!txdb.TxnCommit())
1765 return error("SetBestChain() : TxnCommit failed");
1767 // Add to current best branch
1768 pindexNew->pprev->pnext = pindexNew;
1770 // Delete redundant memory transactions
1771 BOOST_FOREACH(CTransaction& tx, vtx)
1777 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1779 uint256 hash = GetHash();
1781 if (!txdb.TxnBegin())
1782 return error("SetBestChain() : TxnBegin failed");
1784 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1786 txdb.WriteHashBestChain(hash);
1787 if (!txdb.TxnCommit())
1788 return error("SetBestChain() : TxnCommit failed");
1789 pindexGenesisBlock = pindexNew;
1791 else if (hashPrevBlock == hashBestChain)
1793 if (!SetBestChainInner(txdb, pindexNew))
1794 return error("SetBestChain() : SetBestChainInner failed");
1798 // the first block in the new chain that will cause it to become the new best chain
1799 CBlockIndex *pindexIntermediate = pindexNew;
1801 // list of blocks that need to be connected afterwards
1802 std::vector<CBlockIndex*> vpindexSecondary;
1804 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1805 // Try to limit how much needs to be done inside
1806 while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust)
1808 vpindexSecondary.push_back(pindexIntermediate);
1809 pindexIntermediate = pindexIntermediate->pprev;
1812 if (!vpindexSecondary.empty())
1813 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1815 // Switch to new best branch
1816 if (!Reorganize(txdb, pindexIntermediate))
1819 InvalidChainFound(pindexNew);
1820 return error("SetBestChain() : Reorganize failed");
1823 // Connect further blocks
1824 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1827 if (!block.ReadFromDisk(pindex))
1829 printf("SetBestChain() : ReadFromDisk failed\n");
1832 if (!txdb.TxnBegin()) {
1833 printf("SetBestChain() : TxnBegin 2 failed\n");
1836 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1837 if (!block.SetBestChainInner(txdb, pindex))
1842 // Update best block in wallet (so we can detect restored wallets)
1843 bool fIsInitialDownload = IsInitialBlockDownload();
1844 if (!fIsInitialDownload)
1846 const CBlockLocator locator(pindexNew);
1847 ::SetBestChain(locator);
1851 hashBestChain = hash;
1852 pindexBest = pindexNew;
1853 pblockindexFBBHLast = NULL;
1854 nBestHeight = pindexBest->nHeight;
1855 bnBestChainTrust = pindexNew->bnChainTrust;
1856 nTimeBestReceived = GetTime();
1857 nTransactionsUpdated++;
1858 printf("SetBestChain: new best=%s height=%d trust=%s date=%s\n",
1859 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(),
1860 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1862 // Check the version of the last 100 blocks to see if we need to upgrade:
1863 if (!fIsInitialDownload)
1866 const CBlockIndex* pindex = pindexBest;
1867 for (int i = 0; i < 100 && pindex != NULL; i++)
1869 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1871 pindex = pindex->pprev;
1874 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1875 if (nUpgraded > 100/2)
1876 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1877 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1880 std::string strCmd = GetArg("-blocknotify", "");
1882 if (!fIsInitialDownload && !strCmd.empty())
1884 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1885 boost::thread t(runCommand, strCmd); // thread runs free
1891 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1892 // Only those coins meeting minimum age requirement counts. As those
1893 // transactions not in main chain are not currently indexed so we
1894 // might not find out about their coin age. Older transactions are
1895 // guaranteed to be in main chain by sync-checkpoint. This rule is
1896 // introduced to help nodes establish a consistent view of the coin
1897 // age (trust score) of competing branches.
1898 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1900 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1906 BOOST_FOREACH(const CTxIn& txin, vin)
1908 // First try finding the previous transaction in database
1909 CTransaction txPrev;
1911 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1912 continue; // previous transaction not in main chain
1913 if (nTime < txPrev.nTime)
1914 return false; // Transaction timestamp violation
1916 // Read block header
1918 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1919 return false; // unable to read block of previous transaction
1920 if (block.GetBlockTime() + nStakeMinAge > nTime)
1921 continue; // only count coins meeting min age requirement
1923 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1924 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1926 if (fDebug && GetBoolArg("-printcoinage"))
1927 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1930 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1931 if (fDebug && GetBoolArg("-printcoinage"))
1932 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1933 nCoinAge = bnCoinDay.getuint64();
1937 // ppcoin: total coin age spent in block, in the unit of coin-days.
1938 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1943 BOOST_FOREACH(const CTransaction& tx, vtx)
1946 if (tx.GetCoinAge(txdb, nTxCoinAge))
1947 nCoinAge += nTxCoinAge;
1952 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1954 if (fDebug && GetBoolArg("-printcoinage"))
1955 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1959 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1961 // Check for duplicate
1962 uint256 hash = GetHash();
1963 if (mapBlockIndex.count(hash))
1964 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1966 // Construct new block index object
1967 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1969 return error("AddToBlockIndex() : new CBlockIndex failed");
1970 pindexNew->phashBlock = &hash;
1971 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1972 if (miPrev != mapBlockIndex.end())
1974 pindexNew->pprev = (*miPrev).second;
1975 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1978 // ppcoin: compute chain trust score
1979 pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
1981 // ppcoin: compute stake entropy bit for stake modifier
1982 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
1983 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
1985 // ppcoin: record proof-of-stake hash value
1986 if (pindexNew->IsProofOfStake())
1988 if (!mapProofOfStake.count(hash))
1989 return error("AddToBlockIndex() : hashProofOfStake not found in map");
1990 pindexNew->hashProofOfStake = mapProofOfStake[hash];
1993 // ppcoin: compute stake modifier
1994 uint64 nStakeModifier = 0;
1995 bool fGeneratedStakeModifier = false;
1996 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
1997 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
1998 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
1999 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2000 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2001 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2003 // Add to mapBlockIndex
2004 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2005 if (pindexNew->IsProofOfStake())
2006 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2007 pindexNew->phashBlock = &((*mi).first);
2009 // Write to disk block index
2011 if (!txdb.TxnBegin())
2013 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2014 if (!txdb.TxnCommit())
2018 if (pindexNew->bnChainTrust > bnBestChainTrust)
2019 if (!SetBestChain(txdb, pindexNew))
2024 if (pindexNew == pindexBest)
2026 // Notify UI to display prev block's coinbase if it was ours
2027 static uint256 hashPrevBestCoinBase;
2028 UpdatedTransaction(hashPrevBestCoinBase);
2029 hashPrevBestCoinBase = vtx[0].GetHash();
2032 uiInterface.NotifyBlocksChanged();
2039 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
2041 // These are checks that are independent of context
2042 // that can be verified before saving an orphan block.
2045 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2046 return DoS(100, error("CheckBlock() : size limits failed"));
2048 // Special short-term limits to avoid 10,000 BDB lock limit:
2049 if (GetBlockTime() < LOCKS_SWITCH_TIME)
2051 // Rule is: #unique txids referenced <= 4,500
2052 // ... to prevent 10,000 BDB lock exhaustion on old clients
2053 set<uint256> setTxIn;
2054 for (size_t i = 0; i < vtx.size(); i++)
2056 setTxIn.insert(vtx[i].GetHash());
2057 if (i == 0) continue; // skip coinbase txin
2058 BOOST_FOREACH(const CTxIn& txin, vtx[i].vin)
2059 setTxIn.insert(txin.prevout.hash);
2061 size_t nTxids = setTxIn.size();
2063 return error("CheckBlock() : maxlocks violation");
2066 // Check proof of work matches claimed amount
2067 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2068 return DoS(50, error("CheckBlock() : proof of work failed"));
2071 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
2072 return error("CheckBlock() : block timestamp too far in the future");
2074 // First transaction must be coinbase, the rest must not be
2075 if (vtx.empty() || !vtx[0].IsCoinBase())
2076 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2077 for (unsigned int i = 1; i < vtx.size(); i++)
2078 if (vtx[i].IsCoinBase())
2079 return DoS(100, error("CheckBlock() : more than one coinbase"));
2081 // ppcoin: only the second transaction can be the optional coinstake
2082 for (unsigned int i = 2; i < vtx.size(); i++)
2083 if (vtx[i].IsCoinStake())
2084 return DoS(100, error("CheckBlock() : coinstake in wrong position"));
2086 // ppcoin: coinbase output should be empty if proof-of-stake block
2087 if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty()))
2088 return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
2090 // Check coinbase timestamp
2091 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
2092 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2094 // Check coinstake timestamp
2095 if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2096 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2098 // Check coinbase reward
2099 if (vtx[0].GetValueOut() > (IsProofOfWork()? (GetProofOfWorkReward(nBits) - vtx[0].GetMinFee() + MIN_TX_FEE) : 0))
2100 return DoS(50, error("CheckBlock() : coinbase reward exceeded %s > %s",
2101 FormatMoney(vtx[0].GetValueOut()).c_str(),
2102 FormatMoney(IsProofOfWork()? GetProofOfWorkReward(nBits) : 0).c_str()));
2104 // Check transactions
2105 BOOST_FOREACH(const CTransaction& tx, vtx)
2107 if (!tx.CheckTransaction())
2108 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2110 // ppcoin: check transaction timestamp
2111 if (GetBlockTime() < (int64)tx.nTime)
2112 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2115 // Check for duplicate txids. This is caught by ConnectInputs(),
2116 // but catching it earlier avoids a potential DoS attack:
2117 set<uint256> uniqueTx;
2118 BOOST_FOREACH(const CTransaction& tx, vtx)
2120 uniqueTx.insert(tx.GetHash());
2122 if (uniqueTx.size() != vtx.size())
2123 return DoS(100, error("CheckBlock() : duplicate transaction"));
2125 unsigned int nSigOps = 0;
2126 BOOST_FOREACH(const CTransaction& tx, vtx)
2128 nSigOps += tx.GetLegacySigOpCount();
2130 if (nSigOps > MAX_BLOCK_SIGOPS)
2131 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2133 // Check merkle root
2134 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2135 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2137 // ppcoin: check block signature
2138 if (!CheckBlockSignature())
2139 return DoS(100, error("CheckBlock() : bad block signature"));
2144 bool CBlock::AcceptBlock()
2146 // Check for duplicate
2147 uint256 hash = GetHash();
2148 if (mapBlockIndex.count(hash))
2149 return error("AcceptBlock() : block already in mapBlockIndex");
2151 // Get prev block index
2152 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2153 if (mi == mapBlockIndex.end())
2154 return DoS(10, error("AcceptBlock() : prev block not found"));
2155 CBlockIndex* pindexPrev = (*mi).second;
2156 int nHeight = pindexPrev->nHeight+1;
2158 // Check proof-of-work or proof-of-stake
2159 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2160 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2162 // Check timestamp against prev
2163 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
2164 return error("AcceptBlock() : block's timestamp is too early");
2166 // Check that all transactions are finalized
2167 BOOST_FOREACH(const CTransaction& tx, vtx)
2168 if (!tx.IsFinal(nHeight, GetBlockTime()))
2169 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2171 // Check that the block chain matches the known block chain up to a checkpoint
2172 if (!Checkpoints::CheckHardened(nHeight, hash))
2173 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2175 // ppcoin: check that the block satisfies synchronized checkpoint
2176 if (!Checkpoints::CheckSync(hash, pindexPrev))
2178 if(!GetBoolArg("-nosynccheckpoints", false))
2180 return error("AcceptBlock() : rejected by synchronized checkpoint");
2184 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2188 // Reject block.nVersion < 3 blocks since 95% threshold on mainNet and always on testNet:
2189 if (nVersion < 3 && ((!fTestNet && nHeight > 14060) || (fTestNet && nHeight > 0)))
2190 return error("CheckBlock() : rejected nVersion < 3 block");
2192 // Enforce rule that the coinbase starts with serialized block height
2193 CScript expect = CScript() << nHeight;
2194 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2195 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2197 // Write block to history file
2198 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2199 return error("AcceptBlock() : out of disk space");
2200 unsigned int nFile = -1;
2201 unsigned int nBlockPos = 0;
2202 if (!WriteToDisk(nFile, nBlockPos))
2203 return error("AcceptBlock() : WriteToDisk failed");
2204 if (!AddToBlockIndex(nFile, nBlockPos))
2205 return error("AcceptBlock() : AddToBlockIndex failed");
2207 // Relay inventory, but don't relay old inventory during initial block download
2208 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2209 if (hashBestChain == hash)
2212 BOOST_FOREACH(CNode* pnode, vNodes)
2213 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2214 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2217 // ppcoin: check pending sync-checkpoint
2218 Checkpoints::AcceptPendingSyncCheckpoint();
2223 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2225 unsigned int nFound = 0;
2226 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2228 if (pstart->nVersion >= minVersion)
2230 pstart = pstart->pprev;
2232 return (nFound >= nRequired);
2235 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2237 // Check for duplicate
2238 uint256 hash = pblock->GetHash();
2239 if (mapBlockIndex.count(hash))
2240 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2241 if (mapOrphanBlocks.count(hash))
2242 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2244 // ppcoin: check proof-of-stake
2245 // Limited duplicity on stake: prevents block flood attack
2246 // Duplicate stake allowed only when there is orphan child block
2247 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2248 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());
2250 // Preliminary checks
2251 if (!pblock->CheckBlock())
2252 return error("ProcessBlock() : CheckBlock FAILED");
2254 // ppcoin: verify hash target and signature of coinstake tx
2255 if (pblock->IsProofOfStake())
2257 uint256 hashProofOfStake = 0;
2258 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake))
2260 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2261 return false; // do not error here as we expect this during initial block download
2263 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2264 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2267 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2268 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2270 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2271 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2273 bnNewBlock.SetCompact(pblock->nBits);
2275 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime));
2276 if (bnNewBlock > bnRequired)
2279 pfrom->Misbehaving(100);
2280 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2284 // ppcoin: ask for pending sync-checkpoint if any
2285 if (!IsInitialBlockDownload())
2286 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2288 // If don't already have its previous block, shunt it off to holding area until we get it
2289 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2291 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2292 CBlock* pblock2 = new CBlock(*pblock);
2293 // ppcoin: check proof-of-stake
2294 if (pblock2->IsProofOfStake())
2296 // Limited duplicity on stake: prevents block flood attack
2297 // Duplicate stake allowed only when there is orphan child block
2298 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2299 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());
2301 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2303 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2304 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2306 // Ask this guy to fill in what we're missing
2309 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2310 // ppcoin: getblocks may not obtain the ancestor block rejected
2311 // earlier by duplicate-stake check so we ask for it again directly
2312 if (!IsInitialBlockDownload())
2313 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2319 if (!pblock->AcceptBlock())
2320 return error("ProcessBlock() : AcceptBlock FAILED");
2322 // Recursively process any orphan blocks that depended on this one
2323 vector<uint256> vWorkQueue;
2324 vWorkQueue.push_back(hash);
2325 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2327 uint256 hashPrev = vWorkQueue[i];
2328 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2329 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2332 CBlock* pblockOrphan = (*mi).second;
2333 if (pblockOrphan->AcceptBlock())
2334 vWorkQueue.push_back(pblockOrphan->GetHash());
2335 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2336 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2337 delete pblockOrphan;
2339 mapOrphanBlocksByPrev.erase(hashPrev);
2342 printf("ProcessBlock: ACCEPTED\n");
2344 // ppcoin: if responsible for sync-checkpoint send it
2345 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2346 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2351 // ppcoin: sign block
2352 bool CBlock::SignBlock(const CKeyStore& keystore)
2354 vector<valtype> vSolutions;
2355 txnouttype whichType;
2357 if(!IsProofOfStake())
2359 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2361 const CTxOut& txout = vtx[0].vout[i];
2363 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2366 if (whichType == TX_PUBKEY)
2369 valtype& vchPubKey = vSolutions[0];
2372 if (!keystore.GetKey(Hash160(vchPubKey), key))
2374 if (key.GetPubKey() != vchPubKey)
2376 if(!key.Sign(GetHash(), vchBlockSig))
2385 const CTxOut& txout = vtx[1].vout[1];
2387 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2390 if (whichType == TX_PUBKEY)
2393 valtype& vchPubKey = vSolutions[0];
2396 if (!keystore.GetKey(Hash160(vchPubKey), key))
2398 if (key.GetPubKey() != vchPubKey)
2401 return key.Sign(GetHash(), vchBlockSig);
2405 printf("Sign failed\n");
2409 // ppcoin: check block signature
2410 bool CBlock::CheckBlockSignature() const
2412 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2413 return vchBlockSig.empty();
2415 vector<valtype> vSolutions;
2416 txnouttype whichType;
2418 if(IsProofOfStake())
2420 const CTxOut& txout = vtx[1].vout[1];
2422 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2424 if (whichType == TX_PUBKEY)
2426 valtype& vchPubKey = vSolutions[0];
2428 if (!key.SetPubKey(vchPubKey))
2430 if (vchBlockSig.empty())
2432 return key.Verify(GetHash(), vchBlockSig);
2437 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2439 const CTxOut& txout = vtx[0].vout[i];
2441 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2444 if (whichType == TX_PUBKEY)
2447 valtype& vchPubKey = vSolutions[0];
2449 if (!key.SetPubKey(vchPubKey))
2451 if (vchBlockSig.empty())
2453 if(!key.Verify(GetHash(), vchBlockSig))
2463 bool CheckDiskSpace(uint64 nAdditionalBytes)
2465 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2467 // Check for nMinDiskSpace bytes (currently 50MB)
2468 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2471 string strMessage = _("Warning: Disk space is low!");
2472 strMiscWarning = strMessage;
2473 printf("*** %s\n", strMessage.c_str());
2474 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2481 static filesystem::path BlockFilePath(unsigned int nFile)
2483 string strBlockFn = strprintf("blk%04u.dat", nFile);
2484 return GetDataDir() / strBlockFn;
2487 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2489 if ((nFile < 1) || (nFile == (unsigned int) -1))
2491 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2494 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2496 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2505 static unsigned int nCurrentBlockFile = 1;
2507 FILE* AppendBlockFile(unsigned int& nFileRet)
2512 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2515 if (fseek(file, 0, SEEK_END) != 0)
2517 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2518 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2520 nFileRet = nCurrentBlockFile;
2524 nCurrentBlockFile++;
2528 bool LoadBlockIndex(bool fAllowNew)
2532 pchMessageStart[0] = 0xcd;
2533 pchMessageStart[1] = 0xf2;
2534 pchMessageStart[2] = 0xc0;
2535 pchMessageStart[3] = 0xef;
2537 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2538 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2539 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2540 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2541 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2548 if (!txdb.LoadBlockIndex())
2553 // Init with genesis block
2555 if (mapBlockIndex.empty())
2564 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2565 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2566 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2568 // vMerkleTree: 4cb33b3b6a
2572 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2573 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2574 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2576 // vMerkleTree: 4cb33b3b6a
2578 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2580 txNew.nTime = 1360105017;
2581 txNew.vin.resize(1);
2582 txNew.vout.resize(1);
2583 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2584 txNew.vout[0].SetEmpty();
2586 block.vtx.push_back(txNew);
2587 block.hashPrevBlock = 0;
2588 block.hashMerkleRoot = block.BuildMerkleTree();
2590 block.nTime = 1360105017;
2591 block.nBits = bnProofOfWorkLimit.GetCompact();
2592 block.nNonce = !fTestNet ? 1575379 : 46534;
2595 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2597 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2598 assert(block.CheckBlock());
2600 // Start new block file
2602 unsigned int nBlockPos;
2603 if (!block.WriteToDisk(nFile, nBlockPos))
2604 return error("LoadBlockIndex() : writing genesis block to disk failed");
2605 if (!block.AddToBlockIndex(nFile, nBlockPos))
2606 return error("LoadBlockIndex() : genesis block not accepted");
2608 // ppcoin: initialize synchronized checkpoint
2609 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2610 return error("LoadBlockIndex() : failed to init sync checkpoint");
2613 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2616 string strPubKey = "";
2617 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2619 // write checkpoint master key to db
2621 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2622 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2623 if (!txdb.TxnCommit())
2624 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2625 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2626 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2636 void PrintBlockTree()
2638 // pre-compute tree structure
2639 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2640 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2642 CBlockIndex* pindex = (*mi).second;
2643 mapNext[pindex->pprev].push_back(pindex);
2645 //while (rand() % 3 == 0)
2646 // mapNext[pindex->pprev].push_back(pindex);
2649 vector<pair<int, CBlockIndex*> > vStack;
2650 vStack.push_back(make_pair(0, pindexGenesisBlock));
2653 while (!vStack.empty())
2655 int nCol = vStack.back().first;
2656 CBlockIndex* pindex = vStack.back().second;
2659 // print split or gap
2660 if (nCol > nPrevCol)
2662 for (int i = 0; i < nCol-1; i++)
2666 else if (nCol < nPrevCol)
2668 for (int i = 0; i < nCol; i++)
2675 for (int i = 0; i < nCol; i++)
2680 block.ReadFromDisk(pindex);
2681 printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
2685 block.GetHash().ToString().c_str(),
2687 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2688 FormatMoney(pindex->nMint).c_str(),
2691 PrintWallets(block);
2693 // put the main time-chain first
2694 vector<CBlockIndex*>& vNext = mapNext[pindex];
2695 for (unsigned int i = 0; i < vNext.size(); i++)
2697 if (vNext[i]->pnext)
2699 swap(vNext[0], vNext[i]);
2705 for (unsigned int i = 0; i < vNext.size(); i++)
2706 vStack.push_back(make_pair(nCol+i, vNext[i]));
2710 bool LoadExternalBlockFile(FILE* fileIn)
2712 int64 nStart = GetTimeMillis();
2718 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2719 unsigned int nPos = 0;
2720 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2722 unsigned char pchData[65536];
2724 fseek(blkdat, nPos, SEEK_SET);
2725 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2728 nPos = (unsigned int)-1;
2731 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2734 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2736 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2739 nPos += ((unsigned char*)nFind - pchData) + 1;
2742 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2743 } while(!fRequestShutdown);
2744 if (nPos == (unsigned int)-1)
2746 fseek(blkdat, nPos, SEEK_SET);
2749 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2753 if (ProcessBlock(NULL,&block))
2761 catch (std::exception &e) {
2762 printf("%s() : Deserialize or I/O error caught during load\n",
2763 __PRETTY_FUNCTION__);
2766 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2778 //////////////////////////////////////////////////////////////////////////////
2783 extern map<uint256, CAlert> mapAlerts;
2784 extern CCriticalSection cs_mapAlerts;
2786 static string strMintMessage = "Info: Minting suspended due to locked wallet.";
2787 static string strMintWarning;
2789 string GetWarnings(string strFor)
2792 string strStatusBar;
2795 if (GetBoolArg("-testsafemode"))
2798 // ppcoin: wallet lock warning for minting
2799 if (strMintWarning != "")
2802 strStatusBar = strMintWarning;
2805 // Misc warnings like out of disk space and clock is wrong
2806 if (strMiscWarning != "")
2809 strStatusBar = strMiscWarning;
2812 // ppcoin: should not enter safe mode for longer invalid chain
2813 // ppcoin: if sync-checkpoint is too old do not enter safe mode
2814 if (Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) && !fTestNet && !IsInitialBlockDownload())
2817 strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.";
2820 // ppcoin: if detected invalid checkpoint enter safe mode
2821 if (Checkpoints::hashInvalidCheckpoint != 0)
2824 strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.";
2830 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2832 const CAlert& alert = item.second;
2833 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2835 nPriority = alert.nPriority;
2836 strStatusBar = alert.strStatusBar;
2837 if (nPriority > 1000)
2838 strRPC = strStatusBar; // ppcoin: safe mode for high alert
2843 if (strFor == "statusbar")
2844 return strStatusBar;
2845 else if (strFor == "rpc")
2847 assert(!"GetWarnings() : invalid parameter");
2858 //////////////////////////////////////////////////////////////////////////////
2864 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2870 bool txInMap = false;
2873 txInMap = (mempool.exists(inv.hash));
2876 mapOrphanTransactions.count(inv.hash) ||
2877 txdb.ContainsTx(inv.hash);
2881 return mapBlockIndex.count(inv.hash) ||
2882 mapOrphanBlocks.count(inv.hash);
2884 // Don't know what it is, just say we already got one
2891 // The message start string is designed to be unlikely to occur in normal data.
2892 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
2893 // a large 4-byte int at any alignment.
2894 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
2896 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2898 static map<CService, CPubKey> mapReuseKey;
2899 RandAddSeedPerfmon();
2901 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
2902 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2904 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2912 if (strCommand == "version")
2914 // Each connection can only send one version message
2915 if (pfrom->nVersion != 0)
2917 pfrom->Misbehaving(1);
2925 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2926 if (pfrom->nVersion < MIN_PROTO_VERSION)
2928 // Since February 20, 2012, the protocol is initiated at version 209,
2929 // and earlier versions are no longer supported
2930 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2931 pfrom->fDisconnect = true;
2935 if (pfrom->nVersion == 10300)
2936 pfrom->nVersion = 300;
2938 vRecv >> addrFrom >> nNonce;
2940 vRecv >> pfrom->strSubVer;
2942 vRecv >> pfrom->nStartingHeight;
2944 if (pfrom->fInbound && addrMe.IsRoutable())
2946 pfrom->addrLocal = addrMe;
2950 // Disconnect if we connected to ourself
2951 if (nNonce == nLocalHostNonce && nNonce > 1)
2953 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2954 pfrom->fDisconnect = true;
2958 // ppcoin: record my external IP reported by peer
2959 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
2960 addrSeenByPeer = addrMe;
2962 // Be shy and don't send version until we hear
2963 if (pfrom->fInbound)
2964 pfrom->PushVersion();
2966 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2968 AddTimeData(pfrom->addr, nTime);
2971 pfrom->PushMessage("verack");
2972 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2974 if (!pfrom->fInbound)
2976 // Advertise our address
2977 if (!fNoListen && !IsInitialBlockDownload())
2979 CAddress addr = GetLocalAddress(&pfrom->addr);
2980 if (addr.IsRoutable())
2981 pfrom->PushAddress(addr);
2984 // Get recent addresses
2985 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2987 pfrom->PushMessage("getaddr");
2988 pfrom->fGetAddr = true;
2990 addrman.Good(pfrom->addr);
2992 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2994 addrman.Add(addrFrom, addrFrom);
2995 addrman.Good(addrFrom);
2999 // Ask the first connected node for block updates
3000 static int nAskedForBlocks = 0;
3001 if (!pfrom->fClient && !pfrom->fOneShot &&
3002 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3003 (pfrom->nVersion < NOBLKS_VERSION_START ||
3004 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3005 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3008 pfrom->PushGetBlocks(pindexBest, uint256(0));
3014 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3015 item.second.RelayTo(pfrom);
3018 // ppcoin: relay sync-checkpoint
3020 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3021 if (!Checkpoints::checkpointMessage.IsNull())
3022 Checkpoints::checkpointMessage.RelayTo(pfrom);
3025 pfrom->fSuccessfullyConnected = true;
3027 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());
3029 cPeerBlockCounts.input(pfrom->nStartingHeight);
3031 // ppcoin: ask for pending sync-checkpoint if any
3032 if (!IsInitialBlockDownload())
3033 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3037 else if (pfrom->nVersion == 0)
3039 // Must have a version message before anything else
3040 pfrom->Misbehaving(1);
3045 else if (strCommand == "verack")
3047 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3051 else if (strCommand == "addr")
3053 vector<CAddress> vAddr;
3056 // Don't want addr from older versions unless seeding
3057 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3059 if (vAddr.size() > 1000)
3061 pfrom->Misbehaving(20);
3062 return error("message addr size() = %"PRIszu"", vAddr.size());
3065 // Store the new addresses
3066 vector<CAddress> vAddrOk;
3067 int64 nNow = GetAdjustedTime();
3068 int64 nSince = nNow - 10 * 60;
3069 BOOST_FOREACH(CAddress& addr, vAddr)
3073 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3074 addr.nTime = nNow - 5 * 24 * 60 * 60;
3075 pfrom->AddAddressKnown(addr);
3076 bool fReachable = IsReachable(addr);
3077 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3079 // Relay to a limited number of other nodes
3082 // Use deterministic randomness to send to the same nodes for 24 hours
3083 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3084 static uint256 hashSalt;
3086 hashSalt = GetRandHash();
3087 uint64 hashAddr = addr.GetHash();
3088 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3089 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3090 multimap<uint256, CNode*> mapMix;
3091 BOOST_FOREACH(CNode* pnode, vNodes)
3093 if (pnode->nVersion < CADDR_TIME_VERSION)
3095 unsigned int nPointer;
3096 memcpy(&nPointer, &pnode, sizeof(nPointer));
3097 uint256 hashKey = hashRand ^ nPointer;
3098 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3099 mapMix.insert(make_pair(hashKey, pnode));
3101 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3102 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3103 ((*mi).second)->PushAddress(addr);
3106 // Do not store addresses outside our network
3108 vAddrOk.push_back(addr);
3110 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3111 if (vAddr.size() < 1000)
3112 pfrom->fGetAddr = false;
3113 if (pfrom->fOneShot)
3114 pfrom->fDisconnect = true;
3118 else if (strCommand == "inv")
3122 if (vInv.size() > MAX_INV_SZ)
3124 pfrom->Misbehaving(20);
3125 return error("message inv size() = %"PRIszu"", vInv.size());
3128 // find last block in inv vector
3129 unsigned int nLastBlock = (unsigned int)(-1);
3130 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3131 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3132 nLastBlock = vInv.size() - 1 - nInv;
3137 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3139 const CInv &inv = vInv[nInv];
3143 pfrom->AddInventoryKnown(inv);
3145 bool fAlreadyHave = AlreadyHave(txdb, inv);
3147 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3151 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3152 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3153 } else if (nInv == nLastBlock) {
3154 // In case we are on a very long side-chain, it is possible that we already have
3155 // the last block in an inv bundle sent in response to getblocks. Try to detect
3156 // this situation and push another getblocks to continue.
3157 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3159 printf("force request: %s\n", inv.ToString().c_str());
3162 // Track requests for our stuff
3163 Inventory(inv.hash);
3168 else if (strCommand == "getdata")
3172 if (vInv.size() > MAX_INV_SZ)
3174 pfrom->Misbehaving(20);
3175 return error("message getdata size() = %"PRIszu"", vInv.size());
3178 if (fDebugNet || (vInv.size() != 1))
3179 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3181 BOOST_FOREACH(const CInv& inv, vInv)
3185 if (fDebugNet || (vInv.size() == 1))
3186 printf("received getdata for: %s\n", inv.ToString().c_str());
3188 if (inv.type == MSG_BLOCK)
3190 // Send block from disk
3191 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3192 if (mi != mapBlockIndex.end())
3195 block.ReadFromDisk((*mi).second);
3196 pfrom->PushMessage("block", block);
3198 // Trigger them to send a getblocks request for the next batch of inventory
3199 if (inv.hash == pfrom->hashContinue)
3201 // ppcoin: send latest proof-of-work block to allow the
3202 // download node to accept as orphan (proof-of-stake
3203 // block might be rejected by stake connection check)
3205 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3206 pfrom->PushMessage("inv", vInv);
3207 pfrom->hashContinue = 0;
3211 else if (inv.IsKnownType())
3213 // Send stream from relay memory
3214 bool pushed = false;
3217 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3218 if (mi != mapRelay.end()) {
3219 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3223 if (!pushed && inv.type == MSG_TX) {
3225 if (mempool.exists(inv.hash)) {
3226 CTransaction tx = mempool.lookup(inv.hash);
3227 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3230 pfrom->PushMessage("tx", ss);
3235 // Track requests for our stuff
3236 Inventory(inv.hash);
3241 else if (strCommand == "getblocks")
3243 CBlockLocator locator;
3245 vRecv >> locator >> hashStop;
3247 // Find the last block the caller has in the main chain
3248 CBlockIndex* pindex = locator.GetBlockIndex();
3250 // Send the rest of the chain
3252 pindex = pindex->pnext;
3254 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3255 for (; pindex; pindex = pindex->pnext)
3257 if (pindex->GetBlockHash() == hashStop)
3259 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3260 // ppcoin: tell downloading node about the latest block if it's
3261 // without risk being rejected due to stake connection check
3262 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3263 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3266 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3269 // When this block is requested, we'll send an inv that'll make them
3270 // getblocks the next batch of inventory.
3271 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3272 pfrom->hashContinue = pindex->GetBlockHash();
3277 else if (strCommand == "checkpoint")
3279 CSyncCheckpoint checkpoint;
3280 vRecv >> checkpoint;
3282 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3285 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3287 BOOST_FOREACH(CNode* pnode, vNodes)
3288 checkpoint.RelayTo(pnode);
3292 else if (strCommand == "getheaders")
3294 CBlockLocator locator;
3296 vRecv >> locator >> hashStop;
3298 CBlockIndex* pindex = NULL;
3299 if (locator.IsNull())
3301 // If locator is null, return the hashStop block
3302 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3303 if (mi == mapBlockIndex.end())
3305 pindex = (*mi).second;
3309 // Find the last block the caller has in the main chain
3310 pindex = locator.GetBlockIndex();
3312 pindex = pindex->pnext;
3315 vector<CBlock> vHeaders;
3317 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3318 for (; pindex; pindex = pindex->pnext)
3320 vHeaders.push_back(pindex->GetBlockHeader());
3321 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3324 pfrom->PushMessage("headers", vHeaders);
3328 else if (strCommand == "tx")
3330 vector<uint256> vWorkQueue;
3331 vector<uint256> vEraseQueue;
3332 CDataStream vMsg(vRecv);
3337 CInv inv(MSG_TX, tx.GetHash());
3338 pfrom->AddInventoryKnown(inv);
3340 bool fMissingInputs = false;
3341 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3343 SyncWithWallets(tx, NULL, true);
3344 RelayMessage(inv, vMsg);
3345 mapAlreadyAskedFor.erase(inv);
3346 vWorkQueue.push_back(inv.hash);
3347 vEraseQueue.push_back(inv.hash);
3349 // Recursively process any orphan transactions that depended on this one
3350 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3352 uint256 hashPrev = vWorkQueue[i];
3353 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3354 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3357 const CDataStream& vMsg = *((*mi).second);
3359 CDataStream(vMsg) >> tx;
3360 CInv inv(MSG_TX, tx.GetHash());
3361 bool fMissingInputs2 = false;
3363 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3365 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3366 SyncWithWallets(tx, NULL, true);
3367 RelayMessage(inv, vMsg);
3368 mapAlreadyAskedFor.erase(inv);
3369 vWorkQueue.push_back(inv.hash);
3370 vEraseQueue.push_back(inv.hash);
3372 else if (!fMissingInputs2)
3375 vEraseQueue.push_back(inv.hash);
3376 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3381 BOOST_FOREACH(uint256 hash, vEraseQueue)
3382 EraseOrphanTx(hash);
3384 else if (fMissingInputs)
3388 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3389 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3391 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3393 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3397 else if (strCommand == "block")
3402 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3405 CInv inv(MSG_BLOCK, block.GetHash());
3406 pfrom->AddInventoryKnown(inv);
3408 if (ProcessBlock(pfrom, &block))
3409 mapAlreadyAskedFor.erase(inv);
3410 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3414 else if (strCommand == "getaddr")
3416 pfrom->vAddrToSend.clear();
3417 vector<CAddress> vAddr = addrman.GetAddr();
3418 BOOST_FOREACH(const CAddress &addr, vAddr)
3419 pfrom->PushAddress(addr);
3423 else if (strCommand == "mempool")
3425 std::vector<uint256> vtxid;
3426 mempool.queryHashes(vtxid);
3428 for (unsigned int i = 0; i < vtxid.size(); i++) {
3429 CInv inv(MSG_TX, vtxid[i]);
3430 vInv.push_back(inv);
3431 if (i == (MAX_INV_SZ - 1))
3434 if (vInv.size() > 0)
3435 pfrom->PushMessage("inv", vInv);
3439 else if (strCommand == "checkorder")
3444 if (!GetBoolArg("-allowreceivebyip"))
3446 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3453 /// we have a chance to check the order here
3455 // Keep giving the same key to the same ip until they use it
3456 if (!mapReuseKey.count(pfrom->addr))
3457 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3459 // Send back approval of order and pubkey to use
3460 CScript scriptPubKey;
3461 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3462 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3466 else if (strCommand == "reply")
3471 CRequestTracker tracker;
3473 LOCK(pfrom->cs_mapRequests);
3474 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3475 if (mi != pfrom->mapRequests.end())
3477 tracker = (*mi).second;
3478 pfrom->mapRequests.erase(mi);
3481 if (!tracker.IsNull())
3482 tracker.fn(tracker.param1, vRecv);
3486 else if (strCommand == "ping")
3488 if (pfrom->nVersion > BIP0031_VERSION)
3492 // Echo the message back with the nonce. This allows for two useful features:
3494 // 1) A remote node can quickly check if the connection is operational
3495 // 2) Remote nodes can measure the latency of the network thread. If this node
3496 // is overloaded it won't respond to pings quickly and the remote node can
3497 // avoid sending us more work, like chain download requests.
3499 // The nonce stops the remote getting confused between different pings: without
3500 // it, if the remote node sends a ping once per second and this node takes 5
3501 // seconds to respond to each, the 5th ping the remote sends would appear to
3502 // return very quickly.
3503 pfrom->PushMessage("pong", nonce);
3508 else if (strCommand == "alert")
3513 uint256 alertHash = alert.GetHash();
3514 if (pfrom->setKnown.count(alertHash) == 0)
3516 if (alert.ProcessAlert())
3519 pfrom->setKnown.insert(alertHash);
3522 BOOST_FOREACH(CNode* pnode, vNodes)
3523 alert.RelayTo(pnode);
3527 // Small DoS penalty so peers that send us lots of
3528 // duplicate/expired/invalid-signature/whatever alerts
3529 // eventually get banned.
3530 // This isn't a Misbehaving(100) (immediate ban) because the
3531 // peer might be an older or different implementation with
3532 // a different signature key, etc.
3533 pfrom->Misbehaving(10);
3541 // Ignore unknown commands for extensibility
3545 // Update the last seen time for this node's address
3546 if (pfrom->fNetworkNode)
3547 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3548 AddressCurrentlyConnected(pfrom->addr);
3554 bool ProcessMessages(CNode* pfrom)
3556 CDataStream& vRecv = pfrom->vRecv;
3560 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3564 // (4) message start
3573 // Don't bother if send buffer is too full to respond anyway
3574 if (pfrom->vSend.size() >= SendBufferSize())
3577 // Scan for message start
3578 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3579 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3580 if (vRecv.end() - pstart < nHeaderSize)
3582 if ((int)vRecv.size() > nHeaderSize)
3584 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3585 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3589 if (pstart - vRecv.begin() > 0)
3590 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3591 vRecv.erase(vRecv.begin(), pstart);
3594 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3599 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3602 string strCommand = hdr.GetCommand();
3605 unsigned int nMessageSize = hdr.nMessageSize;
3606 if (nMessageSize > MAX_SIZE)
3608 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3611 if (nMessageSize > vRecv.size())
3613 // Rewind and wait for rest of message
3614 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3619 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3620 unsigned int nChecksum = 0;
3621 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3622 if (nChecksum != hdr.nChecksum)
3624 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3625 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3629 // Copy message to its own buffer
3630 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3631 vRecv.ignore(nMessageSize);
3639 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3644 catch (std::ios_base::failure& e)
3646 if (strstr(e.what(), "end of data"))
3648 // Allow exceptions from under-length message on vRecv
3649 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());
3651 else if (strstr(e.what(), "size too large"))
3653 // Allow exceptions from over-long size
3654 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3658 PrintExceptionContinue(&e, "ProcessMessages()");
3661 catch (std::exception& e) {
3662 PrintExceptionContinue(&e, "ProcessMessages()");
3664 PrintExceptionContinue(NULL, "ProcessMessages()");
3668 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3676 bool SendMessages(CNode* pto, bool fSendTrickle)
3678 TRY_LOCK(cs_main, lockMain);
3680 // Don't send anything until we get their version message
3681 if (pto->nVersion == 0)
3684 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3686 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3688 if (pto->nVersion > BIP0031_VERSION)
3689 pto->PushMessage("ping", nonce);
3691 pto->PushMessage("ping");
3694 // Resend wallet transactions that haven't gotten in a block yet
3695 ResendWalletTransactions();
3697 // Address refresh broadcast
3698 static int64 nLastRebroadcast;
3699 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3703 BOOST_FOREACH(CNode* pnode, vNodes)
3705 // Periodically clear setAddrKnown to allow refresh broadcasts
3706 if (nLastRebroadcast)
3707 pnode->setAddrKnown.clear();
3709 // Rebroadcast our address
3712 CAddress addr = GetLocalAddress(&pnode->addr);
3713 if (addr.IsRoutable())
3714 pnode->PushAddress(addr);
3718 nLastRebroadcast = GetTime();
3726 vector<CAddress> vAddr;
3727 vAddr.reserve(pto->vAddrToSend.size());
3728 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3730 // returns true if wasn't already contained in the set
3731 if (pto->setAddrKnown.insert(addr).second)
3733 vAddr.push_back(addr);
3734 // receiver rejects addr messages larger than 1000
3735 if (vAddr.size() >= 1000)
3737 pto->PushMessage("addr", vAddr);
3742 pto->vAddrToSend.clear();
3744 pto->PushMessage("addr", vAddr);
3749 // Message: inventory
3752 vector<CInv> vInvWait;
3754 LOCK(pto->cs_inventory);
3755 vInv.reserve(pto->vInventoryToSend.size());
3756 vInvWait.reserve(pto->vInventoryToSend.size());
3757 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3759 if (pto->setInventoryKnown.count(inv))
3762 // trickle out tx inv to protect privacy
3763 if (inv.type == MSG_TX && !fSendTrickle)
3765 // 1/4 of tx invs blast to all immediately
3766 static uint256 hashSalt;
3768 hashSalt = GetRandHash();
3769 uint256 hashRand = inv.hash ^ hashSalt;
3770 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3771 bool fTrickleWait = ((hashRand & 3) != 0);
3773 // always trickle our own transactions
3777 if (GetTransaction(inv.hash, wtx))
3779 fTrickleWait = true;
3784 vInvWait.push_back(inv);
3789 // returns true if wasn't already contained in the set
3790 if (pto->setInventoryKnown.insert(inv).second)
3792 vInv.push_back(inv);
3793 if (vInv.size() >= 1000)
3795 pto->PushMessage("inv", vInv);
3800 pto->vInventoryToSend = vInvWait;
3803 pto->PushMessage("inv", vInv);
3809 vector<CInv> vGetData;
3810 int64 nNow = GetTime() * 1000000;
3812 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3814 const CInv& inv = (*pto->mapAskFor.begin()).second;
3815 if (!AlreadyHave(txdb, inv))
3818 printf("sending getdata: %s\n", inv.ToString().c_str());
3819 vGetData.push_back(inv);
3820 if (vGetData.size() >= 1000)
3822 pto->PushMessage("getdata", vGetData);
3825 mapAlreadyAskedFor[inv] = nNow;
3827 pto->mapAskFor.erase(pto->mapAskFor.begin());
3829 if (!vGetData.empty())
3830 pto->PushMessage("getdata", vGetData);
3849 //////////////////////////////////////////////////////////////////////////////
3854 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3856 unsigned char* pdata = (unsigned char*)pbuffer;
3857 unsigned int blocks = 1 + ((len + 8) / 64);
3858 unsigned char* pend = pdata + 64 * blocks;
3859 memset(pdata + len, 0, 64 * blocks - len);
3861 unsigned int bits = len * 8;
3862 pend[-1] = (bits >> 0) & 0xff;
3863 pend[-2] = (bits >> 8) & 0xff;
3864 pend[-3] = (bits >> 16) & 0xff;
3865 pend[-4] = (bits >> 24) & 0xff;
3869 static const unsigned int pSHA256InitState[8] =
3870 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3872 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3875 unsigned char data[64];
3879 for (int i = 0; i < 16; i++)
3880 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3882 for (int i = 0; i < 8; i++)
3883 ctx.h[i] = ((uint32_t*)pinit)[i];
3885 SHA256_Update(&ctx, data, sizeof(data));
3886 for (int i = 0; i < 8; i++)
3887 ((uint32_t*)pstate)[i] = ctx.h[i];
3890 // Some explaining would be appreciated
3895 set<uint256> setDependsOn;
3899 COrphan(CTransaction* ptxIn)
3902 dPriority = dFeePerKb = 0;
3907 printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
3908 ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
3909 BOOST_FOREACH(uint256 hash, setDependsOn)
3910 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3915 uint64 nLastBlockTx = 0;
3916 uint64 nLastBlockSize = 0;
3917 int64 nLastCoinStakeSearchInterval = 0;
3919 // We want to sort transactions by priority and fee, so:
3920 typedef boost::tuple<double, double, CTransaction*> TxPriority;
3921 class TxPriorityCompare
3925 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
3926 bool operator()(const TxPriority& a, const TxPriority& b)
3930 if (a.get<1>() == b.get<1>())
3931 return a.get<0>() < b.get<0>();
3932 return a.get<1>() < b.get<1>();
3936 if (a.get<0>() == b.get<0>())
3937 return a.get<1>() < b.get<1>();
3938 return a.get<0>() < b.get<0>();
3944 // fProofOfStake: try (best effort) to make a proof-of-stake block
3945 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
3947 CReserveKey reservekey(pwallet);
3950 auto_ptr<CBlock> pblock(new CBlock());
3954 // Create coinbase tx
3956 txNew.vin.resize(1);
3957 txNew.vin[0].prevout.SetNull();
3958 txNew.vout.resize(1);
3959 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3961 // Add our coinbase tx as first transaction
3962 pblock->vtx.push_back(txNew);
3964 // Largest block you're willing to create:
3965 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
3966 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
3967 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
3969 // Special compatibility rule before 20 Aug: limit size to 500,000 bytes:
3970 if (GetAdjustedTime() < LOCKS_SWITCH_TIME)
3971 nBlockMaxSize = std::min(nBlockMaxSize, (unsigned int)(MAX_BLOCK_SIZE_GEN));
3973 // How much of the block should be dedicated to high-priority transactions,
3974 // included regardless of the fees they pay
3975 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
3976 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
3978 // Minimum block size you want to create; block will be filled with free transactions
3979 // until there are no more or the block reaches this size:
3980 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
3981 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
3983 // Fee-per-kilobyte amount considered the same as "free"
3984 // Be careful setting this: if you set it to zero then
3985 // a transaction spammer can cheaply fill blocks using
3986 // 1-satoshi-fee transactions. It should be set above the real
3987 // cost to you of processing a transaction.
3988 int64 nMinTxFee = MIN_TX_FEE;
3989 if (mapArgs.count("-mintxfee"))
3990 ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
3992 // ppcoin: if coinstake available add coinstake tx
3993 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
3994 CBlockIndex* pindexPrev = pindexBest;
3996 if (fProofOfStake) // attempt to find a coinstake
3998 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
3999 CTransaction txCoinStake;
4000 int64 nSearchTime = txCoinStake.nTime; // search to current time
4001 if (nSearchTime > nLastCoinStakeSearchTime)
4003 if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
4005 if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
4006 { // make sure coinstake would meet timestamp protocol
4007 // as it would be the same as the block timestamp
4008 pblock->vtx[0].vout[0].SetEmpty();
4009 pblock->vtx[0].nTime = txCoinStake.nTime;
4010 pblock->vtx.push_back(txCoinStake);
4013 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
4014 nLastCoinStakeSearchTime = nSearchTime;
4018 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
4020 // Collect memory pool transactions into the block
4023 LOCK2(cs_main, mempool.cs);
4024 CBlockIndex* pindexPrev = pindexBest;
4027 // Priority order to process transactions
4028 list<COrphan> vOrphan; // list memory doesn't move
4029 map<uint256, vector<COrphan*> > mapDependers;
4031 // This vector will be sorted into a priority queue:
4032 vector<TxPriority> vecPriority;
4033 vecPriority.reserve(mempool.mapTx.size());
4034 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
4036 CTransaction& tx = (*mi).second;
4037 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
4040 COrphan* porphan = NULL;
4041 double dPriority = 0;
4043 bool fMissingInputs = false;
4044 BOOST_FOREACH(const CTxIn& txin, tx.vin)
4046 // Read prev transaction
4047 CTransaction txPrev;
4049 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
4051 // This should never happen; all transactions in the memory
4052 // pool should connect to either transactions in the chain
4053 // or other transactions in the memory pool.
4054 if (!mempool.mapTx.count(txin.prevout.hash))
4056 printf("ERROR: mempool transaction missing input\n");
4057 if (fDebug) assert("mempool transaction missing input" == 0);
4058 fMissingInputs = true;
4064 // Has to wait for dependencies
4067 // Use list for automatic deletion
4068 vOrphan.push_back(COrphan(&tx));
4069 porphan = &vOrphan.back();
4071 mapDependers[txin.prevout.hash].push_back(porphan);
4072 porphan->setDependsOn.insert(txin.prevout.hash);
4073 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
4076 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
4077 nTotalIn += nValueIn;
4079 int nConf = txindex.GetDepthInMainChain();
4080 dPriority += (double)nValueIn * nConf;
4082 if (fMissingInputs) continue;
4084 // Priority is sum(valuein * age) / txsize
4085 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4086 dPriority /= nTxSize;
4088 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
4089 // client code rounds up the size to the nearest 1K. That's good, because it gives an
4090 // incentive to create smaller transactions.
4091 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
4095 porphan->dPriority = dPriority;
4096 porphan->dFeePerKb = dFeePerKb;
4099 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
4102 // Collect transactions into block
4103 map<uint256, CTxIndex> mapTestPool;
4104 uint64 nBlockSize = 1000;
4105 uint64 nBlockTx = 0;
4106 int nBlockSigOps = 100;
4107 bool fSortedByFee = (nBlockPrioritySize <= 0);
4109 TxPriorityCompare comparer(fSortedByFee);
4110 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4112 while (!vecPriority.empty())
4114 // Take highest priority transaction off the priority queue:
4115 double dPriority = vecPriority.front().get<0>();
4116 double dFeePerKb = vecPriority.front().get<1>();
4117 CTransaction& tx = *(vecPriority.front().get<2>());
4119 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
4120 vecPriority.pop_back();
4123 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4124 if (nBlockSize + nTxSize >= nBlockMaxSize)
4127 // Legacy limits on sigOps:
4128 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
4129 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4133 if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
4136 // ppcoin: simplify transaction fee - allow free = false
4137 int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
4139 // Skip free transactions if we're past the minimum block size:
4140 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
4143 // Prioritize by fee once past the priority size or we run out of high-priority
4145 if (!fSortedByFee &&
4146 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
4148 fSortedByFee = true;
4149 comparer = TxPriorityCompare(fSortedByFee);
4150 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4153 // Connecting shouldn't fail due to dependency on other memory pool transactions
4154 // because we're already processing them in order of dependency
4155 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
4156 MapPrevTx mapInputs;
4158 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
4161 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
4162 if (nTxFees < nMinFee)
4165 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
4166 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4169 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
4171 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
4172 swap(mapTestPool, mapTestPoolTmp);
4175 pblock->vtx.push_back(tx);
4176 nBlockSize += nTxSize;
4178 nBlockSigOps += nTxSigOps;
4181 if (fDebug && GetBoolArg("-printpriority"))
4183 printf("priority %.1f feeperkb %.1f txid %s\n",
4184 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
4187 // Add transactions that depend on this one to the priority queue
4188 uint256 hash = tx.GetHash();
4189 if (mapDependers.count(hash))
4191 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
4193 if (!porphan->setDependsOn.empty())
4195 porphan->setDependsOn.erase(hash);
4196 if (porphan->setDependsOn.empty())
4198 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
4199 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
4206 nLastBlockTx = nBlockTx;
4207 nLastBlockSize = nBlockSize;
4209 if (fDebug && GetBoolArg("-printpriority"))
4210 printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
4212 if (pblock->IsProofOfWork())
4213 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
4216 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
4217 if (pblock->IsProofOfStake())
4218 pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
4219 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
4220 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4221 if (pblock->IsProofOfWork())
4222 pblock->UpdateTime(pindexPrev);
4226 return pblock.release();
4230 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
4232 // Update nExtraNonce
4233 static uint256 hashPrevBlock;
4234 if (hashPrevBlock != pblock->hashPrevBlock)
4237 hashPrevBlock = pblock->hashPrevBlock;
4240 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4241 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4242 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
4244 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
4248 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
4251 // Pre-build hash buffers
4258 uint256 hashPrevBlock;
4259 uint256 hashMerkleRoot;
4262 unsigned int nNonce;
4265 unsigned char pchPadding0[64];
4267 unsigned char pchPadding1[64];
4270 memset(&tmp, 0, sizeof(tmp));
4272 tmp.block.nVersion = pblock->nVersion;
4273 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
4274 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
4275 tmp.block.nTime = pblock->nTime;
4276 tmp.block.nBits = pblock->nBits;
4277 tmp.block.nNonce = pblock->nNonce;
4279 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
4280 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
4282 // Byte swap all the input buffer
4283 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
4284 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
4286 // Precalc the first half of the first hash, which stays constant
4287 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
4289 memcpy(pdata, &tmp.block, 128);
4290 memcpy(phash1, &tmp.hash1, 64);
4294 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
4296 uint256 hash = pblock->GetHash();
4297 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4299 if (hash > hashTarget && pblock->IsProofOfWork())
4300 return error("BitcoinMiner : proof-of-work not meeting target");
4303 printf("BitcoinMiner:\n");
4304 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
4306 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
4311 if (pblock->hashPrevBlock != hashBestChain)
4312 return error("BitcoinMiner : generated block is stale");
4314 // Remove key from key pool
4315 reservekey.KeepKey();
4317 // Track how many getdata requests this block gets
4319 LOCK(wallet.cs_wallet);
4320 wallet.mapRequestCount[pblock->GetHash()] = 0;
4323 // Process this block the same as if we had received it from another node
4324 if (!ProcessBlock(NULL, pblock))
4325 return error("BitcoinMiner : ProcessBlock, block not accepted");
4331 void static ThreadBitcoinMiner(void* parg);
4333 static bool fGenerateBitcoins = false;
4334 static bool fLimitProcessors = false;
4335 static int nLimitProcessors = -1;
4337 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake)
4339 void *scratchbuf = scrypt_buffer_alloc();
4341 printf("CPUMiner started for proof-of-%s\n", fProofOfStake? "stake" : "work");
4342 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4344 // Make this thread recognisable as the mining thread
4345 RenameThread("bitcoin-miner");
4347 // Each thread has its own key and counter
4348 CReserveKey reservekey(pwallet);
4349 unsigned int nExtraNonce = 0;
4351 while (fGenerateBitcoins || fProofOfStake)
4355 while (vNodes.empty() || IsInitialBlockDownload())
4360 if ((!fGenerateBitcoins) && !fProofOfStake)
4364 while (pwallet->IsLocked())
4366 strMintWarning = strMintMessage;
4369 strMintWarning = "";
4374 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
4375 CBlockIndex* pindexPrev = pindexBest;
4377 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
4380 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
4384 // ppcoin: if proof-of-stake block found then process block
4385 if (pblock->IsProofOfStake())
4387 if (!pblock->SignBlock(*pwalletMain))
4389 strMintWarning = strMintMessage;
4392 strMintWarning = "";
4393 printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
4394 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4395 CheckWork(pblock.get(), *pwalletMain, reservekey);
4396 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4402 printf("Running BitcoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
4403 ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
4406 // Pre-build hash buffers
4408 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
4409 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
4410 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
4412 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
4414 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
4415 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
4421 int64 nStart = GetTime();
4422 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4424 unsigned int max_nonce = 0xffff0000;
4425 block_header res_header;
4430 unsigned int nHashesDone = 0;
4431 unsigned int nNonceFound;
4433 nNonceFound = scanhash_scrypt(
4434 (block_header *)&pblock->nVersion,
4442 // Check if something found
4443 if (nNonceFound != (unsigned int) -1)
4445 if (result <= hashTarget)
4448 pblock->nNonce = nNonceFound;
4449 assert(result == pblock->GetHash());
4450 if (!pblock->SignBlock(*pwalletMain))
4452 // strMintWarning = strMintMessage;
4455 strMintWarning = "";
4457 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4458 CheckWork(pblock.get(), *pwalletMain, reservekey);
4459 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4465 static int64 nHashCounter;
4466 if (nHPSTimerStart == 0)
4468 nHPSTimerStart = GetTimeMillis();
4472 nHashCounter += nHashesDone;
4473 if (GetTimeMillis() - nHPSTimerStart > 4000)
4475 static CCriticalSection cs;
4478 if (GetTimeMillis() - nHPSTimerStart > 4000)
4480 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
4481 nHPSTimerStart = GetTimeMillis();
4483 static int64 nLogTime;
4484 if (GetTime() - nLogTime > 30 * 60)
4486 nLogTime = GetTime();
4487 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
4493 // Check for stop or if block needs to be rebuilt
4496 if (!fGenerateBitcoins)
4498 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4502 if (nBlockNonce >= 0xffff0000)
4504 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4506 if (pindexPrev != pindexBest)
4509 // Update nTime every few seconds
4510 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
4511 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4512 pblock->UpdateTime(pindexPrev);
4513 nBlockTime = ByteReverse(pblock->nTime);
4515 if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
4516 break; // need to update coinbase timestamp
4520 scrypt_buffer_free(scratchbuf);
4523 void static ThreadBitcoinMiner(void* parg)
4525 CWallet* pwallet = (CWallet*)parg;
4528 vnThreadsRunning[THREAD_MINER]++;
4529 BitcoinMiner(pwallet, false);
4530 vnThreadsRunning[THREAD_MINER]--;
4532 catch (std::exception& e) {
4533 vnThreadsRunning[THREAD_MINER]--;
4534 PrintException(&e, "ThreadBitcoinMiner()");
4536 vnThreadsRunning[THREAD_MINER]--;
4537 PrintException(NULL, "ThreadBitcoinMiner()");
4540 if (vnThreadsRunning[THREAD_MINER] == 0)
4542 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4546 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4548 fGenerateBitcoins = fGenerate;
4549 nLimitProcessors = GetArg("-genproclimit", -1);
4550 if (nLimitProcessors == 0)
4551 fGenerateBitcoins = false;
4552 fLimitProcessors = (nLimitProcessors != -1);
4556 int nProcessors = boost::thread::hardware_concurrency();
4557 printf("%d processors\n", nProcessors);
4558 if (nProcessors < 1)
4560 if (fLimitProcessors && nProcessors > nLimitProcessors)
4561 nProcessors = nLimitProcessors;
4562 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4563 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4564 for (int i = 0; i < nAddThreads; i++)
4566 if (!NewThread(ThreadBitcoinMiner, pwallet))
4567 printf("Error: NewThread(ThreadBitcoinMiner) failed\n");