1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2013 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
11 #include "ui_interface.h"
13 #include "scrypt_mine.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
19 using namespace boost;
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
31 unsigned int nTransactionsUpdated = 0;
33 map<uint256, CBlockIndex*> mapBlockIndex;
34 set<pair<COutPoint, unsigned int> > setStakeSeen;
35 uint256 hashGenesisBlock = hashGenesisBlockOfficial;
36 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20);
37 static CBigNum bnInitialHashTarget(~uint256(0) >> 20);
38 unsigned int nStakeMinAge = STAKE_MIN_AGE;
39 int nCoinbaseMaturity = COINBASE_MATURITY_PPC;
40 CBlockIndex* pindexGenesisBlock = NULL;
42 CBigNum bnBestChainTrust = 0;
43 CBigNum bnBestInvalidTrust = 0;
44 uint256 hashBestChain = 0;
45 CBlockIndex* pindexBest = NULL;
46 int64 nTimeBestReceived = 0;
48 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
50 map<uint256, CBlock*> mapOrphanBlocks;
51 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
52 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
53 map<uint256, uint256> mapProofOfStake;
55 map<uint256, CDataStream*> mapOrphanTransactions;
56 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
58 // Constant stuff for coinbase transactions we create:
59 CScript COINBASE_FLAGS;
61 const string strMessageMagic = "NovaCoin Signed Message:\n";
67 int64 nTransactionFee = MIN_TX_FEE;
71 //////////////////////////////////////////////////////////////////////////////
73 // dispatching functions
76 // These functions dispatch to one or all registered wallets
79 void RegisterWallet(CWallet* pwalletIn)
82 LOCK(cs_setpwalletRegistered);
83 setpwalletRegistered.insert(pwalletIn);
87 void UnregisterWallet(CWallet* pwalletIn)
90 LOCK(cs_setpwalletRegistered);
91 setpwalletRegistered.erase(pwalletIn);
95 // check whether the passed transaction is from us
96 bool static IsFromMe(CTransaction& tx)
98 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
99 if (pwallet->IsFromMe(tx))
104 // get the wallet transaction with the given hash (if it exists)
105 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
107 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
108 if (pwallet->GetTransaction(hashTx,wtx))
113 // erases transaction with the given hash from all wallets
114 void static EraseFromWallets(uint256 hash)
116 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
117 pwallet->EraseFromWallet(hash);
120 // make sure all wallets know about the given transaction, in the given block
121 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true)
125 // ppcoin: wallets need to refund inputs when disconnecting coinstake
126 if (tx.IsCoinStake())
128 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
129 if (pwallet->IsFromMe(tx))
130 pwallet->DisableTransaction(tx);
135 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
136 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
139 // notify wallets about a new best chain
140 void static SetBestChain(const CBlockLocator& loc)
142 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
143 pwallet->SetBestChain(loc);
146 // notify wallets about an updated transaction
147 void static UpdatedTransaction(const uint256& hashTx)
149 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
150 pwallet->UpdatedTransaction(hashTx);
154 void static PrintWallets(const CBlock& block)
156 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
157 pwallet->PrintWallet(block);
160 // notify wallets about an incoming inventory (for request counts)
161 void static Inventory(const uint256& hash)
163 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
164 pwallet->Inventory(hash);
167 // ask wallets to resend their transactions
168 void ResendWalletTransactions()
170 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
171 pwallet->ResendWalletTransactions();
180 //////////////////////////////////////////////////////////////////////////////
182 // mapOrphanTransactions
185 bool AddOrphanTx(const CDataStream& vMsg)
188 CDataStream(vMsg) >> tx;
189 uint256 hash = tx.GetHash();
190 if (mapOrphanTransactions.count(hash))
193 CDataStream* pvMsg = new CDataStream(vMsg);
195 // Ignore big transactions, to avoid a
196 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
197 // large transaction with a missing parent then we assume
198 // it will rebroadcast it later, after the parent transaction(s)
199 // have been mined or received.
200 // 10,000 orphans, each of which is at most 5,000 bytes big is
201 // at most 500 megabytes of orphans:
202 if (pvMsg->size() > 5000)
204 printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
209 mapOrphanTransactions[hash] = pvMsg;
210 BOOST_FOREACH(const CTxIn& txin, tx.vin)
211 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
213 printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
214 mapOrphanTransactions.size());
218 void static EraseOrphanTx(uint256 hash)
220 if (!mapOrphanTransactions.count(hash))
222 const CDataStream* pvMsg = mapOrphanTransactions[hash];
224 CDataStream(*pvMsg) >> tx;
225 BOOST_FOREACH(const CTxIn& txin, tx.vin)
227 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
228 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
229 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
232 mapOrphanTransactions.erase(hash);
235 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
237 unsigned int nEvicted = 0;
238 while (mapOrphanTransactions.size() > nMaxOrphans)
240 // Evict a random orphan:
241 uint256 randomhash = GetRandHash();
242 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
243 if (it == mapOrphanTransactions.end())
244 it = mapOrphanTransactions.begin();
245 EraseOrphanTx(it->first);
257 //////////////////////////////////////////////////////////////////////////////
259 // CTransaction and CTxIndex
262 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
265 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
267 if (!ReadFromDisk(txindexRet.pos))
269 if (prevout.n >= vout.size())
277 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
280 return ReadFromDisk(txdb, prevout, txindex);
283 bool CTransaction::ReadFromDisk(COutPoint prevout)
287 return ReadFromDisk(txdb, prevout, txindex);
290 bool CTransaction::IsStandard() const
292 BOOST_FOREACH(const CTxIn& txin, vin)
294 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
295 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
296 // ~65-byte public keys, plus a few script ops.
297 if (txin.scriptSig.size() > 500)
299 if (!txin.scriptSig.IsPushOnly())
302 BOOST_FOREACH(const CTxOut& txout, vout)
303 if (!::IsStandard(txout.scriptPubKey))
309 // Check transaction inputs, and make sure any
310 // pay-to-script-hash transactions are evaluating IsStandard scripts
312 // Why bother? To avoid denial-of-service attacks; an attacker
313 // can submit a standard HASH... OP_EQUAL transaction,
314 // which will get accepted into blocks. The redemption
315 // script can be anything; an attacker could use a very
316 // expensive-to-check-upon-redemption script like:
317 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
319 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
322 return true; // Coinbases don't use vin normally
324 for (unsigned int i = 0; i < vin.size(); i++)
326 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
328 vector<vector<unsigned char> > vSolutions;
329 txnouttype whichType;
330 // get the scriptPubKey corresponding to this input:
331 const CScript& prevScript = prev.scriptPubKey;
332 if (!Solver(prevScript, whichType, vSolutions))
334 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
335 if (nArgsExpected < 0)
338 // Transactions with extra stuff in their scriptSigs are
339 // non-standard. Note that this EvalScript() call will
340 // be quick, because if there are any operations
341 // beside "push data" in the scriptSig the
342 // IsStandard() call returns false
343 vector<vector<unsigned char> > stack;
344 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
347 if (whichType == TX_SCRIPTHASH)
351 CScript subscript(stack.back().begin(), stack.back().end());
352 vector<vector<unsigned char> > vSolutions2;
353 txnouttype whichType2;
354 if (!Solver(subscript, whichType2, vSolutions2))
356 if (whichType2 == TX_SCRIPTHASH)
360 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
363 nArgsExpected += tmpExpected;
366 if (stack.size() != (unsigned int)nArgsExpected)
374 CTransaction::GetLegacySigOpCount() const
376 unsigned int nSigOps = 0;
377 BOOST_FOREACH(const CTxIn& txin, vin)
379 nSigOps += txin.scriptSig.GetSigOpCount(false);
381 BOOST_FOREACH(const CTxOut& txout, vout)
383 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
389 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
401 // Load the block this tx is in
403 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
405 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
410 // Update the tx's hashBlock
411 hashBlock = pblock->GetHash();
413 // Locate the transaction
414 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
415 if (pblock->vtx[nIndex] == *(CTransaction*)this)
417 if (nIndex == (int)pblock->vtx.size())
419 vMerkleBranch.clear();
421 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
425 // Fill in merkle branch
426 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
429 // Is the tx in a block that's in the main chain
430 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
431 if (mi == mapBlockIndex.end())
433 CBlockIndex* pindex = (*mi).second;
434 if (!pindex || !pindex->IsInMainChain())
437 return pindexBest->nHeight - pindex->nHeight + 1;
446 bool CTransaction::CheckTransaction() const
448 // Basic checks that don't depend on any context
450 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
452 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
454 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
455 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
457 // Check for negative or overflow output values
459 for (int i = 0; i < vout.size(); i++)
461 const CTxOut& txout = vout[i];
462 if (txout.IsEmpty() && (!IsCoinBase()) && (!IsCoinStake()))
463 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
464 // ppcoin: enforce minimum output amount
465 if ((!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
466 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
467 if (txout.nValue > MAX_MONEY)
468 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
469 nValueOut += txout.nValue;
470 if (!MoneyRange(nValueOut))
471 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
474 // Check for duplicate inputs
475 set<COutPoint> vInOutPoints;
476 BOOST_FOREACH(const CTxIn& txin, vin)
478 if (vInOutPoints.count(txin.prevout))
480 vInOutPoints.insert(txin.prevout);
485 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
486 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
490 BOOST_FOREACH(const CTxIn& txin, vin)
491 if (txin.prevout.IsNull())
492 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
498 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
499 bool* pfMissingInputs)
502 *pfMissingInputs = false;
504 if (!tx.CheckTransaction())
505 return error("CTxMemPool::accept() : CheckTransaction failed");
507 // Coinbase is only valid in a block, not as a loose transaction
509 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
510 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
511 if (tx.IsCoinStake())
512 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
514 // To help v0.1.5 clients who would see it as a negative number
515 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
516 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
518 // Rather not work on nonstandard transactions (unless -testnet)
519 if (!fTestNet && !tx.IsStandard())
520 return error("CTxMemPool::accept() : nonstandard transaction type");
522 // Do we already have it?
523 uint256 hash = tx.GetHash();
526 if (mapTx.count(hash))
530 if (txdb.ContainsTx(hash))
533 // Check for conflicts with in-memory transactions
534 CTransaction* ptxOld = NULL;
535 for (unsigned int i = 0; i < tx.vin.size(); i++)
537 COutPoint outpoint = tx.vin[i].prevout;
538 if (mapNextTx.count(outpoint))
540 // Disable replacement feature for now
543 // Allow replacing with a newer version of the same transaction
546 ptxOld = mapNextTx[outpoint].ptx;
547 if (ptxOld->IsFinal())
549 if (!tx.IsNewerThan(*ptxOld))
551 for (unsigned int i = 0; i < tx.vin.size(); i++)
553 COutPoint outpoint = tx.vin[i].prevout;
554 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
564 map<uint256, CTxIndex> mapUnused;
565 bool fInvalid = false;
566 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
569 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
571 *pfMissingInputs = true;
572 return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
575 // Check for non-standard pay-to-script-hash in inputs
576 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
577 return error("CTxMemPool::accept() : nonstandard transaction input");
579 // Note: if you modify this code to accept non-standard transactions, then
580 // you should add code here to check that the transaction does a
581 // reasonable number of ECDSA signature verifications.
583 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
584 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
586 // Don't accept it if it can't get into a block
587 if (nFees < tx.GetMinFee(1000, false, GMF_RELAY))
588 return error("CTxMemPool::accept() : not enough fees");
590 // Continuously rate-limit free transactions
591 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
592 // be annoying or make other's transactions take longer to confirm.
593 if (nFees < MIN_RELAY_TX_FEE)
595 static CCriticalSection cs;
596 static double dFreeCount;
597 static int64 nLastTime;
598 int64 nNow = GetTime();
602 // Use an exponentially decaying ~10-minute window:
603 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
605 // -limitfreerelay unit is thousand-bytes-per-minute
606 // At default rate it would take over a month to fill 1GB
607 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
608 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
610 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
615 // Check against previous transactions
616 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
617 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
619 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
623 // Store transaction in memory
628 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
634 ///// are we sure this is ok when loading transactions or restoring block txes
635 // If updated, erase old tx from wallet
637 EraseFromWallets(ptxOld->GetHash());
639 printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str());
643 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
645 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
648 bool CTxMemPool::addUnchecked(CTransaction &tx)
650 printf("addUnchecked(): size %lu\n", mapTx.size());
651 // Add to memory pool without checking anything. Don't call this directly,
652 // call CTxMemPool::accept to properly check the transaction first.
655 uint256 hash = tx.GetHash();
657 for (unsigned int i = 0; i < tx.vin.size(); i++)
658 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
659 nTransactionsUpdated++;
665 bool CTxMemPool::remove(CTransaction &tx)
667 // Remove transaction from memory pool
670 uint256 hash = tx.GetHash();
671 if (mapTx.count(hash))
673 BOOST_FOREACH(const CTxIn& txin, tx.vin)
674 mapNextTx.erase(txin.prevout);
676 nTransactionsUpdated++;
687 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
689 if (hashBlock == 0 || nIndex == -1)
692 // Find the block it claims to be in
693 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
694 if (mi == mapBlockIndex.end())
696 CBlockIndex* pindex = (*mi).second;
697 if (!pindex || !pindex->IsInMainChain())
700 // Make sure the merkle branch connects to this block
701 if (!fMerkleVerified)
703 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
705 fMerkleVerified = true;
709 return pindexBest->nHeight - pindex->nHeight + 1;
713 int CMerkleTx::GetBlocksToMaturity() const
715 if (!(IsCoinBase() || IsCoinStake()))
717 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
721 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
725 if (!IsInMainChain() && !ClientConnectInputs())
727 return CTransaction::AcceptToMemoryPool(txdb, false);
731 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
735 bool CMerkleTx::AcceptToMemoryPool()
738 return AcceptToMemoryPool(txdb);
743 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
748 // Add previous supporting transactions first
749 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
751 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
753 uint256 hash = tx.GetHash();
754 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
755 tx.AcceptToMemoryPool(txdb, fCheckInputs);
758 return AcceptToMemoryPool(txdb, fCheckInputs);
763 bool CWalletTx::AcceptWalletTransaction()
766 return AcceptWalletTransaction(txdb);
769 int CTxIndex::GetDepthInMainChain() const
773 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
775 // Find the block in the index
776 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
777 if (mi == mapBlockIndex.end())
779 CBlockIndex* pindex = (*mi).second;
780 if (!pindex || !pindex->IsInMainChain())
782 return 1 + nBestHeight - pindex->nHeight;
794 //////////////////////////////////////////////////////////////////////////////
796 // CBlock and CBlockIndex
799 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
801 if (!fReadTransactions)
803 *this = pindex->GetBlockHeader();
806 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
808 if (GetHash() != pindex->GetBlockHash())
809 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
813 uint256 static GetOrphanRoot(const CBlock* pblock)
815 // Work back to the first block in the orphan chain
816 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
817 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
818 return pblock->GetHash();
821 // ppcoin: find block wanted by given orphan block
822 uint256 WantedByOrphan(const CBlock* pblockOrphan)
824 // Work back to the first block in the orphan chain
825 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
826 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
827 return pblockOrphan->hashPrevBlock;
830 int64 GetProofOfWorkReward(unsigned int nBits)
832 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
834 bnTarget.SetCompact(nBits);
835 CBigNum bnTargetLimit = bnProofOfWorkLimit;
836 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
838 // ppcoin: subsidy is cut in half every 64x multiply of difficulty
839 // A reasonably continuous curve is used to avoid shock to market
840 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
842 // Human readable form:
844 // nSubsidy = 100 / (diff ^ 1/6)
845 CBigNum bnLowerBound = CENT;
846 CBigNum bnUpperBound = bnSubsidyLimit;
847 while (bnLowerBound + CENT <= bnUpperBound)
849 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
850 if (fDebug && GetBoolArg("-printcreation"))
851 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
852 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
853 bnUpperBound = bnMidValue;
855 bnLowerBound = bnMidValue;
858 int64 nSubsidy = bnUpperBound.getuint64();
859 nSubsidy = (nSubsidy / CENT) * CENT;
860 if (fDebug && GetBoolArg("-printcreation"))
861 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
863 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
866 // ppcoin: miner's coin stake is rewarded based on coin age spent (coin-days)
867 int64 GetProofOfStakeReward(int64 nCoinAge)
869 static int64 nRewardCoinYear = 5 * CENT; // creation amount per coin-year
870 int64 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
871 if (fDebug && GetBoolArg("-printcreation"))
872 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nCoinAge);
876 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
877 static const int64 nTargetSpacingWorkMax = 12 * STAKE_TARGET_SPACING; // 2-hour
880 // minimum amount of work that could possibly be required nTime after
881 // minimum work required was nBase
883 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
886 bnResult.SetCompact(nBase);
888 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
890 // Maximum 200% adjustment per day...
892 nTime -= 24 * 60 * 60;
894 if (bnResult > bnProofOfWorkLimit)
895 bnResult = bnProofOfWorkLimit;
896 return bnResult.GetCompact();
899 // ppcoin: find last block index up to pindex
900 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
902 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
903 pindex = pindex->pprev;
907 unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
909 if (pindexLast == NULL)
910 return bnProofOfWorkLimit.GetCompact(); // genesis block
912 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
913 if (pindexPrev->pprev == NULL)
914 return bnInitialHashTarget.GetCompact(); // first block
915 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
916 if (pindexPrevPrev->pprev == NULL)
917 return bnInitialHashTarget.GetCompact(); // second block
919 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
921 // ppcoin: target change every block
922 // ppcoin: retarget with exponential moving toward target spacing
924 bnNew.SetCompact(pindexPrev->nBits);
925 int64 nTargetSpacing = fProofOfStake? STAKE_TARGET_SPACING : min(nTargetSpacingWorkMax, (int64) STAKE_TARGET_SPACING * (1 + pindexLast->nHeight - pindexPrev->nHeight));
926 int64 nInterval = nTargetTimespan / nTargetSpacing;
927 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
928 bnNew /= ((nInterval + 1) * nTargetSpacing);
930 if (bnNew > bnProofOfWorkLimit)
931 bnNew = bnProofOfWorkLimit;
933 return bnNew.GetCompact();
936 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
939 bnTarget.SetCompact(nBits);
942 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
943 return error("CheckProofOfWork() : nBits below minimum work");
945 // Check proof of work matches claimed amount
946 if (hash > bnTarget.getuint256())
947 return error("CheckProofOfWork() : hash doesn't match nBits");
952 // Return maximum amount of blocks that other nodes claim to have
953 int GetNumBlocksOfPeers()
955 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
958 bool IsInitialBlockDownload()
960 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
962 static int64 nLastUpdate;
963 static CBlockIndex* pindexLastBest;
964 if (pindexBest != pindexLastBest)
966 pindexLastBest = pindexBest;
967 nLastUpdate = GetTime();
969 return (GetTime() - nLastUpdate < 10 &&
970 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
973 void static InvalidChainFound(CBlockIndex* pindexNew)
975 if (pindexNew->bnChainTrust > bnBestInvalidTrust)
977 bnBestInvalidTrust = pindexNew->bnChainTrust;
978 CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust);
981 printf("InvalidChainFound: invalid block=%s height=%d trust=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, CBigNum(pindexNew->bnChainTrust).ToString().c_str());
982 printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(bnBestChainTrust).ToString().c_str());
983 // ppcoin: should not enter safe mode for longer invalid chain
986 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
988 nTime = max(GetBlockTime(), GetAdjustedTime());
1001 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1003 // Relinquish previous transactions' spent pointers
1006 BOOST_FOREACH(const CTxIn& txin, vin)
1008 COutPoint prevout = txin.prevout;
1010 // Get prev txindex from disk
1012 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1013 return error("DisconnectInputs() : ReadTxIndex failed");
1015 if (prevout.n >= txindex.vSpent.size())
1016 return error("DisconnectInputs() : prevout.n out of range");
1018 // Mark outpoint as not spent
1019 txindex.vSpent[prevout.n].SetNull();
1022 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1023 return error("DisconnectInputs() : UpdateTxIndex failed");
1027 // Remove transaction from index
1028 // This can fail if a duplicate of this transaction was in a chain that got
1029 // reorganized away. This is only possible if this transaction was completely
1030 // spent, so erasing it would be a no-op anway.
1031 txdb.EraseTxIndex(*this);
1037 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1038 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1040 // FetchInputs can return false either because we just haven't seen some inputs
1041 // (in which case the transaction should be stored as an orphan)
1042 // or because the transaction is malformed (in which case the transaction should
1043 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1047 return true; // Coinbase transactions have no inputs to fetch.
1049 for (unsigned int i = 0; i < vin.size(); i++)
1051 COutPoint prevout = vin[i].prevout;
1052 if (inputsRet.count(prevout.hash))
1053 continue; // Got it already
1056 CTxIndex& txindex = inputsRet[prevout.hash].first;
1058 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1060 // Get txindex from current proposed changes
1061 txindex = mapTestPool.find(prevout.hash)->second;
1065 // Read txindex from txdb
1066 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1068 if (!fFound && (fBlock || fMiner))
1069 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());
1072 CTransaction& txPrev = inputsRet[prevout.hash].second;
1073 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1075 // Get prev tx from single transactions in memory
1078 if (!mempool.exists(prevout.hash))
1079 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());
1080 txPrev = mempool.lookup(prevout.hash);
1083 txindex.vSpent.resize(txPrev.vout.size());
1087 // Get prev tx from disk
1088 if (!txPrev.ReadFromDisk(txindex.pos))
1089 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1093 // Make sure all prevout.n's are valid:
1094 for (unsigned int i = 0; i < vin.size(); i++)
1096 const COutPoint prevout = vin[i].prevout;
1097 assert(inputsRet.count(prevout.hash) != 0);
1098 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1099 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1100 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1102 // Revisit this if/when transaction replacement is implemented and allows
1105 return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
1112 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1114 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1115 if (mi == inputs.end())
1116 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1118 const CTransaction& txPrev = (mi->second).second;
1119 if (input.prevout.n >= txPrev.vout.size())
1120 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1122 return txPrev.vout[input.prevout.n];
1125 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1131 for (unsigned int i = 0; i < vin.size(); i++)
1133 nResult += GetOutputFor(vin[i], inputs).nValue;
1139 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1144 unsigned int nSigOps = 0;
1145 for (unsigned int i = 0; i < vin.size(); i++)
1147 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1148 if (prevout.scriptPubKey.IsPayToScriptHash())
1149 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1154 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1155 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1156 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1158 // Take over previous transactions' spent pointers
1159 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1160 // fMiner is true when called from the internal bitcoin miner
1161 // ... both are false when called from CTransaction::AcceptToMemoryPool
1166 for (unsigned int i = 0; i < vin.size(); i++)
1168 COutPoint prevout = vin[i].prevout;
1169 assert(inputs.count(prevout.hash) > 0);
1170 CTxIndex& txindex = inputs[prevout.hash].first;
1171 CTransaction& txPrev = inputs[prevout.hash].second;
1173 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1174 return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
1176 // If prev is coinbase/coinstake, check that it's matured
1177 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1178 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1179 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1180 return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight);
1182 // ppcoin: check transaction timestamp
1183 if (txPrev.nTime > nTime)
1184 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1186 // Check for negative or overflow input values
1187 nValueIn += txPrev.vout[prevout.n].nValue;
1188 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1189 return DoS(100, error("ConnectInputs() : txin values out of range"));
1192 // The first loop above does all the inexpensive checks.
1193 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1194 // Helps prevent CPU exhaustion attacks.
1195 for (unsigned int i = 0; i < vin.size(); i++)
1197 COutPoint prevout = vin[i].prevout;
1198 assert(inputs.count(prevout.hash) > 0);
1199 CTxIndex& txindex = inputs[prevout.hash].first;
1200 CTransaction& txPrev = inputs[prevout.hash].second;
1202 // Check for conflicts (double-spend)
1203 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1204 // for an attacker to attempt to split the network.
1205 if (!txindex.vSpent[prevout.n].IsNull())
1206 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());
1208 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1209 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1210 // still computed and checked, and any change will be caught at the next checkpoint.
1211 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1214 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1216 // only during transition phase for P2SH: do not invoke anti-DoS code for
1217 // potentially old clients relaying bad P2SH transactions
1218 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1219 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1221 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1225 // Mark outpoints as spent
1226 txindex.vSpent[prevout.n] = posThisTx;
1229 if (fBlock || fMiner)
1231 mapTestPool[prevout.hash] = txindex;
1237 // ppcoin: coin stake tx earns reward instead of paying fee
1239 if (!GetCoinAge(txdb, nCoinAge))
1240 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1241 int64 nStakeReward = GetValueOut() - nValueIn;
1242 if (nStakeReward > GetProofOfStakeReward(nCoinAge) - GetMinFee() + MIN_TX_FEE)
1243 return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
1247 if (nValueIn < GetValueOut())
1248 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1250 // Tally transaction fees
1251 int64 nTxFee = nValueIn - GetValueOut();
1253 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1254 // ppcoin: enforce transaction fees for every block
1255 if (nTxFee < GetMinFee())
1256 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;
1258 if (!MoneyRange(nFees))
1259 return DoS(100, error("ConnectInputs() : nFees out of range"));
1267 bool CTransaction::ClientConnectInputs()
1272 // Take over previous transactions' spent pointers
1276 for (unsigned int i = 0; i < vin.size(); i++)
1278 // Get prev tx from single transactions in memory
1279 COutPoint prevout = vin[i].prevout;
1280 if (!mempool.exists(prevout.hash))
1282 CTransaction& txPrev = mempool.lookup(prevout.hash);
1284 if (prevout.n >= txPrev.vout.size())
1288 if (!VerifySignature(txPrev, *this, i, true, 0))
1289 return error("ConnectInputs() : VerifySignature failed");
1291 ///// this is redundant with the mempool.mapNextTx stuff,
1292 ///// not sure which I want to get rid of
1293 ///// this has to go away now that posNext is gone
1294 // // Check for conflicts
1295 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1296 // return error("ConnectInputs() : prev tx already used");
1298 // // Flag outpoints as used
1299 // txPrev.vout[prevout.n].posNext = posThisTx;
1301 nValueIn += txPrev.vout[prevout.n].nValue;
1303 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1304 return error("ClientConnectInputs() : txin values out of range");
1306 if (GetValueOut() > nValueIn)
1316 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1318 // Disconnect in reverse order
1319 for (int i = vtx.size()-1; i >= 0; i--)
1320 if (!vtx[i].DisconnectInputs(txdb))
1323 // Update block index on disk without changing it in memory.
1324 // The memory index structure will be changed after the db commits.
1327 CDiskBlockIndex blockindexPrev(pindex->pprev);
1328 blockindexPrev.hashNext = 0;
1329 if (!txdb.WriteBlockIndex(blockindexPrev))
1330 return error("DisconnectBlock() : WriteBlockIndex failed");
1333 // ppcoin: clean up wallet after disconnecting coinstake
1334 BOOST_FOREACH(CTransaction& tx, vtx)
1335 SyncWithWallets(tx, this, false, false);
1340 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1342 // Check it again in case a previous version let a bad block in
1346 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1347 // unless those are already completely spent.
1348 // If such overwrites are allowed, coinbases and transactions depending upon those
1349 // can be duplicated to remove the ability to spend the first instance -- even after
1350 // being sent to another address.
1351 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1352 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1353 // already refuses previously-known transaction id's entirely.
1354 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1355 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1356 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1358 BOOST_FOREACH(CTransaction& tx, vtx)
1360 CTxIndex txindexOld;
1361 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1363 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1370 // BIP16 didn't become active until Apr 1 2012 (Feb 15 on testnet)
1371 int64 nBIP16SwitchTime = fTestNet ? 1329264000 : 1333238400;
1372 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1374 //// issue here: it doesn't know the version
1375 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1377 map<uint256, CTxIndex> mapQueuedChanges;
1380 int64 nValueOut = 0;
1381 unsigned int nSigOps = 0;
1382 BOOST_FOREACH(CTransaction& tx, vtx)
1384 nSigOps += tx.GetLegacySigOpCount();
1385 if (nSigOps > MAX_BLOCK_SIGOPS)
1386 return DoS(100, error("ConnectBlock() : too many sigops"));
1388 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1389 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1391 MapPrevTx mapInputs;
1392 if (tx.IsCoinBase())
1393 nValueOut += tx.GetValueOut();
1397 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1400 if (fStrictPayToScriptHash)
1402 // Add in sigops done by pay-to-script-hash inputs;
1403 // this is to prevent a "rogue miner" from creating
1404 // an incredibly-expensive-to-validate block.
1405 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1406 if (nSigOps > MAX_BLOCK_SIGOPS)
1407 return DoS(100, error("ConnectBlock() : too many sigops"));
1410 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1411 int64 nTxValueOut = tx.GetValueOut();
1412 nValueIn += nTxValueIn;
1413 nValueOut += nTxValueOut;
1414 if (!tx.IsCoinStake())
1415 nFees += nTxValueIn - nTxValueOut;
1417 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1421 mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
1424 // ppcoin: track money supply and mint amount info
1425 pindex->nMint = nValueOut - nValueIn + nFees;
1426 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1427 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1428 return error("Connect() : WriteBlockIndex for pindex failed");
1430 // Write queued txindex changes
1431 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1433 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1434 return error("ConnectBlock() : UpdateTxIndex failed");
1437 // ppcoin: fees are not collected by miners as in bitcoin
1438 // ppcoin: fees are destroyed to compensate the entire network
1439 if (fDebug && GetBoolArg("-printcreation"))
1440 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1442 // Update block index on disk without changing it in memory.
1443 // The memory index structure will be changed after the db commits.
1446 CDiskBlockIndex blockindexPrev(pindex->pprev);
1447 blockindexPrev.hashNext = pindex->GetBlockHash();
1448 if (!txdb.WriteBlockIndex(blockindexPrev))
1449 return error("ConnectBlock() : WriteBlockIndex for blockindexPrev failed");
1452 // Watch for transactions paying to me
1453 BOOST_FOREACH(CTransaction& tx, vtx)
1454 SyncWithWallets(tx, this, true);
1459 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1461 printf("REORGANIZE\n");
1464 CBlockIndex* pfork = pindexBest;
1465 CBlockIndex* plonger = pindexNew;
1466 while (pfork != plonger)
1468 while (plonger->nHeight > pfork->nHeight)
1469 if (!(plonger = plonger->pprev))
1470 return error("Reorganize() : plonger->pprev is null");
1471 if (pfork == plonger)
1473 if (!(pfork = pfork->pprev))
1474 return error("Reorganize() : pfork->pprev is null");
1477 // List of what to disconnect
1478 vector<CBlockIndex*> vDisconnect;
1479 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1480 vDisconnect.push_back(pindex);
1482 // List of what to connect
1483 vector<CBlockIndex*> vConnect;
1484 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1485 vConnect.push_back(pindex);
1486 reverse(vConnect.begin(), vConnect.end());
1488 printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
1489 printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
1491 // Disconnect shorter branch
1492 vector<CTransaction> vResurrect;
1493 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1496 if (!block.ReadFromDisk(pindex))
1497 return error("Reorganize() : ReadFromDisk for disconnect failed");
1498 if (!block.DisconnectBlock(txdb, pindex))
1499 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1501 // Queue memory transactions to resurrect
1502 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1503 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1504 vResurrect.push_back(tx);
1507 // Connect longer branch
1508 vector<CTransaction> vDelete;
1509 for (unsigned int i = 0; i < vConnect.size(); i++)
1511 CBlockIndex* pindex = vConnect[i];
1513 if (!block.ReadFromDisk(pindex))
1514 return error("Reorganize() : ReadFromDisk for connect failed");
1515 if (!block.ConnectBlock(txdb, pindex))
1519 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1522 // Queue memory transactions to delete
1523 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1524 vDelete.push_back(tx);
1526 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1527 return error("Reorganize() : WriteHashBestChain failed");
1529 // Make sure it's successfully written to disk before changing memory structure
1530 if (!txdb.TxnCommit())
1531 return error("Reorganize() : TxnCommit failed");
1533 // Disconnect shorter branch
1534 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1536 pindex->pprev->pnext = NULL;
1538 // Connect longer branch
1539 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1541 pindex->pprev->pnext = pindex;
1543 // Resurrect memory transactions that were in the disconnected branch
1544 BOOST_FOREACH(CTransaction& tx, vResurrect)
1545 tx.AcceptToMemoryPool(txdb, false);
1547 // Delete redundant memory transactions that are in the connected branch
1548 BOOST_FOREACH(CTransaction& tx, vDelete)
1551 printf("REORGANIZE: done\n");
1558 runCommand(std::string strCommand)
1560 int nErr = ::system(strCommand.c_str());
1562 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1565 // Called from inside SetBestChain: attaches a block to the new best chain being built
1566 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1568 uint256 hash = GetHash();
1570 // Adding to current best branch
1571 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1574 InvalidChainFound(pindexNew);
1577 if (!txdb.TxnCommit())
1578 return error("SetBestChain() : TxnCommit failed");
1580 // Add to current best branch
1581 pindexNew->pprev->pnext = pindexNew;
1583 // Delete redundant memory transactions
1584 BOOST_FOREACH(CTransaction& tx, vtx)
1590 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1592 uint256 hash = GetHash();
1594 if (!txdb.TxnBegin())
1595 return error("SetBestChain() : TxnBegin failed");
1597 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1599 txdb.WriteHashBestChain(hash);
1600 if (!txdb.TxnCommit())
1601 return error("SetBestChain() : TxnCommit failed");
1602 pindexGenesisBlock = pindexNew;
1604 else if (hashPrevBlock == hashBestChain)
1606 if (!SetBestChainInner(txdb, pindexNew))
1607 return error("SetBestChain() : SetBestChainInner failed");
1611 // the first block in the new chain that will cause it to become the new best chain
1612 CBlockIndex *pindexIntermediate = pindexNew;
1614 // list of blocks that need to be connected afterwards
1615 std::vector<CBlockIndex*> vpindexSecondary;
1617 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1618 // Try to limit how much needs to be done inside
1619 while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust)
1621 vpindexSecondary.push_back(pindexIntermediate);
1622 pindexIntermediate = pindexIntermediate->pprev;
1625 if (!vpindexSecondary.empty())
1626 printf("Postponing %i reconnects\n", vpindexSecondary.size());
1628 // Switch to new best branch
1629 if (!Reorganize(txdb, pindexIntermediate))
1632 InvalidChainFound(pindexNew);
1633 return error("SetBestChain() : Reorganize failed");
1636 // Connect futher blocks
1637 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1640 if (!block.ReadFromDisk(pindex))
1642 printf("SetBestChain() : ReadFromDisk failed\n");
1645 if (!txdb.TxnBegin()) {
1646 printf("SetBestChain() : TxnBegin 2 failed\n");
1649 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1650 if (!block.SetBestChainInner(txdb, pindex))
1655 // Update best block in wallet (so we can detect restored wallets)
1656 bool fIsInitialDownload = IsInitialBlockDownload();
1657 if (!fIsInitialDownload)
1659 const CBlockLocator locator(pindexNew);
1660 ::SetBestChain(locator);
1664 hashBestChain = hash;
1665 pindexBest = pindexNew;
1666 nBestHeight = pindexBest->nHeight;
1667 bnBestChainTrust = pindexNew->bnChainTrust;
1668 nTimeBestReceived = GetTime();
1669 nTransactionsUpdated++;
1670 printf("SetBestChain: new best=%s height=%d trust=%s moneysupply=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(), FormatMoney(pindexBest->nMoneySupply).c_str());
1672 std::string strCmd = GetArg("-blocknotify", "");
1674 if (!fIsInitialDownload && !strCmd.empty())
1676 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1677 boost::thread t(runCommand, strCmd); // thread runs free
1684 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1685 // Only those coins meeting minimum age requirement counts. As those
1686 // transactions not in main chain are not currently indexed so we
1687 // might not find out about their coin age. Older transactions are
1688 // guaranteed to be in main chain by sync-checkpoint. This rule is
1689 // introduced to help nodes establish a consistent view of the coin
1690 // age (trust score) of competing branches.
1691 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1693 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1699 BOOST_FOREACH(const CTxIn& txin, vin)
1701 // First try finding the previous transaction in database
1702 CTransaction txPrev;
1704 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1705 continue; // previous transaction not in main chain
1706 if (nTime < txPrev.nTime)
1707 return false; // Transaction timestamp violation
1709 // Read block header
1711 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1712 return false; // unable to read block of previous transaction
1713 if (block.GetBlockTime() + nStakeMinAge > nTime)
1714 continue; // only count coins meeting min age requirement
1716 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1717 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1719 if (fDebug && GetBoolArg("-printcoinage"))
1720 printf("coin age nValueIn=%-12I64d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1723 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1724 if (fDebug && GetBoolArg("-printcoinage"))
1725 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1726 nCoinAge = bnCoinDay.getuint64();
1730 // ppcoin: total coin age spent in block, in the unit of coin-days.
1731 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1736 BOOST_FOREACH(const CTransaction& tx, vtx)
1739 if (tx.GetCoinAge(txdb, nTxCoinAge))
1740 nCoinAge += nTxCoinAge;
1745 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1747 if (fDebug && GetBoolArg("-printcoinage"))
1748 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1753 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1755 // Check for duplicate
1756 uint256 hash = GetHash();
1757 if (mapBlockIndex.count(hash))
1758 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1760 // Construct new block index object
1761 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1763 return error("AddToBlockIndex() : new CBlockIndex failed");
1765 pindexNew->phashBlock = &hash;
1766 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1767 if (miPrev != mapBlockIndex.end())
1769 pindexNew->pprev = (*miPrev).second;
1770 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1773 // ppcoin: compute chain trust score
1774 pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
1776 // ppcoin: compute stake entropy bit for stake modifier
1777 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit()))
1778 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
1780 // ppcoin: record proof-of-stake hash value
1781 if (pindexNew->IsProofOfStake())
1783 if (!mapProofOfStake.count(hash))
1784 return error("AddToBlockIndex() : hashProofOfStake not found in map");
1785 pindexNew->hashProofOfStake = mapProofOfStake[hash];
1788 // ppcoin: compute stake modifier
1789 uint64 nStakeModifier = 0;
1790 bool fGeneratedStakeModifier = false;
1791 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
1792 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
1793 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
1794 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
1795 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
1796 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
1798 // Add to mapBlockIndex
1799 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1800 if (pindexNew->IsProofOfStake())
1801 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
1802 pindexNew->phashBlock = &((*mi).first);
1804 // Write to disk block index
1806 if (!txdb.TxnBegin())
1808 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1809 if (!txdb.TxnCommit())
1813 if (pindexNew->bnChainTrust > bnBestChainTrust)
1814 if (!SetBestChain(txdb, pindexNew))
1819 if (pindexNew == pindexBest)
1821 // Notify UI to display prev block's coinbase if it was ours
1822 static uint256 hashPrevBestCoinBase;
1823 UpdatedTransaction(hashPrevBestCoinBase);
1824 hashPrevBestCoinBase = vtx[0].GetHash();
1834 bool CBlock::CheckBlock() const
1836 // These are checks that are independent of context
1837 // that can be verified before saving an orphan block.
1840 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
1841 return DoS(100, error("CheckBlock() : size limits failed"));
1843 // Check proof of work matches claimed amount
1844 if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1845 return DoS(50, error("CheckBlock() : proof of work failed"));
1848 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
1849 return error("CheckBlock() : block timestamp too far in the future");
1851 // First transaction must be coinbase, the rest must not be
1852 if (vtx.empty() || !vtx[0].IsCoinBase())
1853 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1854 for (unsigned int i = 1; i < vtx.size(); i++)
1855 if (vtx[i].IsCoinBase())
1856 return DoS(100, error("CheckBlock() : more than one coinbase"));
1858 // ppcoin: only the second transaction can be the optional coinstake
1859 for (int i = 2; i < vtx.size(); i++)
1860 if (vtx[i].IsCoinStake())
1861 return DoS(100, error("CheckBlock() : coinstake in wrong position"));
1863 // ppcoin: coinbase output should be empty if proof-of-stake block
1864 if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty()))
1865 return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
1867 // Check coinbase timestamp
1868 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
1869 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
1871 // Check coinstake timestamp
1872 if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
1873 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%u nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
1875 // Check coinbase reward
1876 if (vtx[0].GetValueOut() > (IsProofOfWork()? (GetProofOfWorkReward(nBits) - vtx[0].GetMinFee() + MIN_TX_FEE) : 0))
1877 return DoS(50, error("CheckBlock() : coinbase reward exceeded %s > %s",
1878 FormatMoney(vtx[0].GetValueOut()).c_str(),
1879 FormatMoney(IsProofOfWork()? GetProofOfWorkReward(nBits) : 0).c_str()));
1881 // Check transactions
1882 BOOST_FOREACH(const CTransaction& tx, vtx)
1884 if (!tx.CheckTransaction())
1885 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1886 // ppcoin: check transaction timestamp
1887 if (GetBlockTime() < (int64)tx.nTime)
1888 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
1891 // Check for duplicate txids. This is caught by ConnectInputs(),
1892 // but catching it earlier avoids a potential DoS attack:
1893 set<uint256> uniqueTx;
1894 BOOST_FOREACH(const CTransaction& tx, vtx)
1896 uniqueTx.insert(tx.GetHash());
1898 if (uniqueTx.size() != vtx.size())
1899 return DoS(100, error("CheckBlock() : duplicate transaction"));
1901 unsigned int nSigOps = 0;
1902 BOOST_FOREACH(const CTransaction& tx, vtx)
1904 nSigOps += tx.GetLegacySigOpCount();
1906 if (nSigOps > MAX_BLOCK_SIGOPS)
1907 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1910 if (hashMerkleRoot != BuildMerkleTree())
1911 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1913 // ppcoin: check block signature
1914 if (!CheckBlockSignature())
1915 return DoS(100, error("CheckBlock() : bad block signature"));
1920 bool CBlock::AcceptBlock()
1922 // Check for duplicate
1923 uint256 hash = GetHash();
1924 if (mapBlockIndex.count(hash))
1925 return error("AcceptBlock() : block already in mapBlockIndex");
1927 // Get prev block index
1928 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1929 if (mi == mapBlockIndex.end())
1930 return DoS(10, error("AcceptBlock() : prev block not found"));
1931 CBlockIndex* pindexPrev = (*mi).second;
1932 int nHeight = pindexPrev->nHeight+1;
1934 // Check proof-of-work or proof-of-stake
1935 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
1936 return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake"));
1938 // Check timestamp against prev
1939 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
1940 return error("AcceptBlock() : block's timestamp is too early");
1942 // Check that all transactions are finalized
1943 BOOST_FOREACH(const CTransaction& tx, vtx)
1944 if (!tx.IsFinal(nHeight, GetBlockTime()))
1945 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1947 // Check that the block chain matches the known block chain up to a hardened checkpoint
1948 if (!Checkpoints::CheckHardened(nHeight, hash))
1949 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight));
1951 // ppcoin: check that the block satisfies synchronized checkpoint
1952 if (!Checkpoints::CheckSync(hash, pindexPrev))
1953 return error("AcceptBlock() : rejected by synchronized checkpoint");
1957 CScript expect = CScript() << nHeight;
1959 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
1960 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
1963 // Write block to history file
1964 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
1965 return error("AcceptBlock() : out of disk space");
1966 unsigned int nFile = -1;
1967 unsigned int nBlockPos = 0;
1968 if (!WriteToDisk(nFile, nBlockPos))
1969 return error("AcceptBlock() : WriteToDisk failed");
1970 if (!AddToBlockIndex(nFile, nBlockPos))
1971 return error("AcceptBlock() : AddToBlockIndex failed");
1973 // Relay inventory, but don't relay old inventory during initial block download
1974 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1975 if (hashBestChain == hash)
1978 BOOST_FOREACH(CNode* pnode, vNodes)
1979 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1980 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1983 // ppcoin: check pending sync-checkpoint
1984 Checkpoints::AcceptPendingSyncCheckpoint();
1989 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1991 // Check for duplicate
1992 uint256 hash = pblock->GetHash();
1993 if (mapBlockIndex.count(hash))
1994 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1995 if (mapOrphanBlocks.count(hash))
1996 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1998 // ppcoin: check proof-of-stake
1999 // Limited duplicity on stake: prevents block flood attack
2000 // Duplicate stake allowed only when there is orphan child block
2001 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2002 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());
2004 // Preliminary checks
2005 if (!pblock->CheckBlock())
2006 return error("ProcessBlock() : CheckBlock FAILED");
2008 // ppcoin: verify hash target and signature of coinstake tx
2009 if (pblock->IsProofOfStake())
2011 uint256 hashProofOfStake = 0;
2012 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake))
2014 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2015 return false; // do not error here as we expect this during initial block download
2017 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2018 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2021 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2022 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2024 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2025 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2027 bnNewBlock.SetCompact(pblock->nBits);
2029 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime));
2031 if (bnNewBlock > bnRequired)
2034 pfrom->Misbehaving(100);
2035 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2039 // ppcoin: ask for pending sync-checkpoint if any
2040 if (!IsInitialBlockDownload())
2041 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2043 // If don't already have its previous block, shunt it off to holding area until we get it
2044 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2046 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2047 CBlock* pblock2 = new CBlock(*pblock);
2048 // ppcoin: check proof-of-stake
2049 if (pblock2->IsProofOfStake())
2051 // Limited duplicity on stake: prevents block flood attack
2052 // Duplicate stake allowed only when there is orphan child block
2053 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2054 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());
2056 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2058 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2059 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2061 // Ask this guy to fill in what we're missing
2064 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2065 // ppcoin: getblocks may not obtain the ancestor block rejected
2066 // earlier by duplicate-stake check so we ask for it again directly
2067 if (!IsInitialBlockDownload())
2068 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2074 if (!pblock->AcceptBlock())
2075 return error("ProcessBlock() : AcceptBlock FAILED");
2077 // Recursively process any orphan blocks that depended on this one
2078 vector<uint256> vWorkQueue;
2079 vWorkQueue.push_back(hash);
2080 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2082 uint256 hashPrev = vWorkQueue[i];
2083 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2084 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2087 CBlock* pblockOrphan = (*mi).second;
2088 if (pblockOrphan->AcceptBlock())
2089 vWorkQueue.push_back(pblockOrphan->GetHash());
2090 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2091 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2092 delete pblockOrphan;
2094 mapOrphanBlocksByPrev.erase(hashPrev);
2097 printf("ProcessBlock: ACCEPTED\n");
2099 // ppcoin: if responsible for sync-checkpoint send it
2100 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2101 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2106 // ppcoin: sign block
2107 bool CBlock::SignBlock(const CKeyStore& keystore)
2109 vector<valtype> vSolutions;
2110 txnouttype whichType;
2111 int nVouts = nTime < 1361664000 ? 1 : vtx[0].vout.size();
2113 if(!IsProofOfStake())
2115 for(int i = 0; i < nVouts; i++)
2117 const CTxOut& txout = vtx[0].vout[i];
2119 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2122 if (whichType == TX_PUBKEY)
2125 valtype& vchPubKey = vSolutions[0];
2128 if (!keystore.GetKey(Hash160(vchPubKey), key))
2130 if (key.GetPubKey() != vchPubKey)
2132 if(!key.Sign(GetHash(), vchBlockSig))
2141 const CTxOut& txout = vtx[1].vout[1];
2143 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2146 if (whichType == TX_PUBKEY)
2149 valtype& vchPubKey = vSolutions[0];
2152 if (!keystore.GetKey(Hash160(vchPubKey), key))
2154 if (key.GetPubKey() != vchPubKey)
2157 return key.Sign(GetHash(), vchBlockSig);
2161 printf("Sign failed\n");
2165 // ppcoin: check block signature
2166 bool CBlock::CheckBlockSignature() const
2168 if (GetHash() == hashGenesisBlock)
2169 return vchBlockSig.empty();
2171 vector<valtype> vSolutions;
2172 txnouttype whichType;
2173 int nVouts = nTime < 1361664000 ? 1 : vtx[0].vout.size();
2175 if(IsProofOfStake())
2177 const CTxOut& txout = vtx[1].vout[1];
2179 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2181 if (whichType == TX_PUBKEY)
2183 valtype& vchPubKey = vSolutions[0];
2185 if (!key.SetPubKey(vchPubKey))
2187 if (vchBlockSig.empty())
2189 return key.Verify(GetHash(), vchBlockSig);
2194 for(int i = 0; i < nVouts; i++)
2196 const CTxOut& txout = vtx[0].vout[i];
2198 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2201 if (whichType == TX_PUBKEY)
2204 valtype& vchPubKey = vSolutions[0];
2206 if (!key.SetPubKey(vchPubKey))
2208 if (vchBlockSig.empty())
2210 if(!key.Verify(GetHash(), vchBlockSig))
2225 bool CheckDiskSpace(uint64 nAdditionalBytes)
2227 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2229 // Check for 15MB because database could create another 10MB log file at any time
2230 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
2233 string strMessage = _("Warning: Disk space is low");
2234 strMiscWarning = strMessage;
2235 printf("*** %s\n", strMessage.c_str());
2236 ThreadSafeMessageBox(strMessage, "NovaCoin", wxOK | wxICON_EXCLAMATION | wxMODAL);
2243 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2247 FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
2250 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2252 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2261 static unsigned int nCurrentBlockFile = 1;
2263 FILE* AppendBlockFile(unsigned int& nFileRet)
2268 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2271 if (fseek(file, 0, SEEK_END) != 0)
2273 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2274 if (ftell(file) < 0x7F000000 - MAX_SIZE)
2276 nFileRet = nCurrentBlockFile;
2280 nCurrentBlockFile++;
2284 bool LoadBlockIndex(bool fAllowNew)
2288 hashGenesisBlock = hashGenesisBlockTestNet;
2289 nStakeMinAge = 60 * 60 * 24; // test net min age is 1 day
2290 nCoinbaseMaturity = 60;
2293 printf("%s Network: genesis=0x%s nBitsLimit=0x%08x nBitsInitial=0x%08x nStakeMinAge=%d nCoinbaseMaturity=%d nModifierInterval=%d\n",
2294 fTestNet? "Test" : "NovaCoin", hashGenesisBlock.ToString().substr(0, 20).c_str(), bnProofOfWorkLimit.GetCompact(), bnInitialHashTarget.GetCompact(), nStakeMinAge, nCoinbaseMaturity, nModifierInterval);
2300 if (!txdb.LoadBlockIndex())
2305 // Init with genesis block
2307 if (mapBlockIndex.empty())
2313 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2315 txNew.nTime = 1360105017;
2316 txNew.vin.resize(1);
2317 txNew.vout.resize(1);
2318 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2319 txNew.vout[0].SetEmpty();
2321 block.vtx.push_back(txNew);
2322 block.hashPrevBlock = 0;
2323 block.hashMerkleRoot = block.BuildMerkleTree();
2325 block.nTime = 1360105017;
2326 block.nBits = bnProofOfWorkLimit.GetCompact();
2327 block.nNonce = 1575379;
2330 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2332 assert(block.GetHash() == hashGenesisBlock);
2333 assert(block.CheckBlock());
2335 // Start new block file
2337 unsigned int nBlockPos;
2338 if (!block.WriteToDisk(nFile, nBlockPos))
2339 return error("LoadBlockIndex() : writing genesis block to disk failed");
2340 if (!block.AddToBlockIndex(nFile, nBlockPos))
2341 return error("LoadBlockIndex() : genesis block not accepted");
2343 // ppcoin: initialize synchronized checkpoint
2344 if (!Checkpoints::WriteSyncCheckpoint(hashGenesisBlock))
2345 return error("LoadBlockIndex() : failed to init sync checkpoint");
2348 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2351 string strPubKey = "";
2352 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2354 // write checkpoint master key to db
2356 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2357 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2358 if (!txdb.TxnCommit())
2359 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2360 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2361 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2371 void PrintBlockTree()
2373 // precompute tree structure
2374 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2375 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2377 CBlockIndex* pindex = (*mi).second;
2378 mapNext[pindex->pprev].push_back(pindex);
2380 //while (rand() % 3 == 0)
2381 // mapNext[pindex->pprev].push_back(pindex);
2384 vector<pair<int, CBlockIndex*> > vStack;
2385 vStack.push_back(make_pair(0, pindexGenesisBlock));
2388 while (!vStack.empty())
2390 int nCol = vStack.back().first;
2391 CBlockIndex* pindex = vStack.back().second;
2394 // print split or gap
2395 if (nCol > nPrevCol)
2397 for (int i = 0; i < nCol-1; i++)
2401 else if (nCol < nPrevCol)
2403 for (int i = 0; i < nCol; i++)
2410 for (int i = 0; i < nCol; i++)
2415 block.ReadFromDisk(pindex);
2416 printf("%d (%u,%u) %s %08lx %s mint %7s tx %d",
2420 block.GetHash().ToString().c_str(),
2422 DateTimeStrFormat(block.GetBlockTime()).c_str(),
2423 FormatMoney(pindex->nMint).c_str(),
2426 PrintWallets(block);
2428 // put the main timechain first
2429 vector<CBlockIndex*>& vNext = mapNext[pindex];
2430 for (unsigned int i = 0; i < vNext.size(); i++)
2432 if (vNext[i]->pnext)
2434 swap(vNext[0], vNext[i]);
2440 for (unsigned int i = 0; i < vNext.size(); i++)
2441 vStack.push_back(make_pair(nCol+i, vNext[i]));
2454 //////////////////////////////////////////////////////////////////////////////
2459 map<uint256, CAlert> mapAlerts;
2460 CCriticalSection cs_mapAlerts;
2462 static string strMintMessage = _("Info: Minting suspended due to locked wallet.");
2463 static string strMintWarning;
2465 string GetWarnings(string strFor)
2468 string strStatusBar;
2470 if (GetBoolArg("-testsafemode"))
2473 // ppcoin: wallet lock warning for minting
2474 if (strMintWarning != "")
2477 strStatusBar = strMintWarning;
2480 // Misc warnings like out of disk space and clock is wrong
2481 if (strMiscWarning != "")
2484 strStatusBar = strMiscWarning;
2487 // ppcoin: should not enter safe mode for longer invalid chain
2488 // ppcoin: if sync-checkpoint is too old do not enter safe mode
2489 if (Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) && !fTestNet)
2492 strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.";
2495 // ppcoin: if detected invalid checkpoint enter safe mode
2496 if (Checkpoints::hashInvalidCheckpoint != 0)
2499 strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.";
2505 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2507 const CAlert& alert = item.second;
2508 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2510 nPriority = alert.nPriority;
2511 strStatusBar = alert.strStatusBar;
2512 if (nPriority > 1000)
2513 strRPC = strStatusBar; // ppcoin: safe mode for high alert
2518 if (strFor == "statusbar")
2519 return strStatusBar;
2520 else if (strFor == "rpc")
2522 assert(!"GetWarnings() : invalid parameter");
2526 bool CAlert::ProcessAlert()
2528 if (!CheckSignature())
2535 // Cancel previous alerts
2536 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2538 const CAlert& alert = (*mi).second;
2541 printf("cancelling alert %d\n", alert.nID);
2542 mapAlerts.erase(mi++);
2544 else if (!alert.IsInEffect())
2546 printf("expiring alert %d\n", alert.nID);
2547 mapAlerts.erase(mi++);
2553 // Check if this alert has been cancelled
2554 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2556 const CAlert& alert = item.second;
2557 if (alert.Cancels(*this))
2559 printf("alert already cancelled by %d\n", alert.nID);
2565 mapAlerts.insert(make_pair(GetHash(), *this));
2568 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2580 //////////////////////////////////////////////////////////////////////////////
2586 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2592 bool txInMap = false;
2595 txInMap = (mempool.exists(inv.hash));
2598 mapOrphanTransactions.count(inv.hash) ||
2599 txdb.ContainsTx(inv.hash);
2603 return mapBlockIndex.count(inv.hash) ||
2604 mapOrphanBlocks.count(inv.hash);
2606 // Don't know what it is, just say we already got one
2613 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2615 static map<CService, vector<unsigned char> > mapReuseKey;
2616 RandAddSeedPerfmon();
2618 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
2619 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2621 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2623 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2631 if (strCommand == "version")
2633 // Each connection can only send one version message
2634 if (pfrom->nVersion != 0)
2636 pfrom->Misbehaving(1);
2644 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2645 if (pfrom->nVersion < MIN_PROTO_VERSION)
2647 // Since February 20, 2012, the protocol is initiated at version 209,
2648 // and earlier versions are no longer supported
2649 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2650 pfrom->fDisconnect = true;
2654 if (pfrom->nVersion == 10300)
2655 pfrom->nVersion = 300;
2657 vRecv >> addrFrom >> nNonce;
2659 vRecv >> pfrom->strSubVer;
2661 vRecv >> pfrom->nStartingHeight;
2663 // Disconnect if we connected to ourself
2664 if (nNonce == nLocalHostNonce && nNonce > 1)
2666 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2667 pfrom->fDisconnect = true;
2671 // ppcoin: record my external IP reported by peer
2672 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
2673 addrSeenByPeer = addrMe;
2675 // Be shy and don't send version until we hear
2676 if (pfrom->fInbound)
2677 pfrom->PushVersion();
2679 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2681 AddTimeData(pfrom->addr, nTime);
2684 pfrom->PushMessage("verack");
2685 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2687 if (!pfrom->fInbound)
2689 // Advertise our address
2690 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() &&
2691 !IsInitialBlockDownload())
2693 CAddress addr(addrLocalHost);
2694 addr.nTime = GetAdjustedTime();
2695 pfrom->PushAddress(addr);
2698 // Get recent addresses
2699 if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2701 pfrom->PushMessage("getaddr");
2702 pfrom->fGetAddr = true;
2704 addrman.Good(pfrom->addr);
2706 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2708 addrman.Add(addrFrom, addrFrom);
2709 addrman.Good(addrFrom);
2713 // Ask the first connected node for block updates
2714 static int nAskedForBlocks = 0;
2715 if (!pfrom->fClient &&
2716 (pfrom->nVersion < NOBLKS_VERSION_START ||
2717 pfrom->nVersion >= NOBLKS_VERSION_END) &&
2718 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2721 pfrom->PushGetBlocks(pindexBest, uint256(0));
2727 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2728 item.second.RelayTo(pfrom);
2731 // ppcoin: relay sync-checkpoint
2733 LOCK(Checkpoints::cs_hashSyncCheckpoint);
2734 if (!Checkpoints::checkpointMessage.IsNull())
2735 Checkpoints::checkpointMessage.RelayTo(pfrom);
2738 pfrom->fSuccessfullyConnected = true;
2740 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2742 cPeerBlockCounts.input(pfrom->nStartingHeight);
2744 // ppcoin: ask for pending sync-checkpoint if any
2745 if (!IsInitialBlockDownload())
2746 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2750 else if (pfrom->nVersion == 0)
2752 // Must have a version message before anything else
2753 pfrom->Misbehaving(1);
2758 else if (strCommand == "verack")
2760 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2764 else if (strCommand == "addr")
2766 vector<CAddress> vAddr;
2769 // Don't want addr from older versions unless seeding
2770 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2772 if (vAddr.size() > 1000)
2774 pfrom->Misbehaving(20);
2775 return error("message addr size() = %d", vAddr.size());
2778 // Store the new addresses
2779 int64 nNow = GetAdjustedTime();
2780 int64 nSince = nNow - 10 * 60;
2781 BOOST_FOREACH(CAddress& addr, vAddr)
2785 // ignore IPv6 for now, since it isn't implemented anyway
2788 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2789 addr.nTime = nNow - 5 * 24 * 60 * 60;
2790 pfrom->AddAddressKnown(addr);
2791 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2793 // Relay to a limited number of other nodes
2796 // Use deterministic randomness to send to the same nodes for 24 hours
2797 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2798 static uint256 hashSalt;
2800 hashSalt = GetRandHash();
2801 int64 hashAddr = addr.GetHash();
2802 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2803 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2804 multimap<uint256, CNode*> mapMix;
2805 BOOST_FOREACH(CNode* pnode, vNodes)
2807 if (pnode->nVersion < CADDR_TIME_VERSION)
2809 unsigned int nPointer;
2810 memcpy(&nPointer, &pnode, sizeof(nPointer));
2811 uint256 hashKey = hashRand ^ nPointer;
2812 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2813 mapMix.insert(make_pair(hashKey, pnode));
2815 int nRelayNodes = 2;
2816 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2817 ((*mi).second)->PushAddress(addr);
2821 addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60);
2822 if (vAddr.size() < 1000)
2823 pfrom->fGetAddr = false;
2827 else if (strCommand == "inv")
2831 if (vInv.size() > 50000)
2833 pfrom->Misbehaving(20);
2834 return error("message inv size() = %d", vInv.size());
2837 // find last block in inv vector
2838 unsigned int nLastBlock = (unsigned int)(-1);
2839 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
2840 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
2841 nLastBlock = vInv.size() - 1 - nInv;
2846 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
2848 const CInv &inv = vInv[nInv];
2852 pfrom->AddInventoryKnown(inv);
2854 bool fAlreadyHave = AlreadyHave(txdb, inv);
2856 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2860 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
2861 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2862 } else if (nInv == nLastBlock) {
2863 // In case we are on a very long side-chain, it is possible that we already have
2864 // the last block in an inv bundle sent in response to getblocks. Try to detect
2865 // this situation and push another getblocks to continue.
2866 std::vector<CInv> vGetData(1,inv);
2867 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
2869 printf("force request: %s\n", inv.ToString().c_str());
2872 // Track requests for our stuff
2873 Inventory(inv.hash);
2878 else if (strCommand == "getdata")
2882 if (vInv.size() > 50000)
2884 pfrom->Misbehaving(20);
2885 return error("message getdata size() = %d", vInv.size());
2888 BOOST_FOREACH(const CInv& inv, vInv)
2892 printf("received getdata for: %s\n", inv.ToString().c_str());
2894 if (inv.type == MSG_BLOCK)
2896 // Send block from disk
2897 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2898 if (mi != mapBlockIndex.end())
2901 block.ReadFromDisk((*mi).second);
2902 pfrom->PushMessage("block", block);
2904 // Trigger them to send a getblocks request for the next batch of inventory
2905 if (inv.hash == pfrom->hashContinue)
2907 // Bypass PushInventory, this must send even if redundant,
2908 // and we want it right after the last block so they don't
2909 // wait for other stuff first.
2910 // ppcoin: send latest proof-of-work block to allow the
2911 // download node to accept as orphan (proof-of-stake
2912 // block might be rejected by stake connection check)
2914 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
2915 pfrom->PushMessage("inv", vInv);
2916 pfrom->hashContinue = 0;
2920 else if (inv.IsKnownType())
2922 // Send stream from relay memory
2925 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2926 if (mi != mapRelay.end())
2927 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2931 // Track requests for our stuff
2932 Inventory(inv.hash);
2937 else if (strCommand == "getblocks")
2939 CBlockLocator locator;
2941 vRecv >> locator >> hashStop;
2943 // Find the last block the caller has in the main chain
2944 CBlockIndex* pindex = locator.GetBlockIndex();
2946 // Send the rest of the chain
2948 pindex = pindex->pnext;
2949 int nLimit = 500 + locator.GetDistanceBack();
2950 unsigned int nBytes = 0;
2951 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2952 for (; pindex; pindex = pindex->pnext)
2954 if (pindex->GetBlockHash() == hashStop)
2956 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2957 // ppcoin: tell downloading node about the latest block if it's
2958 // without risk being rejected due to stake connection check
2959 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
2960 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
2963 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2965 block.ReadFromDisk(pindex, true);
2966 nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
2967 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2969 // When this block is requested, we'll send an inv that'll make them
2970 // getblocks the next batch of inventory.
2971 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2972 pfrom->hashContinue = pindex->GetBlockHash();
2979 else if (strCommand == "getheaders")
2981 CBlockLocator locator;
2983 vRecv >> locator >> hashStop;
2985 CBlockIndex* pindex = NULL;
2986 if (locator.IsNull())
2988 // If locator is null, return the hashStop block
2989 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2990 if (mi == mapBlockIndex.end())
2992 pindex = (*mi).second;
2996 // Find the last block the caller has in the main chain
2997 pindex = locator.GetBlockIndex();
2999 pindex = pindex->pnext;
3002 vector<CBlock> vHeaders;
3004 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3005 for (; pindex; pindex = pindex->pnext)
3007 vHeaders.push_back(pindex->GetBlockHeader());
3008 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3011 pfrom->PushMessage("headers", vHeaders);
3015 else if (strCommand == "tx")
3017 vector<uint256> vWorkQueue;
3018 vector<uint256> vEraseQueue;
3019 CDataStream vMsg(vRecv);
3024 CInv inv(MSG_TX, tx.GetHash());
3025 pfrom->AddInventoryKnown(inv);
3027 bool fMissingInputs = false;
3028 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3030 SyncWithWallets(tx, NULL, true);
3031 RelayMessage(inv, vMsg);
3032 mapAlreadyAskedFor.erase(inv);
3033 vWorkQueue.push_back(inv.hash);
3034 vEraseQueue.push_back(inv.hash);
3036 // Recursively process any orphan transactions that depended on this one
3037 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3039 uint256 hashPrev = vWorkQueue[i];
3040 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3041 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3044 const CDataStream& vMsg = *((*mi).second);
3046 CDataStream(vMsg) >> tx;
3047 CInv inv(MSG_TX, tx.GetHash());
3048 bool fMissingInputs2 = false;
3050 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3052 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3053 SyncWithWallets(tx, NULL, true);
3054 RelayMessage(inv, vMsg);
3055 mapAlreadyAskedFor.erase(inv);
3056 vWorkQueue.push_back(inv.hash);
3057 vEraseQueue.push_back(inv.hash);
3059 else if (!fMissingInputs2)
3062 vEraseQueue.push_back(inv.hash);
3063 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3068 BOOST_FOREACH(uint256 hash, vEraseQueue)
3069 EraseOrphanTx(hash);
3071 else if (fMissingInputs)
3075 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3076 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3078 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3080 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3084 else if (strCommand == "block")
3089 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3092 CInv inv(MSG_BLOCK, block.GetHash());
3093 pfrom->AddInventoryKnown(inv);
3095 if (ProcessBlock(pfrom, &block))
3096 mapAlreadyAskedFor.erase(inv);
3097 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3101 else if (strCommand == "getaddr")
3103 pfrom->vAddrToSend.clear();
3104 vector<CAddress> vAddr = addrman.GetAddr();
3105 BOOST_FOREACH(const CAddress &addr, vAddr)
3106 pfrom->PushAddress(addr);
3110 else if (strCommand == "checkorder")
3115 if (!GetBoolArg("-allowreceivebyip"))
3117 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3124 /// we have a chance to check the order here
3126 // Keep giving the same key to the same ip until they use it
3127 if (!mapReuseKey.count(pfrom->addr))
3128 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3130 // Send back approval of order and pubkey to use
3131 CScript scriptPubKey;
3132 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3133 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3137 else if (strCommand == "reply")
3142 CRequestTracker tracker;
3144 LOCK(pfrom->cs_mapRequests);
3145 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3146 if (mi != pfrom->mapRequests.end())
3148 tracker = (*mi).second;
3149 pfrom->mapRequests.erase(mi);
3152 if (!tracker.IsNull())
3153 tracker.fn(tracker.param1, vRecv);
3157 else if (strCommand == "ping")
3159 if (pfrom->nVersion > BIP0031_VERSION)
3163 // Echo the message back with the nonce. This allows for two useful features:
3165 // 1) A remote node can quickly check if the connection is operational
3166 // 2) Remote nodes can measure the latency of the network thread. If this node
3167 // is overloaded it won't respond to pings quickly and the remote node can
3168 // avoid sending us more work, like chain download requests.
3170 // The nonce stops the remote getting confused between different pings: without
3171 // it, if the remote node sends a ping once per second and this node takes 5
3172 // seconds to respond to each, the 5th ping the remote sends would appear to
3173 // return very quickly.
3174 pfrom->PushMessage("pong", nonce);
3179 else if (strCommand == "alert")
3184 if (alert.ProcessAlert())
3187 pfrom->setKnown.insert(alert.GetHash());
3190 BOOST_FOREACH(CNode* pnode, vNodes)
3191 alert.RelayTo(pnode);
3196 else if (strCommand == "checkpoint")
3198 CSyncCheckpoint checkpoint;
3199 vRecv >> checkpoint;
3201 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3204 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3206 BOOST_FOREACH(CNode* pnode, vNodes)
3207 checkpoint.RelayTo(pnode);
3213 // Ignore unknown commands for extensibility
3217 // Update the last seen time for this node's address
3218 if (pfrom->fNetworkNode)
3219 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3220 AddressCurrentlyConnected(pfrom->addr);
3226 bool ProcessMessages(CNode* pfrom)
3228 CDataStream& vRecv = pfrom->vRecv;
3232 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3236 // (4) message start
3243 unsigned char pchMessageStart[4];
3244 GetMessageStart(pchMessageStart);
3245 static int64 nTimeLastPrintMessageStart = 0;
3246 if (fDebug && GetBoolArg("-printmessagestart") && nTimeLastPrintMessageStart + 30 < GetAdjustedTime())
3248 string strMessageStart((const char *)pchMessageStart, sizeof(pchMessageStart));
3249 vector<unsigned char> vchMessageStart(strMessageStart.begin(), strMessageStart.end());
3250 printf("ProcessMessages : AdjustedTime=%"PRI64d" MessageStart=%s\n", GetAdjustedTime(), HexStr(vchMessageStart).c_str());
3251 nTimeLastPrintMessageStart = GetAdjustedTime();
3256 // Scan for message start
3257 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3258 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3259 if (vRecv.end() - pstart < nHeaderSize)
3261 if ((int)vRecv.size() > nHeaderSize)
3263 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3264 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3268 if (pstart - vRecv.begin() > 0)
3269 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
3270 vRecv.erase(vRecv.begin(), pstart);
3273 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3278 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3281 string strCommand = hdr.GetCommand();
3284 unsigned int nMessageSize = hdr.nMessageSize;
3285 if (nMessageSize > MAX_SIZE)
3287 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3290 if (nMessageSize > vRecv.size())
3292 // Rewind and wait for rest of message
3293 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3298 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3299 unsigned int nChecksum = 0;
3300 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3301 if (nChecksum != hdr.nChecksum)
3303 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3304 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3308 // Copy message to its own buffer
3309 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3310 vRecv.ignore(nMessageSize);
3318 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3323 catch (std::ios_base::failure& e)
3325 if (strstr(e.what(), "end of data"))
3327 // Allow exceptions from underlength message on vRecv
3328 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());
3330 else if (strstr(e.what(), "size too large"))
3332 // Allow exceptions from overlong size
3333 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3337 PrintExceptionContinue(&e, "ProcessMessages()");
3340 catch (std::exception& e) {
3341 PrintExceptionContinue(&e, "ProcessMessages()");
3343 PrintExceptionContinue(NULL, "ProcessMessages()");
3347 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3355 bool SendMessages(CNode* pto, bool fSendTrickle)
3357 TRY_LOCK(cs_main, lockMain);
3359 // Don't send anything until we get their version message
3360 if (pto->nVersion == 0)
3363 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3365 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3367 if (pto->nVersion > BIP0031_VERSION)
3368 pto->PushMessage("ping", nonce);
3370 pto->PushMessage("ping");
3373 // Resend wallet transactions that haven't gotten in a block yet
3374 ResendWalletTransactions();
3376 // Address refresh broadcast
3377 static int64 nLastRebroadcast;
3378 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3382 BOOST_FOREACH(CNode* pnode, vNodes)
3384 // Periodically clear setAddrKnown to allow refresh broadcasts
3385 if (nLastRebroadcast)
3386 pnode->setAddrKnown.clear();
3388 // Rebroadcast our address
3389 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable())
3391 CAddress addr(addrLocalHost);
3392 addr.nTime = GetAdjustedTime();
3393 pnode->PushAddress(addr);
3397 nLastRebroadcast = GetTime();
3405 vector<CAddress> vAddr;
3406 vAddr.reserve(pto->vAddrToSend.size());
3407 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3409 // returns true if wasn't already contained in the set
3410 if (pto->setAddrKnown.insert(addr).second)
3412 vAddr.push_back(addr);
3413 // receiver rejects addr messages larger than 1000
3414 if (vAddr.size() >= 1000)
3416 pto->PushMessage("addr", vAddr);
3421 pto->vAddrToSend.clear();
3423 pto->PushMessage("addr", vAddr);
3428 // Message: inventory
3431 vector<CInv> vInvWait;
3433 LOCK(pto->cs_inventory);
3434 vInv.reserve(pto->vInventoryToSend.size());
3435 vInvWait.reserve(pto->vInventoryToSend.size());
3436 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3438 if (pto->setInventoryKnown.count(inv))
3441 // trickle out tx inv to protect privacy
3442 if (inv.type == MSG_TX && !fSendTrickle)
3444 // 1/4 of tx invs blast to all immediately
3445 static uint256 hashSalt;
3447 hashSalt = GetRandHash();
3448 uint256 hashRand = inv.hash ^ hashSalt;
3449 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3450 bool fTrickleWait = ((hashRand & 3) != 0);
3452 // always trickle our own transactions
3456 if (GetTransaction(inv.hash, wtx))
3458 fTrickleWait = true;
3463 vInvWait.push_back(inv);
3468 // returns true if wasn't already contained in the set
3469 if (pto->setInventoryKnown.insert(inv).second)
3471 vInv.push_back(inv);
3472 if (vInv.size() >= 1000)
3474 pto->PushMessage("inv", vInv);
3479 pto->vInventoryToSend = vInvWait;
3482 pto->PushMessage("inv", vInv);
3488 vector<CInv> vGetData;
3489 int64 nNow = GetTime() * 1000000;
3491 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3493 const CInv& inv = (*pto->mapAskFor.begin()).second;
3494 if (!AlreadyHave(txdb, inv))
3496 printf("sending getdata: %s\n", inv.ToString().c_str());
3497 vGetData.push_back(inv);
3498 if (vGetData.size() >= 1000)
3500 pto->PushMessage("getdata", vGetData);
3504 mapAlreadyAskedFor[inv] = nNow;
3505 pto->mapAskFor.erase(pto->mapAskFor.begin());
3507 if (!vGetData.empty())
3508 pto->PushMessage("getdata", vGetData);
3527 //////////////////////////////////////////////////////////////////////////////
3532 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3534 unsigned char* pdata = (unsigned char*)pbuffer;
3535 unsigned int blocks = 1 + ((len + 8) / 64);
3536 unsigned char* pend = pdata + 64 * blocks;
3537 memset(pdata + len, 0, 64 * blocks - len);
3539 unsigned int bits = len * 8;
3540 pend[-1] = (bits >> 0) & 0xff;
3541 pend[-2] = (bits >> 8) & 0xff;
3542 pend[-3] = (bits >> 16) & 0xff;
3543 pend[-4] = (bits >> 24) & 0xff;
3547 static const unsigned int pSHA256InitState[8] =
3548 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3550 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3553 unsigned char data[64];
3557 for (int i = 0; i < 16; i++)
3558 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3560 for (int i = 0; i < 8; i++)
3561 ctx.h[i] = ((uint32_t*)pinit)[i];
3563 SHA256_Update(&ctx, data, sizeof(data));
3564 for (int i = 0; i < 8; i++)
3565 ((uint32_t*)pstate)[i] = ctx.h[i];
3568 // Some explaining would be appreciated
3573 set<uint256> setDependsOn;
3576 COrphan(CTransaction* ptxIn)
3584 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3585 BOOST_FOREACH(uint256 hash, setDependsOn)
3586 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3591 uint64 nLastBlockTx = 0;
3592 uint64 nLastBlockSize = 0;
3593 int64 nLastCoinStakeSearchInterval = 0;
3596 // fProofOfStake: try (best effort) to make a proof-of-stake block
3597 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
3599 CReserveKey reservekey(pwallet);
3602 auto_ptr<CBlock> pblock(new CBlock());
3606 // Create coinbase tx
3608 txNew.vin.resize(1);
3609 txNew.vin[0].prevout.SetNull();
3610 txNew.vout.resize(1);
3611 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3613 // Add our coinbase tx as first transaction
3614 pblock->vtx.push_back(txNew);
3616 // ppcoin: if coinstake available add coinstake tx
3617 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
3618 CBlockIndex* pindexPrev = pindexBest;
3620 if (fProofOfStake) // attemp to find a coinstake
3622 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
3623 CTransaction txCoinStake;
3624 int64 nSearchTime = txCoinStake.nTime; // search to current time
3625 if (nSearchTime > nLastCoinStakeSearchTime)
3627 if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
3629 if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
3630 { // make sure coinstake would meet timestamp protocol
3631 // as it would be the same as the block timestamp
3632 pblock->vtx[0].vout[0].SetEmpty();
3633 pblock->vtx[0].nTime = txCoinStake.nTime;
3634 pblock->vtx.push_back(txCoinStake);
3637 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
3638 nLastCoinStakeSearchTime = nSearchTime;
3642 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
3644 // Collect memory pool transactions into the block
3647 LOCK2(cs_main, mempool.cs);
3650 // Priority order to process transactions
3651 list<COrphan> vOrphan; // list memory doesn't move
3652 map<uint256, vector<COrphan*> > mapDependers;
3653 multimap<double, CTransaction*> mapPriority;
3654 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3656 CTransaction& tx = (*mi).second;
3657 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
3660 COrphan* porphan = NULL;
3661 double dPriority = 0;
3662 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3664 // Read prev transaction
3665 CTransaction txPrev;
3667 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3669 // Has to wait for dependencies
3672 // Use list for automatic deletion
3673 vOrphan.push_back(COrphan(&tx));
3674 porphan = &vOrphan.back();
3676 mapDependers[txin.prevout.hash].push_back(porphan);
3677 porphan->setDependsOn.insert(txin.prevout.hash);
3680 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3682 // Read block header
3683 int nConf = txindex.GetDepthInMainChain();
3685 dPriority += (double)nValueIn * nConf;
3687 if (fDebug && GetBoolArg("-printpriority"))
3688 printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3691 // Priority is sum(valuein * age) / txsize
3692 dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3695 porphan->dPriority = dPriority;
3697 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3699 if (fDebug && GetBoolArg("-printpriority"))
3701 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3708 // Collect transactions into block
3709 map<uint256, CTxIndex> mapTestPool;
3710 uint64 nBlockSize = 1000;
3711 uint64 nBlockTx = 0;
3712 int nBlockSigOps = 100;
3713 while (!mapPriority.empty())
3715 // Take highest priority transaction off priority queue
3716 CTransaction& tx = *(*mapPriority.begin()).second;
3717 mapPriority.erase(mapPriority.begin());
3720 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3721 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3724 // Legacy limits on sigOps:
3725 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
3726 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3730 if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
3733 // ppcoin: simplify transaction fee - allow free = false
3734 int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
3736 // Connecting shouldn't fail due to dependency on other memory pool transactions
3737 // because we're already processing them in order of dependency
3738 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3739 MapPrevTx mapInputs;
3741 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3744 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3745 if (nTxFees < nMinFee)
3748 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3749 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3752 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3754 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3755 swap(mapTestPool, mapTestPoolTmp);
3758 pblock->vtx.push_back(tx);
3759 nBlockSize += nTxSize;
3761 nBlockSigOps += nTxSigOps;
3764 // Add transactions that depend on this one to the priority queue
3765 uint256 hash = tx.GetHash();
3766 if (mapDependers.count(hash))
3768 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3770 if (!porphan->setDependsOn.empty())
3772 porphan->setDependsOn.erase(hash);
3773 if (porphan->setDependsOn.empty())
3774 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3780 nLastBlockTx = nBlockTx;
3781 nLastBlockSize = nBlockSize;
3782 if (fDebug && GetBoolArg("-printpriority"))
3783 printf("CreateNewBlock(): total size %lu\n", nBlockSize);
3786 if (pblock->IsProofOfWork())
3787 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
3790 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3791 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3792 if (pblock->IsProofOfStake())
3793 pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
3794 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
3795 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
3796 if (pblock->IsProofOfWork())
3797 pblock->UpdateTime(pindexPrev);
3800 return pblock.release();
3804 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3806 // Update nExtraNonce
3807 static uint256 hashPrevBlock;
3808 if (hashPrevBlock != pblock->hashPrevBlock)
3811 hashPrevBlock = pblock->hashPrevBlock;
3815 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
3816 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
3818 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3820 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3824 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3827 // Prebuild hash buffers
3834 uint256 hashPrevBlock;
3835 uint256 hashMerkleRoot;
3838 unsigned int nNonce;
3841 unsigned char pchPadding0[64];
3843 unsigned char pchPadding1[64];
3846 memset(&tmp, 0, sizeof(tmp));
3848 tmp.block.nVersion = pblock->nVersion;
3849 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3850 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3851 tmp.block.nTime = pblock->nTime;
3852 tmp.block.nBits = pblock->nBits;
3853 tmp.block.nNonce = pblock->nNonce;
3855 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3856 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3858 // Byte swap all the input buffer
3859 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3860 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3862 // Precalc the first half of the first hash, which stays constant
3863 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3865 memcpy(pdata, &tmp.block, 128);
3866 memcpy(phash1, &tmp.hash1, 64);
3870 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3872 uint256 hash = pblock->GetHash();
3873 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3875 if (hash > hashTarget && pblock->IsProofOfWork())
3876 return error("BitcoinMiner : proof-of-work not meeting target");
3879 printf("BitcoinMiner:\n");
3880 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3882 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
3883 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3888 if (pblock->hashPrevBlock != hashBestChain)
3889 return error("BitcoinMiner : generated block is stale");
3891 // Remove key from key pool
3892 reservekey.KeepKey();
3894 // Track how many getdata requests this block gets
3896 LOCK(wallet.cs_wallet);
3897 wallet.mapRequestCount[pblock->GetHash()] = 0;
3900 // Process this block the same as if we had received it from another node
3901 if (!ProcessBlock(NULL, pblock))
3902 return error("BitcoinMiner : ProcessBlock, block not accepted");
3908 void static ThreadBitcoinMiner(void* parg);
3910 static bool fGenerateBitcoins = false;
3911 static bool fLimitProcessors = false;
3912 static int nLimitProcessors = -1;
3914 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake)
3916 void *scratchbuf = scrypt_buffer_alloc();
3918 printf("CPUMiner started for proof-of-%s\n", fProofOfStake? "stake" : "work");
3919 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3921 // Each thread has its own key and counter
3922 CReserveKey reservekey(pwallet);
3923 unsigned int nExtraNonce = 0;
3925 while (fGenerateBitcoins || fProofOfStake)
3929 while (vNodes.empty() || IsInitialBlockDownload())
3934 if ((!fGenerateBitcoins) && !fProofOfStake)
3938 while (pwallet->IsLocked())
3940 strMintWarning = strMintMessage;
3943 strMintWarning = "";
3948 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3949 CBlockIndex* pindexPrev = pindexBest;
3951 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
3955 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3959 // ppcoin: if proof-of-stake block found then process block
3960 if (pblock->IsProofOfStake())
3962 if (!pblock->SignBlock(*pwalletMain))
3964 strMintWarning = strMintMessage;
3967 strMintWarning = "";
3968 printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
3969 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3970 CheckWork(pblock.get(), *pwalletMain, reservekey);
3971 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3977 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3981 // Prebuild hash buffers
3983 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3984 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3985 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3987 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3989 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3990 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3996 int64 nStart = GetTime();
3997 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3999 unsigned int max_nonce = 0xffff0000;
4000 block_header res_header;
4005 unsigned int nHashesDone = 0;
4006 unsigned int nNonceFound;
4008 nNonceFound = scanhash_scrypt(
4009 (block_header *)&pblock->nVersion,
4017 // Check if something found
4018 if (nNonceFound != (unsigned int) -1)
4020 if (result <= hashTarget)
4023 pblock->nNonce = nNonceFound;
4024 assert(result == pblock->GetHash());
4025 if (!pblock->SignBlock(*pwalletMain))
4027 strMintWarning = strMintMessage;
4030 strMintWarning = "";
4031 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4032 CheckWork(pblock.get(), *pwalletMain, reservekey);
4033 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4039 static int64 nHashCounter;
4040 if (nHPSTimerStart == 0)
4042 nHPSTimerStart = GetTimeMillis();
4046 nHashCounter += nHashesDone;
4047 if (GetTimeMillis() - nHPSTimerStart > 4000)
4049 static CCriticalSection cs;
4052 if (GetTimeMillis() - nHPSTimerStart > 4000)
4054 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
4055 nHPSTimerStart = GetTimeMillis();
4057 static int64 nLogTime;
4058 if (GetTime() - nLogTime > 30 * 60)
4060 nLogTime = GetTime();
4061 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
4062 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
4068 // Check for stop or if block needs to be rebuilt
4071 if (!fGenerateBitcoins)
4073 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4077 if (nBlockNonce >= 0xffff0000)
4079 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4081 if (pindexPrev != pindexBest)
4084 // Update nTime every few seconds
4085 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
4086 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4087 pblock->UpdateTime(pindexPrev);
4088 nBlockTime = ByteReverse(pblock->nTime);
4089 if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
4090 break; // need to update coinbase timestamp
4094 scrypt_buffer_free(scratchbuf);
4097 void static ThreadBitcoinMiner(void* parg)
4099 CWallet* pwallet = (CWallet*)parg;
4102 vnThreadsRunning[THREAD_MINER]++;
4103 BitcoinMiner(pwallet, false);
4104 vnThreadsRunning[THREAD_MINER]--;
4106 catch (std::exception& e) {
4107 vnThreadsRunning[THREAD_MINER]--;
4108 PrintException(&e, "ThreadBitcoinMiner()");
4110 vnThreadsRunning[THREAD_MINER]--;
4111 PrintException(NULL, "ThreadBitcoinMiner()");
4114 if (vnThreadsRunning[THREAD_MINER] == 0)
4116 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4120 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4122 fGenerateBitcoins = fGenerate;
4123 nLimitProcessors = GetArg("-genproclimit", -1);
4124 if (nLimitProcessors == 0)
4125 fGenerateBitcoins = false;
4126 fLimitProcessors = (nLimitProcessors != -1);
4130 int nProcessors = boost::thread::hardware_concurrency();
4131 printf("%d processors\n", nProcessors);
4132 if (nProcessors < 1)
4134 if (fLimitProcessors && nProcessors > nLimitProcessors)
4135 nProcessors = nLimitProcessors;
4136 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4137 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4138 for (int i = 0; i < nAddThreads; i++)
4140 if (!CreateThread(ThreadBitcoinMiner, pwallet))
4141 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");