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++;
682 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
684 if (hashBlock == 0 || nIndex == -1)
687 // Find the block it claims to be in
688 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
689 if (mi == mapBlockIndex.end())
691 CBlockIndex* pindex = (*mi).second;
692 if (!pindex || !pindex->IsInMainChain())
695 // Make sure the merkle branch connects to this block
696 if (!fMerkleVerified)
698 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
700 fMerkleVerified = true;
704 return pindexBest->nHeight - pindex->nHeight + 1;
708 int CMerkleTx::GetBlocksToMaturity() const
710 if (!(IsCoinBase() || IsCoinStake()))
712 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
716 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
720 if (!IsInMainChain() && !ClientConnectInputs())
722 return CTransaction::AcceptToMemoryPool(txdb, false);
726 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
730 bool CMerkleTx::AcceptToMemoryPool()
733 return AcceptToMemoryPool(txdb);
736 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
741 // Add previous supporting transactions first
742 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
744 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
746 uint256 hash = tx.GetHash();
747 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
748 tx.AcceptToMemoryPool(txdb, fCheckInputs);
751 return AcceptToMemoryPool(txdb, fCheckInputs);
756 bool CWalletTx::AcceptWalletTransaction()
759 return AcceptWalletTransaction(txdb);
762 int CTxIndex::GetDepthInMainChain() const
766 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
768 // Find the block in the index
769 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
770 if (mi == mapBlockIndex.end())
772 CBlockIndex* pindex = (*mi).second;
773 if (!pindex || !pindex->IsInMainChain())
775 return 1 + nBestHeight - pindex->nHeight;
778 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
779 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
785 if (mempool.exists(hash))
787 tx = mempool.lookup(hash);
793 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
796 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
797 hashBlock = block.GetHash();
804 //////////////////////////////////////////////////////////////////////////////
806 // CBlock and CBlockIndex
809 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
811 if (!fReadTransactions)
813 *this = pindex->GetBlockHeader();
816 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
818 if (GetHash() != pindex->GetBlockHash())
819 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
823 uint256 static GetOrphanRoot(const CBlock* pblock)
825 // Work back to the first block in the orphan chain
826 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
827 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
828 return pblock->GetHash();
831 // ppcoin: find block wanted by given orphan block
832 uint256 WantedByOrphan(const CBlock* pblockOrphan)
834 // Work back to the first block in the orphan chain
835 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
836 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
837 return pblockOrphan->hashPrevBlock;
840 int64 GetProofOfWorkReward(unsigned int nBits)
842 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
844 bnTarget.SetCompact(nBits);
845 CBigNum bnTargetLimit = bnProofOfWorkLimit;
846 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
848 // ppcoin: subsidy is cut in half every 64x multiply of difficulty
849 // A reasonably continuous curve is used to avoid shock to market
850 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
852 // Human readable form:
854 // nSubsidy = 100 / (diff ^ 1/6)
855 CBigNum bnLowerBound = CENT;
856 CBigNum bnUpperBound = bnSubsidyLimit;
857 while (bnLowerBound + CENT <= bnUpperBound)
859 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
860 if (fDebug && GetBoolArg("-printcreation"))
861 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
862 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
863 bnUpperBound = bnMidValue;
865 bnLowerBound = bnMidValue;
868 int64 nSubsidy = bnUpperBound.getuint64();
869 nSubsidy = (nSubsidy / CENT) * CENT;
870 if (fDebug && GetBoolArg("-printcreation"))
871 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
873 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
876 // ppcoin: miner's coin stake is rewarded based on coin age spent (coin-days)
877 int64 GetProofOfStakeReward(int64 nCoinAge)
879 static int64 nRewardCoinYear = 5 * CENT; // creation amount per coin-year
880 int64 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
881 if (fDebug && GetBoolArg("-printcreation"))
882 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nCoinAge);
886 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
887 static const int64 nTargetSpacingWorkMax = 12 * STAKE_TARGET_SPACING; // 2-hour
890 // minimum amount of work that could possibly be required nTime after
891 // minimum work required was nBase
893 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
896 bnResult.SetCompact(nBase);
898 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
900 // Maximum 200% adjustment per day...
902 nTime -= 24 * 60 * 60;
904 if (bnResult > bnProofOfWorkLimit)
905 bnResult = bnProofOfWorkLimit;
906 return bnResult.GetCompact();
909 // ppcoin: find last block index up to pindex
910 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
912 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
913 pindex = pindex->pprev;
917 unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
919 if (pindexLast == NULL)
920 return bnProofOfWorkLimit.GetCompact(); // genesis block
922 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
923 if (pindexPrev->pprev == NULL)
924 return bnInitialHashTarget.GetCompact(); // first block
925 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
926 if (pindexPrevPrev->pprev == NULL)
927 return bnInitialHashTarget.GetCompact(); // second block
929 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
931 // ppcoin: target change every block
932 // ppcoin: retarget with exponential moving toward target spacing
934 bnNew.SetCompact(pindexPrev->nBits);
935 int64 nTargetSpacing = fProofOfStake? STAKE_TARGET_SPACING : min(nTargetSpacingWorkMax, (int64) STAKE_TARGET_SPACING * (1 + pindexLast->nHeight - pindexPrev->nHeight));
936 int64 nInterval = nTargetTimespan / nTargetSpacing;
937 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
938 bnNew /= ((nInterval + 1) * nTargetSpacing);
940 if (bnNew > bnProofOfWorkLimit)
941 bnNew = bnProofOfWorkLimit;
943 return bnNew.GetCompact();
946 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
949 bnTarget.SetCompact(nBits);
952 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
953 return error("CheckProofOfWork() : nBits below minimum work");
955 // Check proof of work matches claimed amount
956 if (hash > bnTarget.getuint256())
957 return error("CheckProofOfWork() : hash doesn't match nBits");
962 // Return maximum amount of blocks that other nodes claim to have
963 int GetNumBlocksOfPeers()
965 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
968 bool IsInitialBlockDownload()
970 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
972 static int64 nLastUpdate;
973 static CBlockIndex* pindexLastBest;
974 if (pindexBest != pindexLastBest)
976 pindexLastBest = pindexBest;
977 nLastUpdate = GetTime();
979 return (GetTime() - nLastUpdate < 10 &&
980 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
983 void static InvalidChainFound(CBlockIndex* pindexNew)
985 if (pindexNew->bnChainTrust > bnBestInvalidTrust)
987 bnBestInvalidTrust = pindexNew->bnChainTrust;
988 CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust);
991 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());
992 printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(bnBestChainTrust).ToString().c_str());
993 // ppcoin: should not enter safe mode for longer invalid chain
996 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
998 nTime = max(GetBlockTime(), GetAdjustedTime());
1011 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1013 // Relinquish previous transactions' spent pointers
1016 BOOST_FOREACH(const CTxIn& txin, vin)
1018 COutPoint prevout = txin.prevout;
1020 // Get prev txindex from disk
1022 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1023 return error("DisconnectInputs() : ReadTxIndex failed");
1025 if (prevout.n >= txindex.vSpent.size())
1026 return error("DisconnectInputs() : prevout.n out of range");
1028 // Mark outpoint as not spent
1029 txindex.vSpent[prevout.n].SetNull();
1032 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1033 return error("DisconnectInputs() : UpdateTxIndex failed");
1037 // Remove transaction from index
1038 // This can fail if a duplicate of this transaction was in a chain that got
1039 // reorganized away. This is only possible if this transaction was completely
1040 // spent, so erasing it would be a no-op anway.
1041 txdb.EraseTxIndex(*this);
1047 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1048 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1050 // FetchInputs can return false either because we just haven't seen some inputs
1051 // (in which case the transaction should be stored as an orphan)
1052 // or because the transaction is malformed (in which case the transaction should
1053 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1057 return true; // Coinbase transactions have no inputs to fetch.
1059 for (unsigned int i = 0; i < vin.size(); i++)
1061 COutPoint prevout = vin[i].prevout;
1062 if (inputsRet.count(prevout.hash))
1063 continue; // Got it already
1066 CTxIndex& txindex = inputsRet[prevout.hash].first;
1068 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1070 // Get txindex from current proposed changes
1071 txindex = mapTestPool.find(prevout.hash)->second;
1075 // Read txindex from txdb
1076 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1078 if (!fFound && (fBlock || fMiner))
1079 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());
1082 CTransaction& txPrev = inputsRet[prevout.hash].second;
1083 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1085 // Get prev tx from single transactions in memory
1088 if (!mempool.exists(prevout.hash))
1089 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());
1090 txPrev = mempool.lookup(prevout.hash);
1093 txindex.vSpent.resize(txPrev.vout.size());
1097 // Get prev tx from disk
1098 if (!txPrev.ReadFromDisk(txindex.pos))
1099 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1103 // Make sure all prevout.n's are valid:
1104 for (unsigned int i = 0; i < vin.size(); i++)
1106 const COutPoint prevout = vin[i].prevout;
1107 assert(inputsRet.count(prevout.hash) != 0);
1108 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1109 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1110 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1112 // Revisit this if/when transaction replacement is implemented and allows
1115 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()));
1122 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1124 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1125 if (mi == inputs.end())
1126 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1128 const CTransaction& txPrev = (mi->second).second;
1129 if (input.prevout.n >= txPrev.vout.size())
1130 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1132 return txPrev.vout[input.prevout.n];
1135 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1141 for (unsigned int i = 0; i < vin.size(); i++)
1143 nResult += GetOutputFor(vin[i], inputs).nValue;
1149 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1154 unsigned int nSigOps = 0;
1155 for (unsigned int i = 0; i < vin.size(); i++)
1157 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1158 if (prevout.scriptPubKey.IsPayToScriptHash())
1159 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1164 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1165 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1166 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1168 // Take over previous transactions' spent pointers
1169 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1170 // fMiner is true when called from the internal bitcoin miner
1171 // ... both are false when called from CTransaction::AcceptToMemoryPool
1176 for (unsigned int i = 0; i < vin.size(); i++)
1178 COutPoint prevout = vin[i].prevout;
1179 assert(inputs.count(prevout.hash) > 0);
1180 CTxIndex& txindex = inputs[prevout.hash].first;
1181 CTransaction& txPrev = inputs[prevout.hash].second;
1183 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1184 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()));
1186 // If prev is coinbase/coinstake, check that it's matured
1187 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1188 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1189 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1190 return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight);
1192 // ppcoin: check transaction timestamp
1193 if (txPrev.nTime > nTime)
1194 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1196 // Check for negative or overflow input values
1197 nValueIn += txPrev.vout[prevout.n].nValue;
1198 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1199 return DoS(100, error("ConnectInputs() : txin values out of range"));
1202 // The first loop above does all the inexpensive checks.
1203 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1204 // Helps prevent CPU exhaustion attacks.
1205 for (unsigned int i = 0; i < vin.size(); i++)
1207 COutPoint prevout = vin[i].prevout;
1208 assert(inputs.count(prevout.hash) > 0);
1209 CTxIndex& txindex = inputs[prevout.hash].first;
1210 CTransaction& txPrev = inputs[prevout.hash].second;
1212 // Check for conflicts (double-spend)
1213 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1214 // for an attacker to attempt to split the network.
1215 if (!txindex.vSpent[prevout.n].IsNull())
1216 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());
1218 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1219 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1220 // still computed and checked, and any change will be caught at the next checkpoint.
1221 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1224 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1226 // only during transition phase for P2SH: do not invoke anti-DoS code for
1227 // potentially old clients relaying bad P2SH transactions
1228 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1229 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1231 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1235 // Mark outpoints as spent
1236 txindex.vSpent[prevout.n] = posThisTx;
1239 if (fBlock || fMiner)
1241 mapTestPool[prevout.hash] = txindex;
1247 // ppcoin: coin stake tx earns reward instead of paying fee
1249 if (!GetCoinAge(txdb, nCoinAge))
1250 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1251 int64 nStakeReward = GetValueOut() - nValueIn;
1252 if (nStakeReward > GetProofOfStakeReward(nCoinAge) - GetMinFee() + MIN_TX_FEE)
1253 return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
1257 if (nValueIn < GetValueOut())
1258 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1260 // Tally transaction fees
1261 int64 nTxFee = nValueIn - GetValueOut();
1263 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1264 // ppcoin: enforce transaction fees for every block
1265 if (nTxFee < GetMinFee())
1266 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;
1268 if (!MoneyRange(nFees))
1269 return DoS(100, error("ConnectInputs() : nFees out of range"));
1277 bool CTransaction::ClientConnectInputs()
1282 // Take over previous transactions' spent pointers
1286 for (unsigned int i = 0; i < vin.size(); i++)
1288 // Get prev tx from single transactions in memory
1289 COutPoint prevout = vin[i].prevout;
1290 if (!mempool.exists(prevout.hash))
1292 CTransaction& txPrev = mempool.lookup(prevout.hash);
1294 if (prevout.n >= txPrev.vout.size())
1298 if (!VerifySignature(txPrev, *this, i, true, 0))
1299 return error("ConnectInputs() : VerifySignature failed");
1301 ///// this is redundant with the mempool.mapNextTx stuff,
1302 ///// not sure which I want to get rid of
1303 ///// this has to go away now that posNext is gone
1304 // // Check for conflicts
1305 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1306 // return error("ConnectInputs() : prev tx already used");
1308 // // Flag outpoints as used
1309 // txPrev.vout[prevout.n].posNext = posThisTx;
1311 nValueIn += txPrev.vout[prevout.n].nValue;
1313 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1314 return error("ClientConnectInputs() : txin values out of range");
1316 if (GetValueOut() > nValueIn)
1326 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1328 // Disconnect in reverse order
1329 for (int i = vtx.size()-1; i >= 0; i--)
1330 if (!vtx[i].DisconnectInputs(txdb))
1333 // Update block index on disk without changing it in memory.
1334 // The memory index structure will be changed after the db commits.
1337 CDiskBlockIndex blockindexPrev(pindex->pprev);
1338 blockindexPrev.hashNext = 0;
1339 if (!txdb.WriteBlockIndex(blockindexPrev))
1340 return error("DisconnectBlock() : WriteBlockIndex failed");
1343 // ppcoin: clean up wallet after disconnecting coinstake
1344 BOOST_FOREACH(CTransaction& tx, vtx)
1345 SyncWithWallets(tx, this, false, false);
1350 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1352 // Check it again in case a previous version let a bad block in
1356 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1357 // unless those are already completely spent.
1358 // If such overwrites are allowed, coinbases and transactions depending upon those
1359 // can be duplicated to remove the ability to spend the first instance -- even after
1360 // being sent to another address.
1361 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1362 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1363 // already refuses previously-known transaction id's entirely.
1364 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1365 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1366 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1368 BOOST_FOREACH(CTransaction& tx, vtx)
1370 CTxIndex txindexOld;
1371 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1373 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1380 // BIP16 didn't become active until Apr 1 2012 (Feb 15 on testnet)
1381 int64 nBIP16SwitchTime = fTestNet ? 1329264000 : 1333238400;
1382 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1384 //// issue here: it doesn't know the version
1385 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1387 map<uint256, CTxIndex> mapQueuedChanges;
1390 int64 nValueOut = 0;
1391 unsigned int nSigOps = 0;
1392 BOOST_FOREACH(CTransaction& tx, vtx)
1394 nSigOps += tx.GetLegacySigOpCount();
1395 if (nSigOps > MAX_BLOCK_SIGOPS)
1396 return DoS(100, error("ConnectBlock() : too many sigops"));
1398 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1399 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1401 MapPrevTx mapInputs;
1402 if (tx.IsCoinBase())
1403 nValueOut += tx.GetValueOut();
1407 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1410 if (fStrictPayToScriptHash)
1412 // Add in sigops done by pay-to-script-hash inputs;
1413 // this is to prevent a "rogue miner" from creating
1414 // an incredibly-expensive-to-validate block.
1415 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1416 if (nSigOps > MAX_BLOCK_SIGOPS)
1417 return DoS(100, error("ConnectBlock() : too many sigops"));
1420 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1421 int64 nTxValueOut = tx.GetValueOut();
1422 nValueIn += nTxValueIn;
1423 nValueOut += nTxValueOut;
1424 if (!tx.IsCoinStake())
1425 nFees += nTxValueIn - nTxValueOut;
1427 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1431 mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
1434 // ppcoin: track money supply and mint amount info
1435 pindex->nMint = nValueOut - nValueIn + nFees;
1436 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1437 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1438 return error("Connect() : WriteBlockIndex for pindex failed");
1440 // Write queued txindex changes
1441 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1443 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1444 return error("ConnectBlock() : UpdateTxIndex failed");
1447 // ppcoin: fees are not collected by miners as in bitcoin
1448 // ppcoin: fees are destroyed to compensate the entire network
1449 if (fDebug && GetBoolArg("-printcreation"))
1450 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1452 // Update block index on disk without changing it in memory.
1453 // The memory index structure will be changed after the db commits.
1456 CDiskBlockIndex blockindexPrev(pindex->pprev);
1457 blockindexPrev.hashNext = pindex->GetBlockHash();
1458 if (!txdb.WriteBlockIndex(blockindexPrev))
1459 return error("ConnectBlock() : WriteBlockIndex for blockindexPrev failed");
1462 // Watch for transactions paying to me
1463 BOOST_FOREACH(CTransaction& tx, vtx)
1464 SyncWithWallets(tx, this, true);
1469 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1471 printf("REORGANIZE\n");
1474 CBlockIndex* pfork = pindexBest;
1475 CBlockIndex* plonger = pindexNew;
1476 while (pfork != plonger)
1478 while (plonger->nHeight > pfork->nHeight)
1479 if (!(plonger = plonger->pprev))
1480 return error("Reorganize() : plonger->pprev is null");
1481 if (pfork == plonger)
1483 if (!(pfork = pfork->pprev))
1484 return error("Reorganize() : pfork->pprev is null");
1487 // List of what to disconnect
1488 vector<CBlockIndex*> vDisconnect;
1489 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1490 vDisconnect.push_back(pindex);
1492 // List of what to connect
1493 vector<CBlockIndex*> vConnect;
1494 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1495 vConnect.push_back(pindex);
1496 reverse(vConnect.begin(), vConnect.end());
1498 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());
1499 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());
1501 // Disconnect shorter branch
1502 vector<CTransaction> vResurrect;
1503 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1506 if (!block.ReadFromDisk(pindex))
1507 return error("Reorganize() : ReadFromDisk for disconnect failed");
1508 if (!block.DisconnectBlock(txdb, pindex))
1509 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1511 // Queue memory transactions to resurrect
1512 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1513 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1514 vResurrect.push_back(tx);
1517 // Connect longer branch
1518 vector<CTransaction> vDelete;
1519 for (unsigned int i = 0; i < vConnect.size(); i++)
1521 CBlockIndex* pindex = vConnect[i];
1523 if (!block.ReadFromDisk(pindex))
1524 return error("Reorganize() : ReadFromDisk for connect failed");
1525 if (!block.ConnectBlock(txdb, pindex))
1529 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1532 // Queue memory transactions to delete
1533 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1534 vDelete.push_back(tx);
1536 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1537 return error("Reorganize() : WriteHashBestChain failed");
1539 // Make sure it's successfully written to disk before changing memory structure
1540 if (!txdb.TxnCommit())
1541 return error("Reorganize() : TxnCommit failed");
1543 // Disconnect shorter branch
1544 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1546 pindex->pprev->pnext = NULL;
1548 // Connect longer branch
1549 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1551 pindex->pprev->pnext = pindex;
1553 // Resurrect memory transactions that were in the disconnected branch
1554 BOOST_FOREACH(CTransaction& tx, vResurrect)
1555 tx.AcceptToMemoryPool(txdb, false);
1557 // Delete redundant memory transactions that are in the connected branch
1558 BOOST_FOREACH(CTransaction& tx, vDelete)
1561 printf("REORGANIZE: done\n");
1568 runCommand(std::string strCommand)
1570 int nErr = ::system(strCommand.c_str());
1572 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1575 // Called from inside SetBestChain: attaches a block to the new best chain being built
1576 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1578 uint256 hash = GetHash();
1580 // Adding to current best branch
1581 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1584 InvalidChainFound(pindexNew);
1587 if (!txdb.TxnCommit())
1588 return error("SetBestChain() : TxnCommit failed");
1590 // Add to current best branch
1591 pindexNew->pprev->pnext = pindexNew;
1593 // Delete redundant memory transactions
1594 BOOST_FOREACH(CTransaction& tx, vtx)
1600 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1602 uint256 hash = GetHash();
1604 if (!txdb.TxnBegin())
1605 return error("SetBestChain() : TxnBegin failed");
1607 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1609 txdb.WriteHashBestChain(hash);
1610 if (!txdb.TxnCommit())
1611 return error("SetBestChain() : TxnCommit failed");
1612 pindexGenesisBlock = pindexNew;
1614 else if (hashPrevBlock == hashBestChain)
1616 if (!SetBestChainInner(txdb, pindexNew))
1617 return error("SetBestChain() : SetBestChainInner failed");
1621 // the first block in the new chain that will cause it to become the new best chain
1622 CBlockIndex *pindexIntermediate = pindexNew;
1624 // list of blocks that need to be connected afterwards
1625 std::vector<CBlockIndex*> vpindexSecondary;
1627 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1628 // Try to limit how much needs to be done inside
1629 while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust)
1631 vpindexSecondary.push_back(pindexIntermediate);
1632 pindexIntermediate = pindexIntermediate->pprev;
1635 if (!vpindexSecondary.empty())
1636 printf("Postponing %i reconnects\n", vpindexSecondary.size());
1638 // Switch to new best branch
1639 if (!Reorganize(txdb, pindexIntermediate))
1642 InvalidChainFound(pindexNew);
1643 return error("SetBestChain() : Reorganize failed");
1646 // Connect futher blocks
1647 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1650 if (!block.ReadFromDisk(pindex))
1652 printf("SetBestChain() : ReadFromDisk failed\n");
1655 if (!txdb.TxnBegin()) {
1656 printf("SetBestChain() : TxnBegin 2 failed\n");
1659 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1660 if (!block.SetBestChainInner(txdb, pindex))
1665 // Update best block in wallet (so we can detect restored wallets)
1666 bool fIsInitialDownload = IsInitialBlockDownload();
1667 if (!fIsInitialDownload)
1669 const CBlockLocator locator(pindexNew);
1670 ::SetBestChain(locator);
1674 hashBestChain = hash;
1675 pindexBest = pindexNew;
1676 nBestHeight = pindexBest->nHeight;
1677 bnBestChainTrust = pindexNew->bnChainTrust;
1678 nTimeBestReceived = GetTime();
1679 nTransactionsUpdated++;
1680 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());
1682 std::string strCmd = GetArg("-blocknotify", "");
1684 if (!fIsInitialDownload && !strCmd.empty())
1686 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1687 boost::thread t(runCommand, strCmd); // thread runs free
1694 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1695 // Only those coins meeting minimum age requirement counts. As those
1696 // transactions not in main chain are not currently indexed so we
1697 // might not find out about their coin age. Older transactions are
1698 // guaranteed to be in main chain by sync-checkpoint. This rule is
1699 // introduced to help nodes establish a consistent view of the coin
1700 // age (trust score) of competing branches.
1701 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1703 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1709 BOOST_FOREACH(const CTxIn& txin, vin)
1711 // First try finding the previous transaction in database
1712 CTransaction txPrev;
1714 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1715 continue; // previous transaction not in main chain
1716 if (nTime < txPrev.nTime)
1717 return false; // Transaction timestamp violation
1719 // Read block header
1721 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1722 return false; // unable to read block of previous transaction
1723 if (block.GetBlockTime() + nStakeMinAge > nTime)
1724 continue; // only count coins meeting min age requirement
1726 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1727 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1729 if (fDebug && GetBoolArg("-printcoinage"))
1730 printf("coin age nValueIn=%-12I64d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1733 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1734 if (fDebug && GetBoolArg("-printcoinage"))
1735 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1736 nCoinAge = bnCoinDay.getuint64();
1740 // ppcoin: total coin age spent in block, in the unit of coin-days.
1741 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1746 BOOST_FOREACH(const CTransaction& tx, vtx)
1749 if (tx.GetCoinAge(txdb, nTxCoinAge))
1750 nCoinAge += nTxCoinAge;
1755 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1757 if (fDebug && GetBoolArg("-printcoinage"))
1758 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1763 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1765 // Check for duplicate
1766 uint256 hash = GetHash();
1767 if (mapBlockIndex.count(hash))
1768 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1770 // Construct new block index object
1771 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1773 return error("AddToBlockIndex() : new CBlockIndex failed");
1775 pindexNew->phashBlock = &hash;
1776 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1777 if (miPrev != mapBlockIndex.end())
1779 pindexNew->pprev = (*miPrev).second;
1780 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1783 // ppcoin: compute chain trust score
1784 pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
1786 // ppcoin: compute stake entropy bit for stake modifier
1787 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
1788 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
1790 // ppcoin: record proof-of-stake hash value
1791 if (pindexNew->IsProofOfStake())
1793 if (!mapProofOfStake.count(hash))
1794 return error("AddToBlockIndex() : hashProofOfStake not found in map");
1795 pindexNew->hashProofOfStake = mapProofOfStake[hash];
1798 // ppcoin: compute stake modifier
1799 uint64 nStakeModifier = 0;
1800 bool fGeneratedStakeModifier = false;
1801 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
1802 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
1803 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
1804 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
1805 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
1806 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
1808 // Add to mapBlockIndex
1809 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1810 if (pindexNew->IsProofOfStake())
1811 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
1812 pindexNew->phashBlock = &((*mi).first);
1814 // Write to disk block index
1816 if (!txdb.TxnBegin())
1818 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1819 if (!txdb.TxnCommit())
1823 if (pindexNew->bnChainTrust > bnBestChainTrust)
1824 if (!SetBestChain(txdb, pindexNew))
1829 if (pindexNew == pindexBest)
1831 // Notify UI to display prev block's coinbase if it was ours
1832 static uint256 hashPrevBestCoinBase;
1833 UpdatedTransaction(hashPrevBestCoinBase);
1834 hashPrevBestCoinBase = vtx[0].GetHash();
1844 bool CBlock::CheckBlock() const
1846 // These are checks that are independent of context
1847 // that can be verified before saving an orphan block.
1850 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
1851 return DoS(100, error("CheckBlock() : size limits failed"));
1853 // Check proof of work matches claimed amount
1854 if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1855 return DoS(50, error("CheckBlock() : proof of work failed"));
1858 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
1859 return error("CheckBlock() : block timestamp too far in the future");
1861 // First transaction must be coinbase, the rest must not be
1862 if (vtx.empty() || !vtx[0].IsCoinBase())
1863 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1864 for (unsigned int i = 1; i < vtx.size(); i++)
1865 if (vtx[i].IsCoinBase())
1866 return DoS(100, error("CheckBlock() : more than one coinbase"));
1868 // ppcoin: only the second transaction can be the optional coinstake
1869 for (int i = 2; i < vtx.size(); i++)
1870 if (vtx[i].IsCoinStake())
1871 return DoS(100, error("CheckBlock() : coinstake in wrong position"));
1873 // ppcoin: coinbase output should be empty if proof-of-stake block
1874 if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty()))
1875 return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
1877 // Check coinbase timestamp
1878 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
1879 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
1881 // Check coinstake timestamp
1882 if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
1883 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%u nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
1885 // Check coinbase reward
1886 if (vtx[0].GetValueOut() > (IsProofOfWork()? (GetProofOfWorkReward(nBits) - vtx[0].GetMinFee() + MIN_TX_FEE) : 0))
1887 return DoS(50, error("CheckBlock() : coinbase reward exceeded %s > %s",
1888 FormatMoney(vtx[0].GetValueOut()).c_str(),
1889 FormatMoney(IsProofOfWork()? GetProofOfWorkReward(nBits) : 0).c_str()));
1891 // Check transactions
1892 BOOST_FOREACH(const CTransaction& tx, vtx)
1894 if (!tx.CheckTransaction())
1895 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1896 // ppcoin: check transaction timestamp
1897 if (GetBlockTime() < (int64)tx.nTime)
1898 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
1901 // Check for duplicate txids. This is caught by ConnectInputs(),
1902 // but catching it earlier avoids a potential DoS attack:
1903 set<uint256> uniqueTx;
1904 BOOST_FOREACH(const CTransaction& tx, vtx)
1906 uniqueTx.insert(tx.GetHash());
1908 if (uniqueTx.size() != vtx.size())
1909 return DoS(100, error("CheckBlock() : duplicate transaction"));
1911 unsigned int nSigOps = 0;
1912 BOOST_FOREACH(const CTransaction& tx, vtx)
1914 nSigOps += tx.GetLegacySigOpCount();
1916 if (nSigOps > MAX_BLOCK_SIGOPS)
1917 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1920 if (hashMerkleRoot != BuildMerkleTree())
1921 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1923 // ppcoin: check block signature
1924 if (!CheckBlockSignature())
1925 return DoS(100, error("CheckBlock() : bad block signature"));
1930 bool CBlock::AcceptBlock()
1932 // Check for duplicate
1933 uint256 hash = GetHash();
1934 if (mapBlockIndex.count(hash))
1935 return error("AcceptBlock() : block already in mapBlockIndex");
1937 // Get prev block index
1938 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1939 if (mi == mapBlockIndex.end())
1940 return DoS(10, error("AcceptBlock() : prev block not found"));
1941 CBlockIndex* pindexPrev = (*mi).second;
1942 int nHeight = pindexPrev->nHeight+1;
1944 // Check proof-of-work or proof-of-stake
1945 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
1946 return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake"));
1948 // Check timestamp against prev
1949 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
1950 return error("AcceptBlock() : block's timestamp is too early");
1952 // Check that all transactions are finalized
1953 BOOST_FOREACH(const CTransaction& tx, vtx)
1954 if (!tx.IsFinal(nHeight, GetBlockTime()))
1955 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1957 // Check that the block chain matches the known block chain up to a hardened checkpoint
1958 if (!Checkpoints::CheckHardened(nHeight, hash))
1959 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight));
1961 // ppcoin: check that the block satisfies synchronized checkpoint
1962 if (!Checkpoints::CheckSync(hash, pindexPrev))
1963 return error("AcceptBlock() : rejected by synchronized checkpoint");
1967 CScript expect = CScript() << nHeight;
1969 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
1970 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
1973 // Write block to history file
1974 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
1975 return error("AcceptBlock() : out of disk space");
1976 unsigned int nFile = -1;
1977 unsigned int nBlockPos = 0;
1978 if (!WriteToDisk(nFile, nBlockPos))
1979 return error("AcceptBlock() : WriteToDisk failed");
1980 if (!AddToBlockIndex(nFile, nBlockPos))
1981 return error("AcceptBlock() : AddToBlockIndex failed");
1983 // Relay inventory, but don't relay old inventory during initial block download
1984 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1985 if (hashBestChain == hash)
1988 BOOST_FOREACH(CNode* pnode, vNodes)
1989 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1990 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1993 // ppcoin: check pending sync-checkpoint
1994 Checkpoints::AcceptPendingSyncCheckpoint();
1999 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2001 // Check for duplicate
2002 uint256 hash = pblock->GetHash();
2003 if (mapBlockIndex.count(hash))
2004 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2005 if (mapOrphanBlocks.count(hash))
2006 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2008 // ppcoin: check proof-of-stake
2009 // Limited duplicity on stake: prevents block flood attack
2010 // Duplicate stake allowed only when there is orphan child block
2011 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2012 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());
2014 // Preliminary checks
2015 if (!pblock->CheckBlock())
2016 return error("ProcessBlock() : CheckBlock FAILED");
2018 // ppcoin: verify hash target and signature of coinstake tx
2019 if (pblock->IsProofOfStake())
2021 uint256 hashProofOfStake = 0;
2022 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake))
2024 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2025 return false; // do not error here as we expect this during initial block download
2027 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2028 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2031 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2032 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2034 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2035 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2037 bnNewBlock.SetCompact(pblock->nBits);
2039 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime));
2041 if (bnNewBlock > bnRequired)
2044 pfrom->Misbehaving(100);
2045 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2049 // ppcoin: ask for pending sync-checkpoint if any
2050 if (!IsInitialBlockDownload())
2051 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2053 // If don't already have its previous block, shunt it off to holding area until we get it
2054 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2056 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2057 CBlock* pblock2 = new CBlock(*pblock);
2058 // ppcoin: check proof-of-stake
2059 if (pblock2->IsProofOfStake())
2061 // Limited duplicity on stake: prevents block flood attack
2062 // Duplicate stake allowed only when there is orphan child block
2063 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2064 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());
2066 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2068 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2069 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2071 // Ask this guy to fill in what we're missing
2074 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2075 // ppcoin: getblocks may not obtain the ancestor block rejected
2076 // earlier by duplicate-stake check so we ask for it again directly
2077 if (!IsInitialBlockDownload())
2078 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2084 if (!pblock->AcceptBlock())
2085 return error("ProcessBlock() : AcceptBlock FAILED");
2087 // Recursively process any orphan blocks that depended on this one
2088 vector<uint256> vWorkQueue;
2089 vWorkQueue.push_back(hash);
2090 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2092 uint256 hashPrev = vWorkQueue[i];
2093 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2094 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2097 CBlock* pblockOrphan = (*mi).second;
2098 if (pblockOrphan->AcceptBlock())
2099 vWorkQueue.push_back(pblockOrphan->GetHash());
2100 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2101 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2102 delete pblockOrphan;
2104 mapOrphanBlocksByPrev.erase(hashPrev);
2107 printf("ProcessBlock: ACCEPTED\n");
2109 // ppcoin: if responsible for sync-checkpoint send it
2110 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2111 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2116 // ppcoin: sign block
2117 bool CBlock::SignBlock(const CKeyStore& keystore)
2119 vector<valtype> vSolutions;
2120 txnouttype whichType;
2121 int nVouts = nTime < 1361664000 ? 1 : vtx[0].vout.size();
2123 if(!IsProofOfStake())
2125 for(int i = 0; i < nVouts; i++)
2127 const CTxOut& txout = vtx[0].vout[i];
2129 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2132 if (whichType == TX_PUBKEY)
2135 valtype& vchPubKey = vSolutions[0];
2138 if (!keystore.GetKey(Hash160(vchPubKey), key))
2140 if (key.GetPubKey() != vchPubKey)
2142 if(!key.Sign(GetHash(), vchBlockSig))
2151 const CTxOut& txout = vtx[1].vout[1];
2153 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2156 if (whichType == TX_PUBKEY)
2159 valtype& vchPubKey = vSolutions[0];
2162 if (!keystore.GetKey(Hash160(vchPubKey), key))
2164 if (key.GetPubKey() != vchPubKey)
2167 return key.Sign(GetHash(), vchBlockSig);
2171 printf("Sign failed\n");
2175 // ppcoin: check block signature
2176 bool CBlock::CheckBlockSignature() const
2178 if (GetHash() == hashGenesisBlock)
2179 return vchBlockSig.empty();
2181 vector<valtype> vSolutions;
2182 txnouttype whichType;
2183 int nVouts = nTime < 1361664000 ? 1 : vtx[0].vout.size();
2185 if(IsProofOfStake())
2187 const CTxOut& txout = vtx[1].vout[1];
2189 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2191 if (whichType == TX_PUBKEY)
2193 valtype& vchPubKey = vSolutions[0];
2195 if (!key.SetPubKey(vchPubKey))
2197 if (vchBlockSig.empty())
2199 return key.Verify(GetHash(), vchBlockSig);
2204 for(int i = 0; i < nVouts; i++)
2206 const CTxOut& txout = vtx[0].vout[i];
2208 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2211 if (whichType == TX_PUBKEY)
2214 valtype& vchPubKey = vSolutions[0];
2216 if (!key.SetPubKey(vchPubKey))
2218 if (vchBlockSig.empty())
2220 if(!key.Verify(GetHash(), vchBlockSig))
2235 bool CheckDiskSpace(uint64 nAdditionalBytes)
2237 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2239 // Check for 15MB because database could create another 10MB log file at any time
2240 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
2243 string strMessage = _("Warning: Disk space is low");
2244 strMiscWarning = strMessage;
2245 printf("*** %s\n", strMessage.c_str());
2246 ThreadSafeMessageBox(strMessage, "NovaCoin", wxOK | wxICON_EXCLAMATION | wxMODAL);
2253 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2257 FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
2260 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2262 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2271 static unsigned int nCurrentBlockFile = 1;
2273 FILE* AppendBlockFile(unsigned int& nFileRet)
2278 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2281 if (fseek(file, 0, SEEK_END) != 0)
2283 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2284 if (ftell(file) < 0x7F000000 - MAX_SIZE)
2286 nFileRet = nCurrentBlockFile;
2290 nCurrentBlockFile++;
2294 bool LoadBlockIndex(bool fAllowNew)
2298 hashGenesisBlock = hashGenesisBlockTestNet;
2299 nStakeMinAge = 60 * 60 * 24; // test net min age is 1 day
2300 nCoinbaseMaturity = 60;
2303 printf("%s Network: genesis=0x%s nBitsLimit=0x%08x nBitsInitial=0x%08x nStakeMinAge=%d nCoinbaseMaturity=%d nModifierInterval=%d\n",
2304 fTestNet? "Test" : "NovaCoin", hashGenesisBlock.ToString().substr(0, 20).c_str(), bnProofOfWorkLimit.GetCompact(), bnInitialHashTarget.GetCompact(), nStakeMinAge, nCoinbaseMaturity, nModifierInterval);
2310 if (!txdb.LoadBlockIndex())
2315 // Init with genesis block
2317 if (mapBlockIndex.empty())
2323 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2325 txNew.nTime = 1360105017;
2326 txNew.vin.resize(1);
2327 txNew.vout.resize(1);
2328 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2329 txNew.vout[0].SetEmpty();
2331 block.vtx.push_back(txNew);
2332 block.hashPrevBlock = 0;
2333 block.hashMerkleRoot = block.BuildMerkleTree();
2335 block.nTime = 1360105017;
2336 block.nBits = bnProofOfWorkLimit.GetCompact();
2337 block.nNonce = 1575379;
2340 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2342 assert(block.GetHash() == hashGenesisBlock);
2343 assert(block.CheckBlock());
2345 // Start new block file
2347 unsigned int nBlockPos;
2348 if (!block.WriteToDisk(nFile, nBlockPos))
2349 return error("LoadBlockIndex() : writing genesis block to disk failed");
2350 if (!block.AddToBlockIndex(nFile, nBlockPos))
2351 return error("LoadBlockIndex() : genesis block not accepted");
2353 // ppcoin: initialize synchronized checkpoint
2354 if (!Checkpoints::WriteSyncCheckpoint(hashGenesisBlock))
2355 return error("LoadBlockIndex() : failed to init sync checkpoint");
2358 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2361 string strPubKey = "";
2362 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2364 // write checkpoint master key to db
2366 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2367 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2368 if (!txdb.TxnCommit())
2369 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2370 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2371 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2381 void PrintBlockTree()
2383 // precompute tree structure
2384 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2385 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2387 CBlockIndex* pindex = (*mi).second;
2388 mapNext[pindex->pprev].push_back(pindex);
2390 //while (rand() % 3 == 0)
2391 // mapNext[pindex->pprev].push_back(pindex);
2394 vector<pair<int, CBlockIndex*> > vStack;
2395 vStack.push_back(make_pair(0, pindexGenesisBlock));
2398 while (!vStack.empty())
2400 int nCol = vStack.back().first;
2401 CBlockIndex* pindex = vStack.back().second;
2404 // print split or gap
2405 if (nCol > nPrevCol)
2407 for (int i = 0; i < nCol-1; i++)
2411 else if (nCol < nPrevCol)
2413 for (int i = 0; i < nCol; i++)
2420 for (int i = 0; i < nCol; i++)
2425 block.ReadFromDisk(pindex);
2426 printf("%d (%u,%u) %s %08lx %s mint %7s tx %d",
2430 block.GetHash().ToString().c_str(),
2432 DateTimeStrFormat(block.GetBlockTime()).c_str(),
2433 FormatMoney(pindex->nMint).c_str(),
2436 PrintWallets(block);
2438 // put the main timechain first
2439 vector<CBlockIndex*>& vNext = mapNext[pindex];
2440 for (unsigned int i = 0; i < vNext.size(); i++)
2442 if (vNext[i]->pnext)
2444 swap(vNext[0], vNext[i]);
2450 for (unsigned int i = 0; i < vNext.size(); i++)
2451 vStack.push_back(make_pair(nCol+i, vNext[i]));
2464 //////////////////////////////////////////////////////////////////////////////
2469 map<uint256, CAlert> mapAlerts;
2470 CCriticalSection cs_mapAlerts;
2472 static string strMintMessage = _("Info: Minting suspended due to locked wallet.");
2473 static string strMintWarning;
2475 string GetWarnings(string strFor)
2478 string strStatusBar;
2480 if (GetBoolArg("-testsafemode"))
2483 // ppcoin: wallet lock warning for minting
2484 if (strMintWarning != "")
2487 strStatusBar = strMintWarning;
2490 // Misc warnings like out of disk space and clock is wrong
2491 if (strMiscWarning != "")
2494 strStatusBar = strMiscWarning;
2497 // ppcoin: should not enter safe mode for longer invalid chain
2498 // ppcoin: if sync-checkpoint is too old do not enter safe mode
2499 if (Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) && !fTestNet)
2502 strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.";
2505 // ppcoin: if detected invalid checkpoint enter safe mode
2506 if (Checkpoints::hashInvalidCheckpoint != 0)
2509 strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.";
2515 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2517 const CAlert& alert = item.second;
2518 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2520 nPriority = alert.nPriority;
2521 strStatusBar = alert.strStatusBar;
2522 if (nPriority > 1000)
2523 strRPC = strStatusBar; // ppcoin: safe mode for high alert
2528 if (strFor == "statusbar")
2529 return strStatusBar;
2530 else if (strFor == "rpc")
2532 assert(!"GetWarnings() : invalid parameter");
2536 bool CAlert::ProcessAlert()
2538 if (!CheckSignature())
2545 // Cancel previous alerts
2546 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2548 const CAlert& alert = (*mi).second;
2551 printf("cancelling alert %d\n", alert.nID);
2552 mapAlerts.erase(mi++);
2554 else if (!alert.IsInEffect())
2556 printf("expiring alert %d\n", alert.nID);
2557 mapAlerts.erase(mi++);
2563 // Check if this alert has been cancelled
2564 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2566 const CAlert& alert = item.second;
2567 if (alert.Cancels(*this))
2569 printf("alert already cancelled by %d\n", alert.nID);
2575 mapAlerts.insert(make_pair(GetHash(), *this));
2578 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2590 //////////////////////////////////////////////////////////////////////////////
2596 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2602 bool txInMap = false;
2605 txInMap = (mempool.exists(inv.hash));
2608 mapOrphanTransactions.count(inv.hash) ||
2609 txdb.ContainsTx(inv.hash);
2613 return mapBlockIndex.count(inv.hash) ||
2614 mapOrphanBlocks.count(inv.hash);
2616 // Don't know what it is, just say we already got one
2623 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2625 static map<CService, vector<unsigned char> > mapReuseKey;
2626 RandAddSeedPerfmon();
2628 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
2629 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2631 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2633 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2641 if (strCommand == "version")
2643 // Each connection can only send one version message
2644 if (pfrom->nVersion != 0)
2646 pfrom->Misbehaving(1);
2654 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2655 if (pfrom->nVersion < MIN_PROTO_VERSION)
2657 // Since February 20, 2012, the protocol is initiated at version 209,
2658 // and earlier versions are no longer supported
2659 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2660 pfrom->fDisconnect = true;
2664 if (pfrom->nVersion == 10300)
2665 pfrom->nVersion = 300;
2667 vRecv >> addrFrom >> nNonce;
2669 vRecv >> pfrom->strSubVer;
2671 vRecv >> pfrom->nStartingHeight;
2673 // Disconnect if we connected to ourself
2674 if (nNonce == nLocalHostNonce && nNonce > 1)
2676 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2677 pfrom->fDisconnect = true;
2681 // ppcoin: record my external IP reported by peer
2682 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
2683 addrSeenByPeer = addrMe;
2685 // Be shy and don't send version until we hear
2686 if (pfrom->fInbound)
2687 pfrom->PushVersion();
2689 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2691 AddTimeData(pfrom->addr, nTime);
2694 pfrom->PushMessage("verack");
2695 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2697 if (!pfrom->fInbound)
2699 // Advertise our address
2700 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() &&
2701 !IsInitialBlockDownload())
2703 CAddress addr(addrLocalHost);
2704 addr.nTime = GetAdjustedTime();
2705 pfrom->PushAddress(addr);
2708 // Get recent addresses
2709 if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2711 pfrom->PushMessage("getaddr");
2712 pfrom->fGetAddr = true;
2714 addrman.Good(pfrom->addr);
2716 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2718 addrman.Add(addrFrom, addrFrom);
2719 addrman.Good(addrFrom);
2723 // Ask the first connected node for block updates
2724 static int nAskedForBlocks = 0;
2725 if (!pfrom->fClient &&
2726 (pfrom->nVersion < NOBLKS_VERSION_START ||
2727 pfrom->nVersion >= NOBLKS_VERSION_END) &&
2728 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2731 pfrom->PushGetBlocks(pindexBest, uint256(0));
2737 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2738 item.second.RelayTo(pfrom);
2741 // ppcoin: relay sync-checkpoint
2743 LOCK(Checkpoints::cs_hashSyncCheckpoint);
2744 if (!Checkpoints::checkpointMessage.IsNull())
2745 Checkpoints::checkpointMessage.RelayTo(pfrom);
2748 pfrom->fSuccessfullyConnected = true;
2750 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2752 cPeerBlockCounts.input(pfrom->nStartingHeight);
2754 // ppcoin: ask for pending sync-checkpoint if any
2755 if (!IsInitialBlockDownload())
2756 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2760 else if (pfrom->nVersion == 0)
2762 // Must have a version message before anything else
2763 pfrom->Misbehaving(1);
2768 else if (strCommand == "verack")
2770 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2774 else if (strCommand == "addr")
2776 vector<CAddress> vAddr;
2779 // Don't want addr from older versions unless seeding
2780 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2782 if (vAddr.size() > 1000)
2784 pfrom->Misbehaving(20);
2785 return error("message addr size() = %d", vAddr.size());
2788 // Store the new addresses
2789 int64 nNow = GetAdjustedTime();
2790 int64 nSince = nNow - 10 * 60;
2791 BOOST_FOREACH(CAddress& addr, vAddr)
2795 // ignore IPv6 for now, since it isn't implemented anyway
2798 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2799 addr.nTime = nNow - 5 * 24 * 60 * 60;
2800 pfrom->AddAddressKnown(addr);
2801 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2803 // Relay to a limited number of other nodes
2806 // Use deterministic randomness to send to the same nodes for 24 hours
2807 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2808 static uint256 hashSalt;
2810 hashSalt = GetRandHash();
2811 int64 hashAddr = addr.GetHash();
2812 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2813 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2814 multimap<uint256, CNode*> mapMix;
2815 BOOST_FOREACH(CNode* pnode, vNodes)
2817 if (pnode->nVersion < CADDR_TIME_VERSION)
2819 unsigned int nPointer;
2820 memcpy(&nPointer, &pnode, sizeof(nPointer));
2821 uint256 hashKey = hashRand ^ nPointer;
2822 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2823 mapMix.insert(make_pair(hashKey, pnode));
2825 int nRelayNodes = 2;
2826 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2827 ((*mi).second)->PushAddress(addr);
2831 addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60);
2832 if (vAddr.size() < 1000)
2833 pfrom->fGetAddr = false;
2837 else if (strCommand == "inv")
2841 if (vInv.size() > 50000)
2843 pfrom->Misbehaving(20);
2844 return error("message inv size() = %d", vInv.size());
2847 // find last block in inv vector
2848 unsigned int nLastBlock = (unsigned int)(-1);
2849 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
2850 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
2851 nLastBlock = vInv.size() - 1 - nInv;
2856 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
2858 const CInv &inv = vInv[nInv];
2862 pfrom->AddInventoryKnown(inv);
2864 bool fAlreadyHave = AlreadyHave(txdb, inv);
2866 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2870 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
2871 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2872 } else if (nInv == nLastBlock) {
2873 // In case we are on a very long side-chain, it is possible that we already have
2874 // the last block in an inv bundle sent in response to getblocks. Try to detect
2875 // this situation and push another getblocks to continue.
2876 std::vector<CInv> vGetData(1,inv);
2877 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
2879 printf("force request: %s\n", inv.ToString().c_str());
2882 // Track requests for our stuff
2883 Inventory(inv.hash);
2888 else if (strCommand == "getdata")
2892 if (vInv.size() > 50000)
2894 pfrom->Misbehaving(20);
2895 return error("message getdata size() = %d", vInv.size());
2898 BOOST_FOREACH(const CInv& inv, vInv)
2902 printf("received getdata for: %s\n", inv.ToString().c_str());
2904 if (inv.type == MSG_BLOCK)
2906 // Send block from disk
2907 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2908 if (mi != mapBlockIndex.end())
2911 block.ReadFromDisk((*mi).second);
2912 pfrom->PushMessage("block", block);
2914 // Trigger them to send a getblocks request for the next batch of inventory
2915 if (inv.hash == pfrom->hashContinue)
2917 // Bypass PushInventory, this must send even if redundant,
2918 // and we want it right after the last block so they don't
2919 // wait for other stuff first.
2920 // ppcoin: send latest proof-of-work block to allow the
2921 // download node to accept as orphan (proof-of-stake
2922 // block might be rejected by stake connection check)
2924 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
2925 pfrom->PushMessage("inv", vInv);
2926 pfrom->hashContinue = 0;
2930 else if (inv.IsKnownType())
2932 // Send stream from relay memory
2935 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2936 if (mi != mapRelay.end())
2937 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2941 // Track requests for our stuff
2942 Inventory(inv.hash);
2947 else if (strCommand == "getblocks")
2949 CBlockLocator locator;
2951 vRecv >> locator >> hashStop;
2953 // Find the last block the caller has in the main chain
2954 CBlockIndex* pindex = locator.GetBlockIndex();
2956 // Send the rest of the chain
2958 pindex = pindex->pnext;
2959 int nLimit = 500 + locator.GetDistanceBack();
2960 unsigned int nBytes = 0;
2961 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2962 for (; pindex; pindex = pindex->pnext)
2964 if (pindex->GetBlockHash() == hashStop)
2966 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2967 // ppcoin: tell downloading node about the latest block if it's
2968 // without risk being rejected due to stake connection check
2969 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
2970 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
2973 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2975 block.ReadFromDisk(pindex, true);
2976 nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
2977 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2979 // When this block is requested, we'll send an inv that'll make them
2980 // getblocks the next batch of inventory.
2981 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2982 pfrom->hashContinue = pindex->GetBlockHash();
2989 else if (strCommand == "getheaders")
2991 CBlockLocator locator;
2993 vRecv >> locator >> hashStop;
2995 CBlockIndex* pindex = NULL;
2996 if (locator.IsNull())
2998 // If locator is null, return the hashStop block
2999 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3000 if (mi == mapBlockIndex.end())
3002 pindex = (*mi).second;
3006 // Find the last block the caller has in the main chain
3007 pindex = locator.GetBlockIndex();
3009 pindex = pindex->pnext;
3012 vector<CBlock> vHeaders;
3014 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3015 for (; pindex; pindex = pindex->pnext)
3017 vHeaders.push_back(pindex->GetBlockHeader());
3018 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3021 pfrom->PushMessage("headers", vHeaders);
3025 else if (strCommand == "tx")
3027 vector<uint256> vWorkQueue;
3028 vector<uint256> vEraseQueue;
3029 CDataStream vMsg(vRecv);
3034 CInv inv(MSG_TX, tx.GetHash());
3035 pfrom->AddInventoryKnown(inv);
3037 bool fMissingInputs = false;
3038 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3040 SyncWithWallets(tx, NULL, true);
3041 RelayMessage(inv, vMsg);
3042 mapAlreadyAskedFor.erase(inv);
3043 vWorkQueue.push_back(inv.hash);
3044 vEraseQueue.push_back(inv.hash);
3046 // Recursively process any orphan transactions that depended on this one
3047 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3049 uint256 hashPrev = vWorkQueue[i];
3050 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3051 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3054 const CDataStream& vMsg = *((*mi).second);
3056 CDataStream(vMsg) >> tx;
3057 CInv inv(MSG_TX, tx.GetHash());
3058 bool fMissingInputs2 = false;
3060 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3062 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3063 SyncWithWallets(tx, NULL, true);
3064 RelayMessage(inv, vMsg);
3065 mapAlreadyAskedFor.erase(inv);
3066 vWorkQueue.push_back(inv.hash);
3067 vEraseQueue.push_back(inv.hash);
3069 else if (!fMissingInputs2)
3072 vEraseQueue.push_back(inv.hash);
3073 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3078 BOOST_FOREACH(uint256 hash, vEraseQueue)
3079 EraseOrphanTx(hash);
3081 else if (fMissingInputs)
3085 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3086 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3088 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3090 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3094 else if (strCommand == "block")
3099 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3102 CInv inv(MSG_BLOCK, block.GetHash());
3103 pfrom->AddInventoryKnown(inv);
3105 if (ProcessBlock(pfrom, &block))
3106 mapAlreadyAskedFor.erase(inv);
3107 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3111 else if (strCommand == "getaddr")
3113 pfrom->vAddrToSend.clear();
3114 vector<CAddress> vAddr = addrman.GetAddr();
3115 BOOST_FOREACH(const CAddress &addr, vAddr)
3116 pfrom->PushAddress(addr);
3120 else if (strCommand == "checkorder")
3125 if (!GetBoolArg("-allowreceivebyip"))
3127 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3134 /// we have a chance to check the order here
3136 // Keep giving the same key to the same ip until they use it
3137 if (!mapReuseKey.count(pfrom->addr))
3138 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3140 // Send back approval of order and pubkey to use
3141 CScript scriptPubKey;
3142 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3143 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3147 else if (strCommand == "reply")
3152 CRequestTracker tracker;
3154 LOCK(pfrom->cs_mapRequests);
3155 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3156 if (mi != pfrom->mapRequests.end())
3158 tracker = (*mi).second;
3159 pfrom->mapRequests.erase(mi);
3162 if (!tracker.IsNull())
3163 tracker.fn(tracker.param1, vRecv);
3167 else if (strCommand == "ping")
3169 if (pfrom->nVersion > BIP0031_VERSION)
3173 // Echo the message back with the nonce. This allows for two useful features:
3175 // 1) A remote node can quickly check if the connection is operational
3176 // 2) Remote nodes can measure the latency of the network thread. If this node
3177 // is overloaded it won't respond to pings quickly and the remote node can
3178 // avoid sending us more work, like chain download requests.
3180 // The nonce stops the remote getting confused between different pings: without
3181 // it, if the remote node sends a ping once per second and this node takes 5
3182 // seconds to respond to each, the 5th ping the remote sends would appear to
3183 // return very quickly.
3184 pfrom->PushMessage("pong", nonce);
3189 else if (strCommand == "alert")
3194 if (alert.ProcessAlert())
3197 pfrom->setKnown.insert(alert.GetHash());
3200 BOOST_FOREACH(CNode* pnode, vNodes)
3201 alert.RelayTo(pnode);
3206 else if (strCommand == "checkpoint")
3208 CSyncCheckpoint checkpoint;
3209 vRecv >> checkpoint;
3211 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3214 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3216 BOOST_FOREACH(CNode* pnode, vNodes)
3217 checkpoint.RelayTo(pnode);
3223 // Ignore unknown commands for extensibility
3227 // Update the last seen time for this node's address
3228 if (pfrom->fNetworkNode)
3229 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3230 AddressCurrentlyConnected(pfrom->addr);
3236 bool ProcessMessages(CNode* pfrom)
3238 CDataStream& vRecv = pfrom->vRecv;
3242 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3246 // (4) message start
3253 unsigned char pchMessageStart[4];
3254 GetMessageStart(pchMessageStart);
3255 static int64 nTimeLastPrintMessageStart = 0;
3256 if (fDebug && GetBoolArg("-printmessagestart") && nTimeLastPrintMessageStart + 30 < GetAdjustedTime())
3258 string strMessageStart((const char *)pchMessageStart, sizeof(pchMessageStart));
3259 vector<unsigned char> vchMessageStart(strMessageStart.begin(), strMessageStart.end());
3260 printf("ProcessMessages : AdjustedTime=%"PRI64d" MessageStart=%s\n", GetAdjustedTime(), HexStr(vchMessageStart).c_str());
3261 nTimeLastPrintMessageStart = GetAdjustedTime();
3266 // Scan for message start
3267 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3268 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3269 if (vRecv.end() - pstart < nHeaderSize)
3271 if ((int)vRecv.size() > nHeaderSize)
3273 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3274 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3278 if (pstart - vRecv.begin() > 0)
3279 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
3280 vRecv.erase(vRecv.begin(), pstart);
3283 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3288 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3291 string strCommand = hdr.GetCommand();
3294 unsigned int nMessageSize = hdr.nMessageSize;
3295 if (nMessageSize > MAX_SIZE)
3297 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3300 if (nMessageSize > vRecv.size())
3302 // Rewind and wait for rest of message
3303 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3308 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3309 unsigned int nChecksum = 0;
3310 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3311 if (nChecksum != hdr.nChecksum)
3313 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3314 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3318 // Copy message to its own buffer
3319 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3320 vRecv.ignore(nMessageSize);
3328 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3333 catch (std::ios_base::failure& e)
3335 if (strstr(e.what(), "end of data"))
3337 // Allow exceptions from underlength message on vRecv
3338 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());
3340 else if (strstr(e.what(), "size too large"))
3342 // Allow exceptions from overlong size
3343 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3347 PrintExceptionContinue(&e, "ProcessMessages()");
3350 catch (std::exception& e) {
3351 PrintExceptionContinue(&e, "ProcessMessages()");
3353 PrintExceptionContinue(NULL, "ProcessMessages()");
3357 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3365 bool SendMessages(CNode* pto, bool fSendTrickle)
3367 TRY_LOCK(cs_main, lockMain);
3369 // Don't send anything until we get their version message
3370 if (pto->nVersion == 0)
3373 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3375 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3377 if (pto->nVersion > BIP0031_VERSION)
3378 pto->PushMessage("ping", nonce);
3380 pto->PushMessage("ping");
3383 // Resend wallet transactions that haven't gotten in a block yet
3384 ResendWalletTransactions();
3386 // Address refresh broadcast
3387 static int64 nLastRebroadcast;
3388 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3392 BOOST_FOREACH(CNode* pnode, vNodes)
3394 // Periodically clear setAddrKnown to allow refresh broadcasts
3395 if (nLastRebroadcast)
3396 pnode->setAddrKnown.clear();
3398 // Rebroadcast our address
3399 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable())
3401 CAddress addr(addrLocalHost);
3402 addr.nTime = GetAdjustedTime();
3403 pnode->PushAddress(addr);
3407 nLastRebroadcast = GetTime();
3415 vector<CAddress> vAddr;
3416 vAddr.reserve(pto->vAddrToSend.size());
3417 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3419 // returns true if wasn't already contained in the set
3420 if (pto->setAddrKnown.insert(addr).second)
3422 vAddr.push_back(addr);
3423 // receiver rejects addr messages larger than 1000
3424 if (vAddr.size() >= 1000)
3426 pto->PushMessage("addr", vAddr);
3431 pto->vAddrToSend.clear();
3433 pto->PushMessage("addr", vAddr);
3438 // Message: inventory
3441 vector<CInv> vInvWait;
3443 LOCK(pto->cs_inventory);
3444 vInv.reserve(pto->vInventoryToSend.size());
3445 vInvWait.reserve(pto->vInventoryToSend.size());
3446 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3448 if (pto->setInventoryKnown.count(inv))
3451 // trickle out tx inv to protect privacy
3452 if (inv.type == MSG_TX && !fSendTrickle)
3454 // 1/4 of tx invs blast to all immediately
3455 static uint256 hashSalt;
3457 hashSalt = GetRandHash();
3458 uint256 hashRand = inv.hash ^ hashSalt;
3459 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3460 bool fTrickleWait = ((hashRand & 3) != 0);
3462 // always trickle our own transactions
3466 if (GetTransaction(inv.hash, wtx))
3468 fTrickleWait = true;
3473 vInvWait.push_back(inv);
3478 // returns true if wasn't already contained in the set
3479 if (pto->setInventoryKnown.insert(inv).second)
3481 vInv.push_back(inv);
3482 if (vInv.size() >= 1000)
3484 pto->PushMessage("inv", vInv);
3489 pto->vInventoryToSend = vInvWait;
3492 pto->PushMessage("inv", vInv);
3498 vector<CInv> vGetData;
3499 int64 nNow = GetTime() * 1000000;
3501 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3503 const CInv& inv = (*pto->mapAskFor.begin()).second;
3504 if (!AlreadyHave(txdb, inv))
3506 printf("sending getdata: %s\n", inv.ToString().c_str());
3507 vGetData.push_back(inv);
3508 if (vGetData.size() >= 1000)
3510 pto->PushMessage("getdata", vGetData);
3514 mapAlreadyAskedFor[inv] = nNow;
3515 pto->mapAskFor.erase(pto->mapAskFor.begin());
3517 if (!vGetData.empty())
3518 pto->PushMessage("getdata", vGetData);
3537 //////////////////////////////////////////////////////////////////////////////
3542 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3544 unsigned char* pdata = (unsigned char*)pbuffer;
3545 unsigned int blocks = 1 + ((len + 8) / 64);
3546 unsigned char* pend = pdata + 64 * blocks;
3547 memset(pdata + len, 0, 64 * blocks - len);
3549 unsigned int bits = len * 8;
3550 pend[-1] = (bits >> 0) & 0xff;
3551 pend[-2] = (bits >> 8) & 0xff;
3552 pend[-3] = (bits >> 16) & 0xff;
3553 pend[-4] = (bits >> 24) & 0xff;
3557 static const unsigned int pSHA256InitState[8] =
3558 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3560 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3563 unsigned char data[64];
3567 for (int i = 0; i < 16; i++)
3568 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3570 for (int i = 0; i < 8; i++)
3571 ctx.h[i] = ((uint32_t*)pinit)[i];
3573 SHA256_Update(&ctx, data, sizeof(data));
3574 for (int i = 0; i < 8; i++)
3575 ((uint32_t*)pstate)[i] = ctx.h[i];
3578 // Some explaining would be appreciated
3583 set<uint256> setDependsOn;
3586 COrphan(CTransaction* ptxIn)
3594 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3595 BOOST_FOREACH(uint256 hash, setDependsOn)
3596 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3601 uint64 nLastBlockTx = 0;
3602 uint64 nLastBlockSize = 0;
3603 int64 nLastCoinStakeSearchInterval = 0;
3606 // fProofOfStake: try (best effort) to make a proof-of-stake block
3607 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
3609 CReserveKey reservekey(pwallet);
3612 auto_ptr<CBlock> pblock(new CBlock());
3616 // Create coinbase tx
3618 txNew.vin.resize(1);
3619 txNew.vin[0].prevout.SetNull();
3620 txNew.vout.resize(1);
3621 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3623 // Add our coinbase tx as first transaction
3624 pblock->vtx.push_back(txNew);
3626 // ppcoin: if coinstake available add coinstake tx
3627 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
3628 CBlockIndex* pindexPrev = pindexBest;
3630 if (fProofOfStake) // attemp to find a coinstake
3632 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
3633 CTransaction txCoinStake;
3634 int64 nSearchTime = txCoinStake.nTime; // search to current time
3635 if (nSearchTime > nLastCoinStakeSearchTime)
3637 if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
3639 if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
3640 { // make sure coinstake would meet timestamp protocol
3641 // as it would be the same as the block timestamp
3642 pblock->vtx[0].vout[0].SetEmpty();
3643 pblock->vtx[0].nTime = txCoinStake.nTime;
3644 pblock->vtx.push_back(txCoinStake);
3647 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
3648 nLastCoinStakeSearchTime = nSearchTime;
3652 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
3654 // Collect memory pool transactions into the block
3657 LOCK2(cs_main, mempool.cs);
3660 // Priority order to process transactions
3661 list<COrphan> vOrphan; // list memory doesn't move
3662 map<uint256, vector<COrphan*> > mapDependers;
3663 multimap<double, CTransaction*> mapPriority;
3664 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3666 CTransaction& tx = (*mi).second;
3667 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
3670 COrphan* porphan = NULL;
3671 double dPriority = 0;
3672 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3674 // Read prev transaction
3675 CTransaction txPrev;
3677 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3679 // Has to wait for dependencies
3682 // Use list for automatic deletion
3683 vOrphan.push_back(COrphan(&tx));
3684 porphan = &vOrphan.back();
3686 mapDependers[txin.prevout.hash].push_back(porphan);
3687 porphan->setDependsOn.insert(txin.prevout.hash);
3690 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3692 // Read block header
3693 int nConf = txindex.GetDepthInMainChain();
3695 dPriority += (double)nValueIn * nConf;
3697 if (fDebug && GetBoolArg("-printpriority"))
3698 printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3701 // Priority is sum(valuein * age) / txsize
3702 dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3705 porphan->dPriority = dPriority;
3707 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3709 if (fDebug && GetBoolArg("-printpriority"))
3711 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3718 // Collect transactions into block
3719 map<uint256, CTxIndex> mapTestPool;
3720 uint64 nBlockSize = 1000;
3721 uint64 nBlockTx = 0;
3722 int nBlockSigOps = 100;
3723 while (!mapPriority.empty())
3725 // Take highest priority transaction off priority queue
3726 CTransaction& tx = *(*mapPriority.begin()).second;
3727 mapPriority.erase(mapPriority.begin());
3730 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3731 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3734 // Legacy limits on sigOps:
3735 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
3736 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3740 if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
3743 // ppcoin: simplify transaction fee - allow free = false
3744 int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
3746 // Connecting shouldn't fail due to dependency on other memory pool transactions
3747 // because we're already processing them in order of dependency
3748 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3749 MapPrevTx mapInputs;
3751 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3754 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3755 if (nTxFees < nMinFee)
3758 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3759 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3762 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3764 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3765 swap(mapTestPool, mapTestPoolTmp);
3768 pblock->vtx.push_back(tx);
3769 nBlockSize += nTxSize;
3771 nBlockSigOps += nTxSigOps;
3774 // Add transactions that depend on this one to the priority queue
3775 uint256 hash = tx.GetHash();
3776 if (mapDependers.count(hash))
3778 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3780 if (!porphan->setDependsOn.empty())
3782 porphan->setDependsOn.erase(hash);
3783 if (porphan->setDependsOn.empty())
3784 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3790 nLastBlockTx = nBlockTx;
3791 nLastBlockSize = nBlockSize;
3792 if (fDebug && GetBoolArg("-printpriority"))
3793 printf("CreateNewBlock(): total size %lu\n", nBlockSize);
3796 if (pblock->IsProofOfWork())
3797 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
3800 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3801 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3802 if (pblock->IsProofOfStake())
3803 pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
3804 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
3805 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
3806 if (pblock->IsProofOfWork())
3807 pblock->UpdateTime(pindexPrev);
3810 return pblock.release();
3814 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3816 // Update nExtraNonce
3817 static uint256 hashPrevBlock;
3818 if (hashPrevBlock != pblock->hashPrevBlock)
3821 hashPrevBlock = pblock->hashPrevBlock;
3825 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
3826 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
3828 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3830 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3834 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3837 // Prebuild hash buffers
3844 uint256 hashPrevBlock;
3845 uint256 hashMerkleRoot;
3848 unsigned int nNonce;
3851 unsigned char pchPadding0[64];
3853 unsigned char pchPadding1[64];
3856 memset(&tmp, 0, sizeof(tmp));
3858 tmp.block.nVersion = pblock->nVersion;
3859 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3860 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3861 tmp.block.nTime = pblock->nTime;
3862 tmp.block.nBits = pblock->nBits;
3863 tmp.block.nNonce = pblock->nNonce;
3865 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3866 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3868 // Byte swap all the input buffer
3869 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3870 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3872 // Precalc the first half of the first hash, which stays constant
3873 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3875 memcpy(pdata, &tmp.block, 128);
3876 memcpy(phash1, &tmp.hash1, 64);
3880 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3882 uint256 hash = pblock->GetHash();
3883 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3885 if (hash > hashTarget && pblock->IsProofOfWork())
3886 return error("BitcoinMiner : proof-of-work not meeting target");
3889 printf("BitcoinMiner:\n");
3890 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3892 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
3893 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3898 if (pblock->hashPrevBlock != hashBestChain)
3899 return error("BitcoinMiner : generated block is stale");
3901 // Remove key from key pool
3902 reservekey.KeepKey();
3904 // Track how many getdata requests this block gets
3906 LOCK(wallet.cs_wallet);
3907 wallet.mapRequestCount[pblock->GetHash()] = 0;
3910 // Process this block the same as if we had received it from another node
3911 if (!ProcessBlock(NULL, pblock))
3912 return error("BitcoinMiner : ProcessBlock, block not accepted");
3918 void static ThreadBitcoinMiner(void* parg);
3920 static bool fGenerateBitcoins = false;
3921 static bool fLimitProcessors = false;
3922 static int nLimitProcessors = -1;
3924 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake)
3926 void *scratchbuf = scrypt_buffer_alloc();
3928 printf("CPUMiner started for proof-of-%s\n", fProofOfStake? "stake" : "work");
3929 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3931 // Each thread has its own key and counter
3932 CReserveKey reservekey(pwallet);
3933 unsigned int nExtraNonce = 0;
3935 while (fGenerateBitcoins || fProofOfStake)
3939 while (vNodes.empty() || IsInitialBlockDownload())
3944 if ((!fGenerateBitcoins) && !fProofOfStake)
3948 while (pwallet->IsLocked())
3950 strMintWarning = strMintMessage;
3953 strMintWarning = "";
3958 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3959 CBlockIndex* pindexPrev = pindexBest;
3961 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
3965 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3969 // ppcoin: if proof-of-stake block found then process block
3970 if (pblock->IsProofOfStake())
3972 if (!pblock->SignBlock(*pwalletMain))
3974 strMintWarning = strMintMessage;
3977 strMintWarning = "";
3978 printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
3979 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3980 CheckWork(pblock.get(), *pwalletMain, reservekey);
3981 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3987 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3991 // Prebuild hash buffers
3993 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3994 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3995 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3997 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3999 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
4000 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
4006 int64 nStart = GetTime();
4007 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4009 unsigned int max_nonce = 0xffff0000;
4010 block_header res_header;
4015 unsigned int nHashesDone = 0;
4016 unsigned int nNonceFound;
4018 nNonceFound = scanhash_scrypt(
4019 (block_header *)&pblock->nVersion,
4027 // Check if something found
4028 if (nNonceFound != (unsigned int) -1)
4030 if (result <= hashTarget)
4033 pblock->nNonce = nNonceFound;
4034 assert(result == pblock->GetHash());
4035 if (!pblock->SignBlock(*pwalletMain))
4037 strMintWarning = strMintMessage;
4040 strMintWarning = "";
4041 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4042 CheckWork(pblock.get(), *pwalletMain, reservekey);
4043 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4049 static int64 nHashCounter;
4050 if (nHPSTimerStart == 0)
4052 nHPSTimerStart = GetTimeMillis();
4056 nHashCounter += nHashesDone;
4057 if (GetTimeMillis() - nHPSTimerStart > 4000)
4059 static CCriticalSection cs;
4062 if (GetTimeMillis() - nHPSTimerStart > 4000)
4064 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
4065 nHPSTimerStart = GetTimeMillis();
4067 static int64 nLogTime;
4068 if (GetTime() - nLogTime > 30 * 60)
4070 nLogTime = GetTime();
4071 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
4072 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
4078 // Check for stop or if block needs to be rebuilt
4081 if (!fGenerateBitcoins)
4083 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4087 if (nBlockNonce >= 0xffff0000)
4089 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4091 if (pindexPrev != pindexBest)
4094 // Update nTime every few seconds
4095 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
4096 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4097 pblock->UpdateTime(pindexPrev);
4098 nBlockTime = ByteReverse(pblock->nTime);
4099 if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
4100 break; // need to update coinbase timestamp
4104 scrypt_buffer_free(scratchbuf);
4107 void static ThreadBitcoinMiner(void* parg)
4109 CWallet* pwallet = (CWallet*)parg;
4112 vnThreadsRunning[THREAD_MINER]++;
4113 BitcoinMiner(pwallet, false);
4114 vnThreadsRunning[THREAD_MINER]--;
4116 catch (std::exception& e) {
4117 vnThreadsRunning[THREAD_MINER]--;
4118 PrintException(&e, "ThreadBitcoinMiner()");
4120 vnThreadsRunning[THREAD_MINER]--;
4121 PrintException(NULL, "ThreadBitcoinMiner()");
4124 if (vnThreadsRunning[THREAD_MINER] == 0)
4126 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4130 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4132 fGenerateBitcoins = fGenerate;
4133 nLimitProcessors = GetArg("-genproclimit", -1);
4134 if (nLimitProcessors == 0)
4135 fGenerateBitcoins = false;
4136 fLimitProcessors = (nLimitProcessors != -1);
4140 int nProcessors = boost::thread::hardware_concurrency();
4141 printf("%d processors\n", nProcessors);
4142 if (nProcessors < 1)
4144 if (fLimitProcessors && nProcessors > nLimitProcessors)
4145 nProcessors = nLimitProcessors;
4146 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4147 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4148 for (int i = 0; i < nAddThreads; i++)
4150 if (!CreateThread(ThreadBitcoinMiner, pwallet))
4151 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");