1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2011-2012 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"
12 #include <boost/algorithm/string/replace.hpp>
13 #include <boost/filesystem.hpp>
14 #include <boost/filesystem/fstream.hpp>
17 using namespace boost;
23 CCriticalSection cs_setpwalletRegistered;
24 set<CWallet*> setpwalletRegistered;
26 CCriticalSection cs_main;
29 unsigned int nTransactionsUpdated = 0;
31 map<uint256, CBlockIndex*> mapBlockIndex;
32 set<pair<COutPoint, unsigned int> > setStakeSeen;
33 uint256 hashGenesisBlock = hashGenesisBlockOfficial;
34 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
35 static CBigNum bnInitialHashTarget(~uint256(0) >> 40);
36 unsigned int nStakeMinAge = STAKE_MIN_AGE;
37 int nCoinbaseMaturity = COINBASE_MATURITY_PPC;
38 CBlockIndex* pindexGenesisBlock = NULL;
40 CBigNum bnBestChainTrust = 0;
41 CBigNum bnBestInvalidTrust = 0;
42 uint256 hashBestChain = 0;
43 CBlockIndex* pindexBest = NULL;
44 int64 nTimeBestReceived = 0;
46 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
48 map<uint256, CBlock*> mapOrphanBlocks;
49 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
50 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
52 map<uint256, CDataStream*> mapOrphanTransactions;
53 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
55 // Constant stuff for coinbase transactions we create:
56 CScript COINBASE_FLAGS;
58 const string strMessageMagic = "PPCoin Signed Message:\n";
64 int64 nTransactionFee = MIN_TX_FEE;
68 //////////////////////////////////////////////////////////////////////////////
70 // dispatching functions
73 // These functions dispatch to one or all registered wallets
76 void RegisterWallet(CWallet* pwalletIn)
79 LOCK(cs_setpwalletRegistered);
80 setpwalletRegistered.insert(pwalletIn);
84 void UnregisterWallet(CWallet* pwalletIn)
87 LOCK(cs_setpwalletRegistered);
88 setpwalletRegistered.erase(pwalletIn);
92 // check whether the passed transaction is from us
93 bool static IsFromMe(CTransaction& tx)
95 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
96 if (pwallet->IsFromMe(tx))
101 // get the wallet transaction with the given hash (if it exists)
102 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
104 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
105 if (pwallet->GetTransaction(hashTx,wtx))
110 // erases transaction with the given hash from all wallets
111 void static EraseFromWallets(uint256 hash)
113 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
114 pwallet->EraseFromWallet(hash);
117 // make sure all wallets know about the given transaction, in the given block
118 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true)
122 // ppcoin: wallets need to refund inputs when disconnecting coinstake
123 if (tx.IsCoinStake())
125 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126 if (pwallet->IsFromMe(tx))
127 pwallet->DisableTransaction(tx);
132 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
133 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
136 // notify wallets about a new best chain
137 void static SetBestChain(const CBlockLocator& loc)
139 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
140 pwallet->SetBestChain(loc);
143 // notify wallets about an updated transaction
144 void static UpdatedTransaction(const uint256& hashTx)
146 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
147 pwallet->UpdatedTransaction(hashTx);
151 void static PrintWallets(const CBlock& block)
153 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
154 pwallet->PrintWallet(block);
157 // notify wallets about an incoming inventory (for request counts)
158 void static Inventory(const uint256& hash)
160 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
161 pwallet->Inventory(hash);
164 // ask wallets to resend their transactions
165 void static ResendWalletTransactions()
167 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
168 pwallet->ResendWalletTransactions();
177 //////////////////////////////////////////////////////////////////////////////
179 // mapOrphanTransactions
182 bool AddOrphanTx(const CDataStream& vMsg)
185 CDataStream(vMsg) >> tx;
186 uint256 hash = tx.GetHash();
187 if (mapOrphanTransactions.count(hash))
190 CDataStream* pvMsg = new CDataStream(vMsg);
192 // Ignore big transactions, to avoid a
193 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
194 // large transaction with a missing parent then we assume
195 // it will rebroadcast it later, after the parent transaction(s)
196 // have been mined or received.
197 // 10,000 orphans, each of which is at most 5,000 bytes big is
198 // at most 500 megabytes of orphans:
199 if (pvMsg->size() > 5000)
201 printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
206 mapOrphanTransactions[hash] = pvMsg;
207 BOOST_FOREACH(const CTxIn& txin, tx.vin)
208 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
210 printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
211 mapOrphanTransactions.size());
215 void static EraseOrphanTx(uint256 hash)
217 if (!mapOrphanTransactions.count(hash))
219 const CDataStream* pvMsg = mapOrphanTransactions[hash];
221 CDataStream(*pvMsg) >> tx;
222 BOOST_FOREACH(const CTxIn& txin, tx.vin)
224 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
225 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
226 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
229 mapOrphanTransactions.erase(hash);
232 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
234 unsigned int nEvicted = 0;
235 while (mapOrphanTransactions.size() > nMaxOrphans)
237 // Evict a random orphan:
238 uint256 randomhash = GetRandHash();
239 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
240 if (it == mapOrphanTransactions.end())
241 it = mapOrphanTransactions.begin();
242 EraseOrphanTx(it->first);
254 //////////////////////////////////////////////////////////////////////////////
256 // CTransaction and CTxIndex
259 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
262 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
264 if (!ReadFromDisk(txindexRet.pos))
266 if (prevout.n >= vout.size())
274 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
277 return ReadFromDisk(txdb, prevout, txindex);
280 bool CTransaction::ReadFromDisk(COutPoint prevout)
284 return ReadFromDisk(txdb, prevout, txindex);
287 bool CTransaction::IsStandard() const
289 BOOST_FOREACH(const CTxIn& txin, vin)
291 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
292 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
293 // ~65-byte public keys, plus a few script ops.
294 if (txin.scriptSig.size() > 500)
296 if (!txin.scriptSig.IsPushOnly())
299 BOOST_FOREACH(const CTxOut& txout, vout)
300 if (!::IsStandard(txout.scriptPubKey))
306 // Check transaction inputs, and make sure any
307 // pay-to-script-hash transactions are evaluating IsStandard scripts
309 // Why bother? To avoid denial-of-service attacks; an attacker
310 // can submit a standard HASH... OP_EQUAL transaction,
311 // which will get accepted into blocks. The redemption
312 // script can be anything; an attacker could use a very
313 // expensive-to-check-upon-redemption script like:
314 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
316 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
319 return true; // Coinbases don't use vin normally
321 for (unsigned int i = 0; i < vin.size(); i++)
323 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
325 vector<vector<unsigned char> > vSolutions;
326 txnouttype whichType;
327 // get the scriptPubKey corresponding to this input:
328 const CScript& prevScript = prev.scriptPubKey;
329 if (!Solver(prevScript, whichType, vSolutions))
331 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
332 if (nArgsExpected < 0)
335 // Transactions with extra stuff in their scriptSigs are
336 // non-standard. Note that this EvalScript() call will
337 // be quick, because if there are any operations
338 // beside "push data" in the scriptSig the
339 // IsStandard() call returns false
340 vector<vector<unsigned char> > stack;
341 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
344 if (whichType == TX_SCRIPTHASH)
348 CScript subscript(stack.back().begin(), stack.back().end());
349 vector<vector<unsigned char> > vSolutions2;
350 txnouttype whichType2;
351 if (!Solver(subscript, whichType2, vSolutions2))
353 if (whichType2 == TX_SCRIPTHASH)
357 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
360 nArgsExpected += tmpExpected;
363 if (stack.size() != (unsigned int)nArgsExpected)
371 CTransaction::GetLegacySigOpCount() const
373 unsigned int nSigOps = 0;
374 BOOST_FOREACH(const CTxIn& txin, vin)
376 nSigOps += txin.scriptSig.GetSigOpCount(false);
378 BOOST_FOREACH(const CTxOut& txout, vout)
380 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
386 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
398 // Load the block this tx is in
400 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
402 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
407 // Update the tx's hashBlock
408 hashBlock = pblock->GetHash();
410 // Locate the transaction
411 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
412 if (pblock->vtx[nIndex] == *(CTransaction*)this)
414 if (nIndex == (int)pblock->vtx.size())
416 vMerkleBranch.clear();
418 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
422 // Fill in merkle branch
423 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
426 // Is the tx in a block that's in the main chain
427 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
428 if (mi == mapBlockIndex.end())
430 CBlockIndex* pindex = (*mi).second;
431 if (!pindex || !pindex->IsInMainChain())
434 return pindexBest->nHeight - pindex->nHeight + 1;
443 bool CTransaction::CheckTransaction() const
445 // Basic checks that don't depend on any context
447 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
449 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
451 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
452 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
454 // Check for negative or overflow output values
456 for (int i = 0; i < vout.size(); i++)
458 const CTxOut& txout = vout[i];
459 if (txout.IsEmpty() && (!IsCoinBase()) && (!IsCoinStake()))
460 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
461 // ppcoin: enforce minimum output amount
462 if ((!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
463 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
464 if (txout.nValue > MAX_MONEY)
465 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
466 nValueOut += txout.nValue;
467 if (!MoneyRange(nValueOut))
468 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
471 // Check for duplicate inputs
472 set<COutPoint> vInOutPoints;
473 BOOST_FOREACH(const CTxIn& txin, vin)
475 if (vInOutPoints.count(txin.prevout))
477 vInOutPoints.insert(txin.prevout);
482 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
483 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
487 BOOST_FOREACH(const CTxIn& txin, vin)
488 if (txin.prevout.IsNull())
489 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
495 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
496 bool* pfMissingInputs)
499 *pfMissingInputs = false;
501 if (!tx.CheckTransaction())
502 return error("CTxMemPool::accept() : CheckTransaction failed");
504 // Coinbase is only valid in a block, not as a loose transaction
506 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
507 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
508 if (tx.IsCoinStake())
509 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
511 // To help v0.1.5 clients who would see it as a negative number
512 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
513 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
515 // Rather not work on nonstandard transactions (unless -testnet)
516 if (!fTestNet && !tx.IsStandard())
517 return error("CTxMemPool::accept() : nonstandard transaction type");
519 // Do we already have it?
520 uint256 hash = tx.GetHash();
523 if (mapTx.count(hash))
527 if (txdb.ContainsTx(hash))
530 // Check for conflicts with in-memory transactions
531 CTransaction* ptxOld = NULL;
532 for (unsigned int i = 0; i < tx.vin.size(); i++)
534 COutPoint outpoint = tx.vin[i].prevout;
535 if (mapNextTx.count(outpoint))
537 // Disable replacement feature for now
540 // Allow replacing with a newer version of the same transaction
543 ptxOld = mapNextTx[outpoint].ptx;
544 if (ptxOld->IsFinal())
546 if (!tx.IsNewerThan(*ptxOld))
548 for (unsigned int i = 0; i < tx.vin.size(); i++)
550 COutPoint outpoint = tx.vin[i].prevout;
551 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
561 map<uint256, CTxIndex> mapUnused;
562 bool fInvalid = false;
563 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
566 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
568 *pfMissingInputs = true;
569 return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
572 // Check for non-standard pay-to-script-hash in inputs
573 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
574 return error("CTxMemPool::accept() : nonstandard transaction input");
576 // Note: if you modify this code to accept non-standard transactions, then
577 // you should add code here to check that the transaction does a
578 // reasonable number of ECDSA signature verifications.
580 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
581 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
583 // Don't accept it if it can't get into a block
584 if (nFees < tx.GetMinFee(1000, false, GMF_RELAY))
585 return error("CTxMemPool::accept() : not enough fees");
587 // Continuously rate-limit free transactions
588 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
589 // be annoying or make other's transactions take longer to confirm.
590 if (nFees < MIN_RELAY_TX_FEE)
592 static CCriticalSection cs;
593 static double dFreeCount;
594 static int64 nLastTime;
595 int64 nNow = GetTime();
599 // Use an exponentially decaying ~10-minute window:
600 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
602 // -limitfreerelay unit is thousand-bytes-per-minute
603 // At default rate it would take over a month to fill 1GB
604 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
605 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
607 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
612 // Check against previous transactions
613 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
614 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
616 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
620 // Store transaction in memory
625 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
631 ///// are we sure this is ok when loading transactions or restoring block txes
632 // If updated, erase old tx from wallet
634 EraseFromWallets(ptxOld->GetHash());
636 printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str());
640 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
642 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
645 bool CTxMemPool::addUnchecked(CTransaction &tx)
647 printf("addUnchecked(): size %lu\n", mapTx.size());
648 // Add to memory pool without checking anything. Don't call this directly,
649 // call CTxMemPool::accept to properly check the transaction first.
652 uint256 hash = tx.GetHash();
654 for (unsigned int i = 0; i < tx.vin.size(); i++)
655 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
656 nTransactionsUpdated++;
662 bool CTxMemPool::remove(CTransaction &tx)
664 // Remove transaction from memory pool
667 uint256 hash = tx.GetHash();
668 if (mapTx.count(hash))
670 BOOST_FOREACH(const CTxIn& txin, tx.vin)
671 mapNextTx.erase(txin.prevout);
673 nTransactionsUpdated++;
684 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
686 if (hashBlock == 0 || nIndex == -1)
689 // Find the block it claims to be in
690 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
691 if (mi == mapBlockIndex.end())
693 CBlockIndex* pindex = (*mi).second;
694 if (!pindex || !pindex->IsInMainChain())
697 // Make sure the merkle branch connects to this block
698 if (!fMerkleVerified)
700 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
702 fMerkleVerified = true;
706 return pindexBest->nHeight - pindex->nHeight + 1;
710 int CMerkleTx::GetBlocksToMaturity() const
712 if (!(IsCoinBase() || IsCoinStake()))
714 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
718 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
722 if (!IsInMainChain() && !ClientConnectInputs())
724 return CTransaction::AcceptToMemoryPool(txdb, false);
728 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
732 bool CMerkleTx::AcceptToMemoryPool()
735 return AcceptToMemoryPool(txdb);
740 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
745 // Add previous supporting transactions first
746 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
748 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
750 uint256 hash = tx.GetHash();
751 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
752 tx.AcceptToMemoryPool(txdb, fCheckInputs);
755 return AcceptToMemoryPool(txdb, fCheckInputs);
760 bool CWalletTx::AcceptWalletTransaction()
763 return AcceptWalletTransaction(txdb);
766 int CTxIndex::GetDepthInMainChain() const
770 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
772 // Find the block in the index
773 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
774 if (mi == mapBlockIndex.end())
776 CBlockIndex* pindex = (*mi).second;
777 if (!pindex || !pindex->IsInMainChain())
779 return 1 + nBestHeight - pindex->nHeight;
791 //////////////////////////////////////////////////////////////////////////////
793 // CBlock and CBlockIndex
796 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
798 if (!fReadTransactions)
800 *this = pindex->GetBlockHeader();
803 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
805 if (GetHash() != pindex->GetBlockHash())
806 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
810 uint256 static GetOrphanRoot(const CBlock* pblock)
812 // Work back to the first block in the orphan chain
813 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
814 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
815 return pblock->GetHash();
818 // ppcoin: find block wanted by given orphan block
819 uint256 WantedByOrphan(const CBlock* pblockOrphan)
821 // Work back to the first block in the orphan chain
822 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
823 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
824 return pblockOrphan->hashPrevBlock;
827 int64 GetProofOfWorkReward(unsigned int nBits)
829 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
831 bnTarget.SetCompact(nBits);
832 CBigNum bnTargetLimit = bnProofOfWorkLimit;
833 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
835 // ppcoin: subsidy is cut in half every 16x multiply of difficulty
836 // A reasonably continuous curve is used to avoid shock to market
837 // (nSubsidyLimit / nSubsidy) ** 4 == bnProofOfWorkLimit / bnTarget
838 CBigNum bnLowerBound = CENT;
839 CBigNum bnUpperBound = bnSubsidyLimit;
840 while (bnLowerBound + CENT <= bnUpperBound)
842 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
843 if (fDebug && GetBoolArg("-printcreation"))
844 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
845 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
846 bnUpperBound = bnMidValue;
848 bnLowerBound = bnMidValue;
851 int64 nSubsidy = bnUpperBound.getuint64();
852 nSubsidy = (nSubsidy / CENT) * CENT;
853 if (fDebug && GetBoolArg("-printcreation"))
854 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
856 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
859 // ppcoin: miner's coin stake is rewarded based on coin age spent (coin-days)
860 int64 GetProofOfStakeReward(int64 nCoinAge)
862 static int64 nRewardCoinYear = CENT; // creation amount per coin-year
863 int64 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
864 if (fDebug && GetBoolArg("-printcreation"))
865 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nCoinAge);
869 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
870 static const int64 nTargetSpacingStake = 10 * 60; // ten minutes
871 static const int64 nTargetSpacingWorkMax = 2 * 60 * 60; // two hours
874 // minimum amount of work that could possibly be required nTime after
875 // minimum work required was nBase
877 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
880 bnResult.SetCompact(nBase);
882 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
884 // Maximum 200% adjustment per day...
886 nTime -= 24 * 60 * 60;
888 if (bnResult > bnProofOfWorkLimit)
889 bnResult = bnProofOfWorkLimit;
890 return bnResult.GetCompact();
893 // ppcoin: find last block index up to pindex
894 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
896 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
897 pindex = pindex->pprev;
901 unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
903 if (pindexLast == NULL)
904 return bnProofOfWorkLimit.GetCompact(); // genesis block
906 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
907 if (pindexPrev->pprev == NULL)
908 return bnInitialHashTarget.GetCompact(); // first block
909 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
910 if (pindexPrevPrev->pprev == NULL)
911 return bnInitialHashTarget.GetCompact(); // second block
913 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
915 // ppcoin: target change every block
916 // ppcoin: retarget with exponential moving toward target spacing
918 bnNew.SetCompact(pindexPrev->nBits);
919 int64 nTargetSpacing = fProofOfStake? nTargetSpacingStake : min(nTargetSpacingWorkMax, nTargetSpacingStake * (1 + pindexLast->nHeight - pindexPrev->nHeight));
920 int64 nInterval = nTargetTimespan / nTargetSpacing;
921 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
922 bnNew /= ((nInterval + 1) * nTargetSpacing);
924 if (bnNew > bnProofOfWorkLimit)
925 bnNew = bnProofOfWorkLimit;
927 return bnNew.GetCompact();
930 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
933 bnTarget.SetCompact(nBits);
936 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
937 return error("CheckProofOfWork() : nBits below minimum work");
939 // Check proof of work matches claimed amount
940 if (hash > bnTarget.getuint256())
941 return error("CheckProofOfWork() : hash doesn't match nBits");
946 // Return maximum amount of blocks that other nodes claim to have
947 int GetNumBlocksOfPeers()
949 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
952 bool IsInitialBlockDownload()
954 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
956 static int64 nLastUpdate;
957 static CBlockIndex* pindexLastBest;
958 if (pindexBest != pindexLastBest)
960 pindexLastBest = pindexBest;
961 nLastUpdate = GetTime();
963 return (GetTime() - nLastUpdate < 10 &&
964 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
967 void static InvalidChainFound(CBlockIndex* pindexNew)
969 if (pindexNew->bnChainTrust > bnBestInvalidTrust)
971 bnBestInvalidTrust = pindexNew->bnChainTrust;
972 CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust);
975 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());
976 printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(bnBestChainTrust).ToString().c_str());
977 // ppcoin: should not enter safe mode for longer invalid chain
980 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
982 nTime = max(GetBlockTime(), GetAdjustedTime());
995 bool CTransaction::DisconnectInputs(CTxDB& txdb)
997 // Relinquish previous transactions' spent pointers
1000 BOOST_FOREACH(const CTxIn& txin, vin)
1002 COutPoint prevout = txin.prevout;
1004 // Get prev txindex from disk
1006 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1007 return error("DisconnectInputs() : ReadTxIndex failed");
1009 if (prevout.n >= txindex.vSpent.size())
1010 return error("DisconnectInputs() : prevout.n out of range");
1012 // Mark outpoint as not spent
1013 txindex.vSpent[prevout.n].SetNull();
1016 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1017 return error("DisconnectInputs() : UpdateTxIndex failed");
1021 // Remove transaction from index
1022 // This can fail if a duplicate of this transaction was in a chain that got
1023 // reorganized away. This is only possible if this transaction was completely
1024 // spent, so erasing it would be a no-op anway.
1025 txdb.EraseTxIndex(*this);
1031 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1032 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1034 // FetchInputs can return false either because we just haven't seen some inputs
1035 // (in which case the transaction should be stored as an orphan)
1036 // or because the transaction is malformed (in which case the transaction should
1037 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1041 return true; // Coinbase transactions have no inputs to fetch.
1043 for (unsigned int i = 0; i < vin.size(); i++)
1045 COutPoint prevout = vin[i].prevout;
1046 if (inputsRet.count(prevout.hash))
1047 continue; // Got it already
1050 CTxIndex& txindex = inputsRet[prevout.hash].first;
1052 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1054 // Get txindex from current proposed changes
1055 txindex = mapTestPool.find(prevout.hash)->second;
1059 // Read txindex from txdb
1060 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1062 if (!fFound && (fBlock || fMiner))
1063 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());
1066 CTransaction& txPrev = inputsRet[prevout.hash].second;
1067 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1069 // Get prev tx from single transactions in memory
1072 if (!mempool.exists(prevout.hash))
1073 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());
1074 txPrev = mempool.lookup(prevout.hash);
1077 txindex.vSpent.resize(txPrev.vout.size());
1081 // Get prev tx from disk
1082 if (!txPrev.ReadFromDisk(txindex.pos))
1083 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1087 // Make sure all prevout.n's are valid:
1088 for (unsigned int i = 0; i < vin.size(); i++)
1090 const COutPoint prevout = vin[i].prevout;
1091 assert(inputsRet.count(prevout.hash) != 0);
1092 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1093 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1094 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1096 // Revisit this if/when transaction replacement is implemented and allows
1099 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()));
1106 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1108 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1109 if (mi == inputs.end())
1110 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1112 const CTransaction& txPrev = (mi->second).second;
1113 if (input.prevout.n >= txPrev.vout.size())
1114 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1116 return txPrev.vout[input.prevout.n];
1119 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1125 for (unsigned int i = 0; i < vin.size(); i++)
1127 nResult += GetOutputFor(vin[i], inputs).nValue;
1133 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1138 unsigned int nSigOps = 0;
1139 for (unsigned int i = 0; i < vin.size(); i++)
1141 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1142 if (prevout.scriptPubKey.IsPayToScriptHash())
1143 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1148 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1149 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1150 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1152 // Take over previous transactions' spent pointers
1153 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1154 // fMiner is true when called from the internal bitcoin miner
1155 // ... both are false when called from CTransaction::AcceptToMemoryPool
1160 for (unsigned int i = 0; i < vin.size(); i++)
1162 COutPoint prevout = vin[i].prevout;
1163 assert(inputs.count(prevout.hash) > 0);
1164 CTxIndex& txindex = inputs[prevout.hash].first;
1165 CTransaction& txPrev = inputs[prevout.hash].second;
1167 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1168 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()));
1170 // If prev is coinbase/coinstake, check that it's matured
1171 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1172 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1173 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1174 return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight);
1176 // ppcoin: check transaction timestamp
1177 if (txPrev.nTime > nTime)
1178 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1180 // Check for negative or overflow input values
1181 nValueIn += txPrev.vout[prevout.n].nValue;
1182 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1183 return DoS(100, error("ConnectInputs() : txin values out of range"));
1186 // The first loop above does all the inexpensive checks.
1187 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1188 // Helps prevent CPU exhaustion attacks.
1189 for (unsigned int i = 0; i < vin.size(); i++)
1191 COutPoint prevout = vin[i].prevout;
1192 assert(inputs.count(prevout.hash) > 0);
1193 CTxIndex& txindex = inputs[prevout.hash].first;
1194 CTransaction& txPrev = inputs[prevout.hash].second;
1196 // Check for conflicts (double-spend)
1197 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1198 // for an attacker to attempt to split the network.
1199 if (!txindex.vSpent[prevout.n].IsNull())
1200 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());
1202 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1203 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1204 // still computed and checked, and any change will be caught at the next checkpoint.
1205 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1208 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1210 // only during transition phase for P2SH: do not invoke anti-DoS code for
1211 // potentially old clients relaying bad P2SH transactions
1212 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1213 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1215 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1219 // Mark outpoints as spent
1220 txindex.vSpent[prevout.n] = posThisTx;
1223 if (fBlock || fMiner)
1225 mapTestPool[prevout.hash] = txindex;
1231 // ppcoin: coin stake tx earns reward instead of paying fee
1233 if (!GetCoinAge(txdb, nCoinAge))
1234 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1235 int64 nStakeReward = GetValueOut() - nValueIn;
1236 if (nStakeReward > GetProofOfStakeReward(nCoinAge) - GetMinFee() + MIN_TX_FEE)
1237 return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
1241 if (nValueIn < GetValueOut())
1242 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1244 // Tally transaction fees
1245 int64 nTxFee = nValueIn - GetValueOut();
1247 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1248 // ppcoin: enforce transaction fees for every block
1249 if (nTxFee < GetMinFee())
1250 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;
1252 if (!MoneyRange(nFees))
1253 return DoS(100, error("ConnectInputs() : nFees out of range"));
1261 bool CTransaction::ClientConnectInputs()
1266 // Take over previous transactions' spent pointers
1270 for (unsigned int i = 0; i < vin.size(); i++)
1272 // Get prev tx from single transactions in memory
1273 COutPoint prevout = vin[i].prevout;
1274 if (!mempool.exists(prevout.hash))
1276 CTransaction& txPrev = mempool.lookup(prevout.hash);
1278 if (prevout.n >= txPrev.vout.size())
1282 if (!VerifySignature(txPrev, *this, i, true, 0))
1283 return error("ConnectInputs() : VerifySignature failed");
1285 ///// this is redundant with the mempool.mapNextTx stuff,
1286 ///// not sure which I want to get rid of
1287 ///// this has to go away now that posNext is gone
1288 // // Check for conflicts
1289 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1290 // return error("ConnectInputs() : prev tx already used");
1292 // // Flag outpoints as used
1293 // txPrev.vout[prevout.n].posNext = posThisTx;
1295 nValueIn += txPrev.vout[prevout.n].nValue;
1297 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1298 return error("ClientConnectInputs() : txin values out of range");
1300 if (GetValueOut() > nValueIn)
1310 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1312 // Disconnect in reverse order
1313 for (int i = vtx.size()-1; i >= 0; i--)
1314 if (!vtx[i].DisconnectInputs(txdb))
1317 // Update block index on disk without changing it in memory.
1318 // The memory index structure will be changed after the db commits.
1321 CDiskBlockIndex blockindexPrev(pindex->pprev);
1322 blockindexPrev.hashNext = 0;
1323 if (!txdb.WriteBlockIndex(blockindexPrev))
1324 return error("DisconnectBlock() : WriteBlockIndex failed");
1327 // ppcoin: clean up wallet after disconnecting coinstake
1328 BOOST_FOREACH(CTransaction& tx, vtx)
1329 SyncWithWallets(tx, this, false, false);
1334 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1336 // Check it again in case a previous version let a bad block in
1340 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1341 // unless those are already completely spent.
1342 // If such overwrites are allowed, coinbases and transactions depending upon those
1343 // can be duplicated to remove the ability to spend the first instance -- even after
1344 // being sent to another address.
1345 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1346 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1347 // already refuses previously-known transaction id's entirely.
1348 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1349 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1350 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1352 BOOST_FOREACH(CTransaction& tx, vtx)
1354 CTxIndex txindexOld;
1355 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1357 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1364 // BIP16 didn't become active until Apr 1 2012 (Feb 15 on testnet)
1365 int64 nBIP16SwitchTime = fTestNet ? 1329264000 : 1333238400;
1366 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1368 //// issue here: it doesn't know the version
1369 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1371 map<uint256, CTxIndex> mapQueuedChanges;
1374 int64 nValueOut = 0;
1375 unsigned int nSigOps = 0;
1376 BOOST_FOREACH(CTransaction& tx, vtx)
1378 nSigOps += tx.GetLegacySigOpCount();
1379 if (nSigOps > MAX_BLOCK_SIGOPS)
1380 return DoS(100, error("ConnectBlock() : too many sigops"));
1382 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1383 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1385 MapPrevTx mapInputs;
1386 if (tx.IsCoinBase())
1387 nValueOut += tx.GetValueOut();
1391 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1394 if (fStrictPayToScriptHash)
1396 // Add in sigops done by pay-to-script-hash inputs;
1397 // this is to prevent a "rogue miner" from creating
1398 // an incredibly-expensive-to-validate block.
1399 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1400 if (nSigOps > MAX_BLOCK_SIGOPS)
1401 return DoS(100, error("ConnectBlock() : too many sigops"));
1404 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1405 int64 nTxValueOut = tx.GetValueOut();
1406 nValueIn += nTxValueIn;
1407 nValueOut += nTxValueOut;
1408 if (!tx.IsCoinStake())
1409 nFees += nTxValueIn - nTxValueOut;
1411 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1415 mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
1418 // ppcoin: track money supply
1419 pindex->nMint = nValueOut - nValueIn + nFees;
1420 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1422 // Write queued txindex changes
1423 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1425 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1426 return error("ConnectBlock() : UpdateTxIndex failed");
1429 // ppcoin: fees are not collected by miners as in bitcoin
1430 // ppcoin: fees are destroyed to compensate the entire network
1431 if (fDebug && GetBoolArg("-printcreation"))
1432 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1434 // Update block index on disk without changing it in memory.
1435 // The memory index structure will be changed after the db commits.
1438 CDiskBlockIndex blockindexPrev(pindex->pprev);
1439 blockindexPrev.hashNext = pindex->GetBlockHash();
1440 if (!txdb.WriteBlockIndex(blockindexPrev))
1441 return error("ConnectBlock() : WriteBlockIndex failed");
1444 // Watch for transactions paying to me
1445 BOOST_FOREACH(CTransaction& tx, vtx)
1446 SyncWithWallets(tx, this, true);
1451 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1453 printf("REORGANIZE\n");
1456 CBlockIndex* pfork = pindexBest;
1457 CBlockIndex* plonger = pindexNew;
1458 while (pfork != plonger)
1460 while (plonger->nHeight > pfork->nHeight)
1461 if (!(plonger = plonger->pprev))
1462 return error("Reorganize() : plonger->pprev is null");
1463 if (pfork == plonger)
1465 if (!(pfork = pfork->pprev))
1466 return error("Reorganize() : pfork->pprev is null");
1469 // List of what to disconnect
1470 vector<CBlockIndex*> vDisconnect;
1471 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1472 vDisconnect.push_back(pindex);
1474 // List of what to connect
1475 vector<CBlockIndex*> vConnect;
1476 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1477 vConnect.push_back(pindex);
1478 reverse(vConnect.begin(), vConnect.end());
1480 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());
1481 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());
1483 // Disconnect shorter branch
1484 vector<CTransaction> vResurrect;
1485 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1488 if (!block.ReadFromDisk(pindex))
1489 return error("Reorganize() : ReadFromDisk for disconnect failed");
1490 if (!block.DisconnectBlock(txdb, pindex))
1491 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1493 // Queue memory transactions to resurrect
1494 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1495 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1496 vResurrect.push_back(tx);
1499 // Connect longer branch
1500 vector<CTransaction> vDelete;
1501 for (unsigned int i = 0; i < vConnect.size(); i++)
1503 CBlockIndex* pindex = vConnect[i];
1505 if (!block.ReadFromDisk(pindex))
1506 return error("Reorganize() : ReadFromDisk for connect failed");
1507 if (!block.ConnectBlock(txdb, pindex))
1511 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1514 // Queue memory transactions to delete
1515 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1516 vDelete.push_back(tx);
1518 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1519 return error("Reorganize() : WriteHashBestChain failed");
1521 // Make sure it's successfully written to disk before changing memory structure
1522 if (!txdb.TxnCommit())
1523 return error("Reorganize() : TxnCommit failed");
1525 // Disconnect shorter branch
1526 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1528 pindex->pprev->pnext = NULL;
1530 // Connect longer branch
1531 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1533 pindex->pprev->pnext = pindex;
1535 // Resurrect memory transactions that were in the disconnected branch
1536 BOOST_FOREACH(CTransaction& tx, vResurrect)
1537 tx.AcceptToMemoryPool(txdb, false);
1539 // Delete redundant memory transactions that are in the connected branch
1540 BOOST_FOREACH(CTransaction& tx, vDelete)
1543 printf("REORGANIZE: done\n");
1550 runCommand(std::string strCommand)
1552 int nErr = ::system(strCommand.c_str());
1554 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1557 // Called from inside SetBestChain: attaches a block to the new best chain being built
1558 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1560 uint256 hash = GetHash();
1562 // Adding to current best branch
1563 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1566 InvalidChainFound(pindexNew);
1569 if (!txdb.TxnCommit())
1570 return error("SetBestChain() : TxnCommit failed");
1572 // Add to current best branch
1573 pindexNew->pprev->pnext = pindexNew;
1575 // Delete redundant memory transactions
1576 BOOST_FOREACH(CTransaction& tx, vtx)
1582 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1584 uint256 hash = GetHash();
1586 if (!txdb.TxnBegin())
1587 return error("SetBestChain() : TxnBegin failed");
1589 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1591 txdb.WriteHashBestChain(hash);
1592 if (!txdb.TxnCommit())
1593 return error("SetBestChain() : TxnCommit failed");
1594 pindexGenesisBlock = pindexNew;
1596 else if (hashPrevBlock == hashBestChain)
1598 if (!SetBestChainInner(txdb, pindexNew))
1599 return error("SetBestChain() : SetBestChainInner failed");
1603 // the first block in the new chain that will cause it to become the new best chain
1604 CBlockIndex *pindexIntermediate = pindexNew;
1606 // list of blocks that need to be connected afterwards
1607 std::vector<CBlockIndex*> vpindexSecondary;
1609 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1610 // Try to limit how much needs to be done inside
1611 while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust)
1613 vpindexSecondary.push_back(pindexIntermediate);
1614 pindexIntermediate = pindexIntermediate->pprev;
1617 if (!vpindexSecondary.empty())
1618 printf("Postponing %i reconnects\n", vpindexSecondary.size());
1620 // Switch to new best branch
1621 if (!Reorganize(txdb, pindexIntermediate))
1624 InvalidChainFound(pindexNew);
1625 return error("SetBestChain() : Reorganize failed");
1628 // Connect futher blocks
1629 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1632 if (!block.ReadFromDisk(pindex))
1634 printf("SetBestChain() : ReadFromDisk failed\n");
1637 if (!txdb.TxnBegin()) {
1638 printf("SetBestChain() : TxnBegin 2 failed\n");
1641 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1642 if (!block.SetBestChainInner(txdb, pindex))
1647 // Update best block in wallet (so we can detect restored wallets)
1648 bool fIsInitialDownload = IsInitialBlockDownload();
1649 if (!fIsInitialDownload)
1651 const CBlockLocator locator(pindexNew);
1652 ::SetBestChain(locator);
1656 hashBestChain = hash;
1657 pindexBest = pindexNew;
1658 nBestHeight = pindexBest->nHeight;
1659 bnBestChainTrust = pindexNew->bnChainTrust;
1660 nTimeBestReceived = GetTime();
1661 nTransactionsUpdated++;
1662 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());
1664 std::string strCmd = GetArg("-blocknotify", "");
1666 if (!fIsInitialDownload && !strCmd.empty())
1668 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1669 boost::thread t(runCommand, strCmd); // thread runs free
1676 // ppcoin: coinstake must meet hash target according to the protocol:
1677 // kernel (input 0) must meet the formula
1678 // hash(nBits + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDay
1679 // this ensures that the chance of getting a coinstake is proportional to the
1680 // amount of coin age one owns.
1681 // The reason this hash is chosen is the following:
1682 // nBits: encodes all past block timestamps, making computing hash in advance
1684 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
1685 // generate transaction for future advantage
1686 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
1687 // nodes generating coinstake at the same time
1688 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
1690 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
1691 // generating coinstake at the same time
1692 // block/tx hash should not be used here as they can be generated in vast
1693 // quantities so as to generate blocks faster, degrading the system back into
1694 // a proof-of-work situation.
1696 bool CTransaction::CheckProofOfStake(unsigned int nBits) const
1698 CBigNum bnTargetPerCoinDay;
1699 bnTargetPerCoinDay.SetCompact(nBits);
1704 // Kernel (input 0) must match the stake hash target per coin age (nBits)
1705 const CTxIn& txin = vin[0];
1707 // First try finding the previous transaction in database
1709 CTransaction txPrev;
1711 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1712 return false; // previous transaction not in main chain
1714 if (nTime < txPrev.nTime)
1715 return false; // Transaction timestamp violation
1718 if (!VerifySignature(txPrev, *this, 0, true, 0))
1719 return DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", GetHash().ToString().c_str()));
1721 // Read block header
1723 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1724 return false; // unable to read block of previous transaction
1725 if (block.GetBlockTime() + nStakeMinAge > nTime)
1726 return false; // only count coins meeting min age requirement
1728 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1729 CBigNum bnCoinDay = CBigNum(nValueIn) * min(nTime-txPrev.nTime, (unsigned int)STAKE_MAX_AGE) / COIN / (24 * 60 * 60);
1731 CDataStream ss(SER_GETHASH, 0);
1732 ss << nBits << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << txPrev.nTime << txin.prevout.n << nTime;
1733 if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1736 return DoS(100, error("CheckProofOfStake() : check target failed on coinstake %s", GetHash().ToString().c_str()));
1739 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1740 // Only those coins meeting minimum age requirement counts. As those
1741 // transactions not in main chain are not currently indexed so we
1742 // might not find out about their coin age. Older transactions are
1743 // guaranteed to be in main chain by sync-checkpoint. This rule is
1744 // introduced to help nodes establish a consistent view of the coin
1745 // age (trust score) of competing branches.
1746 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1748 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1754 BOOST_FOREACH(const CTxIn& txin, vin)
1756 // First try finding the previous transaction in database
1757 CTransaction txPrev;
1759 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1760 continue; // previous transaction not in main chain
1761 if (nTime < txPrev.nTime)
1762 return false; // Transaction timestamp violation
1764 // Read block header
1766 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1767 return false; // unable to read block of previous transaction
1768 if (block.GetBlockTime() + nStakeMinAge > nTime)
1769 continue; // only count coins meeting min age requirement
1771 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1772 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1774 if (fDebug && GetBoolArg("-printcoinage"))
1775 printf("coin age nValueIn=%-12I64d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1778 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1779 if (fDebug && GetBoolArg("-printcoinage"))
1780 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1781 nCoinAge = bnCoinDay.getuint64();
1785 // ppcoin: total coin age spent in block, in the unit of coin-days.
1786 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1791 BOOST_FOREACH(const CTransaction& tx, vtx)
1794 if (tx.GetCoinAge(txdb, nTxCoinAge))
1795 nCoinAge += nTxCoinAge;
1800 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1802 if (fDebug && GetBoolArg("-printcoinage"))
1803 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1808 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1810 // Check for duplicate
1811 uint256 hash = GetHash();
1812 if (mapBlockIndex.count(hash))
1813 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1815 // Construct new block index object
1816 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1818 return error("AddToBlockIndex() : new CBlockIndex failed");
1819 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1820 if (pindexNew->fProofOfStake)
1821 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
1823 pindexNew->phashBlock = &((*mi).first);
1824 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1825 if (miPrev != mapBlockIndex.end())
1827 pindexNew->pprev = (*miPrev).second;
1828 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1831 // ppcoin: compute chain trust score
1832 pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
1835 if (!txdb.TxnBegin())
1837 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1838 if (!txdb.TxnCommit())
1842 if (pindexNew->bnChainTrust > bnBestChainTrust)
1843 if (!SetBestChain(txdb, pindexNew))
1846 // ppcoin: got mint/moneysupply info in block index, write to db
1847 if (!txdb.TxnBegin())
1849 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1850 if (!txdb.TxnCommit())
1855 if (pindexNew == pindexBest)
1857 // Notify UI to display prev block's coinbase if it was ours
1858 static uint256 hashPrevBestCoinBase;
1859 UpdatedTransaction(hashPrevBestCoinBase);
1860 hashPrevBestCoinBase = vtx[0].GetHash();
1870 bool CBlock::CheckBlock() const
1872 // These are checks that are independent of context
1873 // that can be verified before saving an orphan block.
1876 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
1877 return DoS(100, error("CheckBlock() : size limits failed"));
1879 // Check proof of work matches claimed amount
1880 if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1881 return DoS(50, error("CheckBlock() : proof of work failed"));
1884 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
1885 return error("CheckBlock() : block timestamp too far in the future");
1887 // First transaction must be coinbase, the rest must not be
1888 if (vtx.empty() || !vtx[0].IsCoinBase())
1889 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1890 for (unsigned int i = 1; i < vtx.size(); i++)
1891 if (vtx[i].IsCoinBase())
1892 return DoS(100, error("CheckBlock() : more than one coinbase"));
1894 // ppcoin: only the second transaction can be the optional coinstake
1895 for (int i = 2; i < vtx.size(); i++)
1896 if (vtx[i].IsCoinStake())
1897 return DoS(100, error("CheckBlock() : coinstake in wrong position"));
1899 // ppcoin: coinbase output should be empty if proof-of-stake block
1900 if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty()))
1901 return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
1903 // Check coinbase timestamp
1904 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
1905 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
1907 // Check coinstake timestamp
1908 if (IsProofOfStake() && GetBlockTime() > (int64)vtx[1].nTime + nMaxClockDrift)
1909 return DoS(50, error("CheckBlock() : coinstake timestamp is too early"));
1911 // Check coinbase reward
1912 if (vtx[0].GetValueOut() > (IsProofOfWork()? (GetProofOfWorkReward(nBits) - vtx[0].GetMinFee() + MIN_TX_FEE) : 0))
1913 return DoS(50, error("CheckBlock() : coinbase reward exceeded %s > %s",
1914 FormatMoney(vtx[0].GetValueOut()).c_str(),
1915 FormatMoney(IsProofOfWork()? GetProofOfWorkReward(nBits) : 0).c_str()));
1917 // Check transactions
1918 BOOST_FOREACH(const CTransaction& tx, vtx)
1920 if (!tx.CheckTransaction())
1921 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1922 // ppcoin: check transaction timestamp
1923 if (GetBlockTime() < (int64)tx.nTime)
1924 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
1927 // Check for duplicate txids. This is caught by ConnectInputs(),
1928 // but catching it earlier avoids a potential DoS attack:
1929 set<uint256> uniqueTx;
1930 BOOST_FOREACH(const CTransaction& tx, vtx)
1932 uniqueTx.insert(tx.GetHash());
1934 if (uniqueTx.size() != vtx.size())
1935 return DoS(100, error("CheckBlock() : duplicate transaction"));
1937 unsigned int nSigOps = 0;
1938 BOOST_FOREACH(const CTransaction& tx, vtx)
1940 nSigOps += tx.GetLegacySigOpCount();
1942 if (nSigOps > MAX_BLOCK_SIGOPS)
1943 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1946 if (hashMerkleRoot != BuildMerkleTree())
1947 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1949 // ppcoin: check block signature
1950 if (!CheckBlockSignature())
1951 return DoS(100, error("CheckBlock() : bad block signature"));
1956 bool CBlock::AcceptBlock()
1958 // Check for duplicate
1959 uint256 hash = GetHash();
1960 if (mapBlockIndex.count(hash))
1961 return error("AcceptBlock() : block already in mapBlockIndex");
1963 // Get prev block index
1964 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1965 if (mi == mapBlockIndex.end())
1966 return DoS(10, error("AcceptBlock() : prev block not found"));
1967 CBlockIndex* pindexPrev = (*mi).second;
1968 int nHeight = pindexPrev->nHeight+1;
1970 // Check proof-of-work or proof-of-stake
1971 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
1972 return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake"));
1974 // Check timestamp against prev
1975 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
1976 return error("AcceptBlock() : block's timestamp is too early");
1978 // Check that all transactions are finalized
1979 BOOST_FOREACH(const CTransaction& tx, vtx)
1980 if (!tx.IsFinal(nHeight, GetBlockTime()))
1981 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1983 // Check that the block chain matches the known block chain up to a hardened checkpoint
1984 if (!Checkpoints::CheckHardened(nHeight, hash))
1985 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight));
1987 // ppcoin: check that the block satisfies synchronized checkpoint
1988 if (!Checkpoints::CheckSync(hash, pindexPrev))
1989 return error("AcceptBlock() : rejected by synchronized checkpoint");
1991 // Write block to history file
1992 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
1993 return error("AcceptBlock() : out of disk space");
1994 unsigned int nFile = -1;
1995 unsigned int nBlockPos = 0;
1996 if (!WriteToDisk(nFile, nBlockPos))
1997 return error("AcceptBlock() : WriteToDisk failed");
1998 if (!AddToBlockIndex(nFile, nBlockPos))
1999 return error("AcceptBlock() : AddToBlockIndex failed");
2001 // Relay inventory, but don't relay old inventory during initial block download
2002 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2003 if (hashBestChain == hash)
2006 BOOST_FOREACH(CNode* pnode, vNodes)
2007 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2008 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2011 // ppcoin: check pending sync-checkpoint
2012 Checkpoints::AcceptPendingSyncCheckpoint();
2017 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2019 // Check for duplicate
2020 uint256 hash = pblock->GetHash();
2021 if (mapBlockIndex.count(hash))
2022 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2023 if (mapOrphanBlocks.count(hash))
2024 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2026 // ppcoin: check proof-of-stake
2027 // Limited duplicity on stake: prevents block flood attack
2028 // Duplicate stake allowed only when there is orphan child block
2029 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2030 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());
2032 // Preliminary checks
2033 if (!pblock->CheckBlock())
2034 return error("ProcessBlock() : CheckBlock FAILED");
2036 // ppcoin: verify hash target and signature of coinstake tx
2037 if (pblock->IsProofOfStake() && !pblock->vtx[1].CheckProofOfStake(pblock->nBits))
2039 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2040 return false; // do not error here as we expect this during initial block download
2043 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2044 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2046 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2047 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2049 bnNewBlock.SetCompact(pblock->nBits);
2051 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime));
2053 if (bnNewBlock > bnRequired)
2056 pfrom->Misbehaving(100);
2057 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2061 // ppcoin: ask for pending sync-checkpoint if any
2062 if (!IsInitialBlockDownload())
2063 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2065 // If don't already have its previous block, shunt it off to holding area until we get it
2066 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2068 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2069 CBlock* pblock2 = new CBlock(*pblock);
2070 // ppcoin: check proof-of-stake
2071 if (pblock2->IsProofOfStake())
2073 // Limited duplicity on stake: prevents block flood attack
2074 // Duplicate stake allowed only when there is orphan child block
2075 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2076 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());
2078 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2080 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2081 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2083 // Ask this guy to fill in what we're missing
2086 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2087 // ppcoin: getblocks may not obtain the ancestor block rejected
2088 // earlier by duplicate-stake check so we ask for it again directly
2089 if (!IsInitialBlockDownload())
2090 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2096 if (!pblock->AcceptBlock())
2097 return error("ProcessBlock() : AcceptBlock FAILED");
2099 // Recursively process any orphan blocks that depended on this one
2100 vector<uint256> vWorkQueue;
2101 vWorkQueue.push_back(hash);
2102 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2104 uint256 hashPrev = vWorkQueue[i];
2105 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2106 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2109 CBlock* pblockOrphan = (*mi).second;
2110 if (pblockOrphan->AcceptBlock())
2111 vWorkQueue.push_back(pblockOrphan->GetHash());
2112 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2113 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2114 delete pblockOrphan;
2116 mapOrphanBlocksByPrev.erase(hashPrev);
2119 printf("ProcessBlock: ACCEPTED\n");
2121 // ppcoin: if responsible for sync-checkpoint send it
2122 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2123 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2128 // ppcoin: sign block
2129 bool CBlock::SignBlock(const CKeyStore& keystore)
2131 vector<valtype> vSolutions;
2132 txnouttype whichType;
2133 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
2135 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2137 if (whichType == TX_PUBKEY)
2140 const valtype& vchPubKey = vSolutions[0];
2142 if (!keystore.GetKey(Hash160(vchPubKey), key))
2144 if (key.GetPubKey() != vchPubKey)
2146 return key.Sign(GetHash(), vchBlockSig);
2151 // ppcoin: check block signature
2152 bool CBlock::CheckBlockSignature() const
2154 if (GetHash() == hashGenesisBlock)
2155 return vchBlockSig.empty();
2157 vector<valtype> vSolutions;
2158 txnouttype whichType;
2159 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
2161 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2163 if (whichType == TX_PUBKEY)
2165 const valtype& vchPubKey = vSolutions[0];
2167 if (!key.SetPubKey(vchPubKey))
2169 if (vchBlockSig.empty())
2171 return key.Verify(GetHash(), vchBlockSig);
2181 bool CheckDiskSpace(uint64 nAdditionalBytes)
2183 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2185 // Check for 15MB because database could create another 10MB log file at any time
2186 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
2189 string strMessage = _("Warning: Disk space is low");
2190 strMiscWarning = strMessage;
2191 printf("*** %s\n", strMessage.c_str());
2192 ThreadSafeMessageBox(strMessage, "PPCoin", wxOK | wxICON_EXCLAMATION | wxMODAL);
2199 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2203 FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
2206 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2208 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2217 static unsigned int nCurrentBlockFile = 1;
2219 FILE* AppendBlockFile(unsigned int& nFileRet)
2224 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2227 if (fseek(file, 0, SEEK_END) != 0)
2229 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2230 if (ftell(file) < 0x7F000000 - MAX_SIZE)
2232 nFileRet = nCurrentBlockFile;
2236 nCurrentBlockFile++;
2240 bool LoadBlockIndex(bool fAllowNew)
2244 hashGenesisBlock = hashGenesisBlockTestNet;
2245 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
2246 nStakeMinAge = 60 * 60 * 24; // test net min age is 1 day
2247 nCoinbaseMaturity = 60;
2248 bnInitialHashTarget = CBigNum(~uint256(0) >> 29);
2251 printf("%s Network: genesis=0x%s nBitsLimit=0x%08x nBitsInitial=0x%08x nStakeMinAge=%d nCoinbaseMaturity=%d\n",
2252 fTestNet? "Test" : "PPCoin", hashGenesisBlock.ToString().substr(0, 20).c_str(), bnProofOfWorkLimit.GetCompact(), bnInitialHashTarget.GetCompact(), nStakeMinAge, nCoinbaseMaturity);
2258 if (!txdb.LoadBlockIndex())
2263 // Init with genesis block
2265 if (mapBlockIndex.empty())
2271 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
2272 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2273 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
2274 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
2275 // vMerkleTree: 4a5e1e
2278 const char* pszTimestamp = "Matonis 07-AUG-2012 Parallel Currencies And The Roadmap To Monetary Freedom";
2280 txNew.nTime = 1345083810;
2281 txNew.vin.resize(1);
2282 txNew.vout.resize(1);
2283 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2284 txNew.vout[0].SetEmpty();
2286 block.vtx.push_back(txNew);
2287 block.hashPrevBlock = 0;
2288 block.hashMerkleRoot = block.BuildMerkleTree();
2290 block.nTime = 1345084287;
2291 block.nBits = bnProofOfWorkLimit.GetCompact();
2292 block.nNonce = 2179302059;
2296 block.nTime = 1345090000;
2297 block.nNonce = 122894938;
2301 printf("%s\n", block.GetHash().ToString().c_str());
2302 printf("%s\n", hashGenesisBlock.ToString().c_str());
2303 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
2304 assert(block.hashMerkleRoot == uint256("0x3c2d8f85fab4d17aac558cc648a1a58acff0de6deb890c29985690052c5993c2"));
2306 assert(block.GetHash() == hashGenesisBlock);
2307 assert(block.CheckBlock());
2309 // Start new block file
2311 unsigned int nBlockPos;
2312 if (!block.WriteToDisk(nFile, nBlockPos))
2313 return error("LoadBlockIndex() : writing genesis block to disk failed");
2314 if (!block.AddToBlockIndex(nFile, nBlockPos))
2315 return error("LoadBlockIndex() : genesis block not accepted");
2317 // ppcoin: initialize synchronized checkpoint
2318 if (!Checkpoints::WriteSyncCheckpoint(hashGenesisBlock))
2319 return error("LoadBlockIndex() : failed to init sync checkpoint");
2322 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2325 string strPubKey = "";
2326 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2328 // write checkpoint master key to db
2330 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2331 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2332 if (!txdb.TxnCommit())
2333 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2334 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2335 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2345 void PrintBlockTree()
2347 // precompute tree structure
2348 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2349 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2351 CBlockIndex* pindex = (*mi).second;
2352 mapNext[pindex->pprev].push_back(pindex);
2354 //while (rand() % 3 == 0)
2355 // mapNext[pindex->pprev].push_back(pindex);
2358 vector<pair<int, CBlockIndex*> > vStack;
2359 vStack.push_back(make_pair(0, pindexGenesisBlock));
2362 while (!vStack.empty())
2364 int nCol = vStack.back().first;
2365 CBlockIndex* pindex = vStack.back().second;
2368 // print split or gap
2369 if (nCol > nPrevCol)
2371 for (int i = 0; i < nCol-1; i++)
2375 else if (nCol < nPrevCol)
2377 for (int i = 0; i < nCol; i++)
2384 for (int i = 0; i < nCol; i++)
2389 block.ReadFromDisk(pindex);
2390 printf("%d (%u,%u) %s %08lx %s mint %7s tx %d",
2394 block.GetHash().ToString().c_str(),
2396 DateTimeStrFormat(block.GetBlockTime()).c_str(),
2397 FormatMoney(pindex->nMint).c_str(),
2400 PrintWallets(block);
2402 // put the main timechain first
2403 vector<CBlockIndex*>& vNext = mapNext[pindex];
2404 for (unsigned int i = 0; i < vNext.size(); i++)
2406 if (vNext[i]->pnext)
2408 swap(vNext[0], vNext[i]);
2414 for (unsigned int i = 0; i < vNext.size(); i++)
2415 vStack.push_back(make_pair(nCol+i, vNext[i]));
2428 //////////////////////////////////////////////////////////////////////////////
2433 map<uint256, CAlert> mapAlerts;
2434 CCriticalSection cs_mapAlerts;
2436 static string strMintMessage = _("Info: Minting suspended due to locked wallet.");
2437 static string strMintWarning;
2439 string GetWarnings(string strFor)
2442 string strStatusBar;
2444 if (GetBoolArg("-testsafemode"))
2447 // ppcoin: wallet lock warning for minting
2448 if (strMintWarning != "")
2451 strStatusBar = strMintWarning;
2454 // Misc warnings like out of disk space and clock is wrong
2455 if (strMiscWarning != "")
2458 strStatusBar = strMiscWarning;
2461 // ppcoin: should not enter safe mode for longer invalid chain
2462 // ppcoin: if sync-checkpoint too old enter safe mode
2463 if (Checkpoints::IsMatureSyncCheckpoint() && !fTestNet)
2466 strStatusBar = strRPC = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers of the issue.";
2469 // ppcoin: if detected invalid checkpoint enter safe mode
2470 if (Checkpoints::hashInvalidCheckpoint != 0)
2473 strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers of the issue.";
2479 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2481 const CAlert& alert = item.second;
2482 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2484 nPriority = alert.nPriority;
2485 strStatusBar = alert.strStatusBar;
2486 if (nPriority > 1000)
2487 strRPC = strStatusBar; // ppcoin: safe mode for high alert
2492 if (strFor == "statusbar")
2493 return strStatusBar;
2494 else if (strFor == "rpc")
2496 assert(!"GetWarnings() : invalid parameter");
2500 bool CAlert::ProcessAlert()
2502 if (!CheckSignature())
2509 // Cancel previous alerts
2510 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2512 const CAlert& alert = (*mi).second;
2515 printf("cancelling alert %d\n", alert.nID);
2516 mapAlerts.erase(mi++);
2518 else if (!alert.IsInEffect())
2520 printf("expiring alert %d\n", alert.nID);
2521 mapAlerts.erase(mi++);
2527 // Check if this alert has been cancelled
2528 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2530 const CAlert& alert = item.second;
2531 if (alert.Cancels(*this))
2533 printf("alert already cancelled by %d\n", alert.nID);
2539 mapAlerts.insert(make_pair(GetHash(), *this));
2542 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2554 //////////////////////////////////////////////////////////////////////////////
2560 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2566 bool txInMap = false;
2569 txInMap = (mempool.exists(inv.hash));
2572 mapOrphanTransactions.count(inv.hash) ||
2573 txdb.ContainsTx(inv.hash);
2577 return mapBlockIndex.count(inv.hash) ||
2578 mapOrphanBlocks.count(inv.hash);
2580 // Don't know what it is, just say we already got one
2587 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2589 static map<CService, vector<unsigned char> > mapReuseKey;
2590 RandAddSeedPerfmon();
2592 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
2593 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2595 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2597 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2605 if (strCommand == "version")
2607 // Each connection can only send one version message
2608 if (pfrom->nVersion != 0)
2610 pfrom->Misbehaving(1);
2618 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2619 if (pfrom->nVersion < MIN_PROTO_VERSION)
2621 // Since February 20, 2012, the protocol is initiated at version 209,
2622 // and earlier versions are no longer supported
2623 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2624 pfrom->fDisconnect = true;
2628 if (pfrom->nVersion == 10300)
2629 pfrom->nVersion = 300;
2631 vRecv >> addrFrom >> nNonce;
2633 vRecv >> pfrom->strSubVer;
2635 vRecv >> pfrom->nStartingHeight;
2637 // Disconnect if we connected to ourself
2638 if (nNonce == nLocalHostNonce && nNonce > 1)
2640 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2641 pfrom->fDisconnect = true;
2645 // ppcoin: record my external IP reported by peer
2646 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
2647 addrSeenByPeer = addrMe;
2649 // Be shy and don't send version until we hear
2650 if (pfrom->fInbound)
2651 pfrom->PushVersion();
2653 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2655 AddTimeData(pfrom->addr, nTime);
2658 pfrom->PushMessage("verack");
2659 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2661 if (!pfrom->fInbound)
2663 // Advertise our address
2664 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() &&
2665 !IsInitialBlockDownload())
2667 CAddress addr(addrLocalHost);
2668 addr.nTime = GetAdjustedTime();
2669 pfrom->PushAddress(addr);
2672 // Get recent addresses
2673 if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2675 pfrom->PushMessage("getaddr");
2676 pfrom->fGetAddr = true;
2678 addrman.Good(pfrom->addr);
2680 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2682 addrman.Add(addrFrom, addrFrom);
2683 addrman.Good(addrFrom);
2687 // Ask the first connected node for block updates
2688 static int nAskedForBlocks = 0;
2689 if (!pfrom->fClient &&
2690 (pfrom->nVersion < NOBLKS_VERSION_START ||
2691 pfrom->nVersion >= NOBLKS_VERSION_END) &&
2692 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2695 pfrom->PushGetBlocks(pindexBest, uint256(0));
2701 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2702 item.second.RelayTo(pfrom);
2705 // ppcoin: relay sync-checkpoint
2707 LOCK(Checkpoints::cs_hashSyncCheckpoint);
2708 if (!Checkpoints::checkpointMessage.IsNull())
2709 Checkpoints::checkpointMessage.RelayTo(pfrom);
2712 pfrom->fSuccessfullyConnected = true;
2714 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2716 cPeerBlockCounts.input(pfrom->nStartingHeight);
2718 // ppcoin: ask for pending sync-checkpoint if any
2719 if (!IsInitialBlockDownload())
2720 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2724 else if (pfrom->nVersion == 0)
2726 // Must have a version message before anything else
2727 pfrom->Misbehaving(1);
2732 else if (strCommand == "verack")
2734 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2738 else if (strCommand == "addr")
2740 vector<CAddress> vAddr;
2743 // Don't want addr from older versions unless seeding
2744 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2746 if (vAddr.size() > 1000)
2748 pfrom->Misbehaving(20);
2749 return error("message addr size() = %d", vAddr.size());
2752 // Store the new addresses
2753 int64 nNow = GetAdjustedTime();
2754 int64 nSince = nNow - 10 * 60;
2755 BOOST_FOREACH(CAddress& addr, vAddr)
2759 // ignore IPv6 for now, since it isn't implemented anyway
2762 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2763 addr.nTime = nNow - 5 * 24 * 60 * 60;
2764 pfrom->AddAddressKnown(addr);
2765 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2767 // Relay to a limited number of other nodes
2770 // Use deterministic randomness to send to the same nodes for 24 hours
2771 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2772 static uint256 hashSalt;
2774 hashSalt = GetRandHash();
2775 int64 hashAddr = addr.GetHash();
2776 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2777 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2778 multimap<uint256, CNode*> mapMix;
2779 BOOST_FOREACH(CNode* pnode, vNodes)
2781 if (pnode->nVersion < CADDR_TIME_VERSION)
2783 unsigned int nPointer;
2784 memcpy(&nPointer, &pnode, sizeof(nPointer));
2785 uint256 hashKey = hashRand ^ nPointer;
2786 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2787 mapMix.insert(make_pair(hashKey, pnode));
2789 int nRelayNodes = 2;
2790 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2791 ((*mi).second)->PushAddress(addr);
2795 addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60);
2796 if (vAddr.size() < 1000)
2797 pfrom->fGetAddr = false;
2801 else if (strCommand == "inv")
2805 if (vInv.size() > 50000)
2807 pfrom->Misbehaving(20);
2808 return error("message inv size() = %d", vInv.size());
2811 // find last block in inv vector
2812 unsigned int nLastBlock = (unsigned int)(-1);
2813 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
2814 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
2815 nLastBlock = vInv.size() - 1 - nInv;
2820 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
2822 const CInv &inv = vInv[nInv];
2826 pfrom->AddInventoryKnown(inv);
2828 bool fAlreadyHave = AlreadyHave(txdb, inv);
2830 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2834 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
2835 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2836 } else if (nInv == nLastBlock) {
2837 // In case we are on a very long side-chain, it is possible that we already have
2838 // the last block in an inv bundle sent in response to getblocks. Try to detect
2839 // this situation and push another getblocks to continue.
2840 std::vector<CInv> vGetData(1,inv);
2841 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
2843 printf("force request: %s\n", inv.ToString().c_str());
2846 // Track requests for our stuff
2847 Inventory(inv.hash);
2852 else if (strCommand == "getdata")
2856 if (vInv.size() > 50000)
2858 pfrom->Misbehaving(20);
2859 return error("message getdata size() = %d", vInv.size());
2862 BOOST_FOREACH(const CInv& inv, vInv)
2866 printf("received getdata for: %s\n", inv.ToString().c_str());
2868 if (inv.type == MSG_BLOCK)
2870 // Send block from disk
2871 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2872 if (mi != mapBlockIndex.end())
2875 block.ReadFromDisk((*mi).second);
2876 pfrom->PushMessage("block", block);
2878 // Trigger them to send a getblocks request for the next batch of inventory
2879 if (inv.hash == pfrom->hashContinue)
2881 // Bypass PushInventory, this must send even if redundant,
2882 // and we want it right after the last block so they don't
2883 // wait for other stuff first.
2884 // ppcoin: send latest proof-of-work block to allow the
2885 // download node to accept as orphan (proof-of-stake
2886 // block might be rejected by stake connection check)
2888 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
2889 pfrom->PushMessage("inv", vInv);
2890 pfrom->hashContinue = 0;
2894 else if (inv.IsKnownType())
2896 // Send stream from relay memory
2899 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2900 if (mi != mapRelay.end())
2901 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2905 // Track requests for our stuff
2906 Inventory(inv.hash);
2911 else if (strCommand == "getblocks")
2913 CBlockLocator locator;
2915 vRecv >> locator >> hashStop;
2917 // Find the last block the caller has in the main chain
2918 CBlockIndex* pindex = locator.GetBlockIndex();
2920 // Send the rest of the chain
2922 pindex = pindex->pnext;
2923 int nLimit = 500 + locator.GetDistanceBack();
2924 unsigned int nBytes = 0;
2925 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2926 for (; pindex; pindex = pindex->pnext)
2928 if (pindex->GetBlockHash() == hashStop)
2930 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2931 // ppcoin: tell downloading node about the latest block if it's
2932 // without risk being rejected due to stake connection check
2933 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
2934 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
2937 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2939 block.ReadFromDisk(pindex, true);
2940 nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
2941 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2943 // When this block is requested, we'll send an inv that'll make them
2944 // getblocks the next batch of inventory.
2945 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2946 pfrom->hashContinue = pindex->GetBlockHash();
2953 else if (strCommand == "getheaders")
2955 CBlockLocator locator;
2957 vRecv >> locator >> hashStop;
2959 CBlockIndex* pindex = NULL;
2960 if (locator.IsNull())
2962 // If locator is null, return the hashStop block
2963 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2964 if (mi == mapBlockIndex.end())
2966 pindex = (*mi).second;
2970 // Find the last block the caller has in the main chain
2971 pindex = locator.GetBlockIndex();
2973 pindex = pindex->pnext;
2976 vector<CBlock> vHeaders;
2978 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
2979 for (; pindex; pindex = pindex->pnext)
2981 vHeaders.push_back(pindex->GetBlockHeader());
2982 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2985 pfrom->PushMessage("headers", vHeaders);
2989 else if (strCommand == "tx")
2991 vector<uint256> vWorkQueue;
2992 vector<uint256> vEraseQueue;
2993 CDataStream vMsg(vRecv);
2998 CInv inv(MSG_TX, tx.GetHash());
2999 pfrom->AddInventoryKnown(inv);
3001 bool fMissingInputs = false;
3002 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3004 SyncWithWallets(tx, NULL, true);
3005 RelayMessage(inv, vMsg);
3006 mapAlreadyAskedFor.erase(inv);
3007 vWorkQueue.push_back(inv.hash);
3008 vEraseQueue.push_back(inv.hash);
3010 // Recursively process any orphan transactions that depended on this one
3011 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3013 uint256 hashPrev = vWorkQueue[i];
3014 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3015 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3018 const CDataStream& vMsg = *((*mi).second);
3020 CDataStream(vMsg) >> tx;
3021 CInv inv(MSG_TX, tx.GetHash());
3022 bool fMissingInputs2 = false;
3024 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3026 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3027 SyncWithWallets(tx, NULL, true);
3028 RelayMessage(inv, vMsg);
3029 mapAlreadyAskedFor.erase(inv);
3030 vWorkQueue.push_back(inv.hash);
3031 vEraseQueue.push_back(inv.hash);
3033 else if (!fMissingInputs2)
3036 vEraseQueue.push_back(inv.hash);
3037 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3042 BOOST_FOREACH(uint256 hash, vEraseQueue)
3043 EraseOrphanTx(hash);
3045 else if (fMissingInputs)
3049 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3050 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3052 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3054 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3058 else if (strCommand == "block")
3063 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3066 CInv inv(MSG_BLOCK, block.GetHash());
3067 pfrom->AddInventoryKnown(inv);
3069 if (ProcessBlock(pfrom, &block))
3070 mapAlreadyAskedFor.erase(inv);
3071 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3075 else if (strCommand == "getaddr")
3077 pfrom->vAddrToSend.clear();
3078 vector<CAddress> vAddr = addrman.GetAddr();
3079 BOOST_FOREACH(const CAddress &addr, vAddr)
3080 pfrom->PushAddress(addr);
3084 else if (strCommand == "checkorder")
3089 if (!GetBoolArg("-allowreceivebyip"))
3091 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3098 /// we have a chance to check the order here
3100 // Keep giving the same key to the same ip until they use it
3101 if (!mapReuseKey.count(pfrom->addr))
3102 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3104 // Send back approval of order and pubkey to use
3105 CScript scriptPubKey;
3106 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3107 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3111 else if (strCommand == "reply")
3116 CRequestTracker tracker;
3118 LOCK(pfrom->cs_mapRequests);
3119 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3120 if (mi != pfrom->mapRequests.end())
3122 tracker = (*mi).second;
3123 pfrom->mapRequests.erase(mi);
3126 if (!tracker.IsNull())
3127 tracker.fn(tracker.param1, vRecv);
3131 else if (strCommand == "ping")
3133 if (pfrom->nVersion > BIP0031_VERSION)
3137 // Echo the message back with the nonce. This allows for two useful features:
3139 // 1) A remote node can quickly check if the connection is operational
3140 // 2) Remote nodes can measure the latency of the network thread. If this node
3141 // is overloaded it won't respond to pings quickly and the remote node can
3142 // avoid sending us more work, like chain download requests.
3144 // The nonce stops the remote getting confused between different pings: without
3145 // it, if the remote node sends a ping once per second and this node takes 5
3146 // seconds to respond to each, the 5th ping the remote sends would appear to
3147 // return very quickly.
3148 pfrom->PushMessage("pong", nonce);
3153 else if (strCommand == "alert")
3158 if (alert.ProcessAlert())
3161 pfrom->setKnown.insert(alert.GetHash());
3164 BOOST_FOREACH(CNode* pnode, vNodes)
3165 alert.RelayTo(pnode);
3170 else if (strCommand == "checkpoint")
3172 CSyncCheckpoint checkpoint;
3173 vRecv >> checkpoint;
3175 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3178 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3180 BOOST_FOREACH(CNode* pnode, vNodes)
3181 checkpoint.RelayTo(pnode);
3187 // Ignore unknown commands for extensibility
3191 // Update the last seen time for this node's address
3192 if (pfrom->fNetworkNode)
3193 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3194 AddressCurrentlyConnected(pfrom->addr);
3200 bool ProcessMessages(CNode* pfrom)
3202 CDataStream& vRecv = pfrom->vRecv;
3206 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3210 // (4) message start
3217 unsigned char pchMessageStart[4];
3218 GetMessageStart(pchMessageStart);
3219 static int64 nTimeLastPrintMessageStart = 0;
3220 if (fDebug && GetBoolArg("-printmessagestart") && nTimeLastPrintMessageStart + 30 < GetAdjustedTime())
3222 string strMessageStart((const char *)pchMessageStart, sizeof(pchMessageStart));
3223 vector<unsigned char> vchMessageStart(strMessageStart.begin(), strMessageStart.end());
3224 printf("ProcessMessages : AdjustedTime=%"PRI64d" MessageStart=%s\n", GetAdjustedTime(), HexStr(vchMessageStart).c_str());
3225 nTimeLastPrintMessageStart = GetAdjustedTime();
3230 // Scan for message start
3231 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3232 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3233 if (vRecv.end() - pstart < nHeaderSize)
3235 if ((int)vRecv.size() > nHeaderSize)
3237 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3238 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3242 if (pstart - vRecv.begin() > 0)
3243 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
3244 vRecv.erase(vRecv.begin(), pstart);
3247 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3252 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3255 string strCommand = hdr.GetCommand();
3258 unsigned int nMessageSize = hdr.nMessageSize;
3259 if (nMessageSize > MAX_SIZE)
3261 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3264 if (nMessageSize > vRecv.size())
3266 // Rewind and wait for rest of message
3267 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3272 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3273 unsigned int nChecksum = 0;
3274 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3275 if (nChecksum != hdr.nChecksum)
3277 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3278 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3282 // Copy message to its own buffer
3283 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3284 vRecv.ignore(nMessageSize);
3292 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3297 catch (std::ios_base::failure& e)
3299 if (strstr(e.what(), "end of data"))
3301 // Allow exceptions from underlength message on vRecv
3302 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());
3304 else if (strstr(e.what(), "size too large"))
3306 // Allow exceptions from overlong size
3307 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3311 PrintExceptionContinue(&e, "ProcessMessages()");
3314 catch (std::exception& e) {
3315 PrintExceptionContinue(&e, "ProcessMessages()");
3317 PrintExceptionContinue(NULL, "ProcessMessages()");
3321 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3329 bool SendMessages(CNode* pto, bool fSendTrickle)
3331 TRY_LOCK(cs_main, lockMain);
3333 // Don't send anything until we get their version message
3334 if (pto->nVersion == 0)
3337 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3339 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3341 if (pto->nVersion > BIP0031_VERSION)
3342 pto->PushMessage("ping", nonce);
3344 pto->PushMessage("ping");
3347 // Resend wallet transactions that haven't gotten in a block yet
3348 ResendWalletTransactions();
3350 // Address refresh broadcast
3351 static int64 nLastRebroadcast;
3352 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3356 BOOST_FOREACH(CNode* pnode, vNodes)
3358 // Periodically clear setAddrKnown to allow refresh broadcasts
3359 if (nLastRebroadcast)
3360 pnode->setAddrKnown.clear();
3362 // Rebroadcast our address
3363 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable())
3365 CAddress addr(addrLocalHost);
3366 addr.nTime = GetAdjustedTime();
3367 pnode->PushAddress(addr);
3371 nLastRebroadcast = GetTime();
3379 vector<CAddress> vAddr;
3380 vAddr.reserve(pto->vAddrToSend.size());
3381 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3383 // returns true if wasn't already contained in the set
3384 if (pto->setAddrKnown.insert(addr).second)
3386 vAddr.push_back(addr);
3387 // receiver rejects addr messages larger than 1000
3388 if (vAddr.size() >= 1000)
3390 pto->PushMessage("addr", vAddr);
3395 pto->vAddrToSend.clear();
3397 pto->PushMessage("addr", vAddr);
3402 // Message: inventory
3405 vector<CInv> vInvWait;
3407 LOCK(pto->cs_inventory);
3408 vInv.reserve(pto->vInventoryToSend.size());
3409 vInvWait.reserve(pto->vInventoryToSend.size());
3410 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3412 if (pto->setInventoryKnown.count(inv))
3415 // trickle out tx inv to protect privacy
3416 if (inv.type == MSG_TX && !fSendTrickle)
3418 // 1/4 of tx invs blast to all immediately
3419 static uint256 hashSalt;
3421 hashSalt = GetRandHash();
3422 uint256 hashRand = inv.hash ^ hashSalt;
3423 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3424 bool fTrickleWait = ((hashRand & 3) != 0);
3426 // always trickle our own transactions
3430 if (GetTransaction(inv.hash, wtx))
3432 fTrickleWait = true;
3437 vInvWait.push_back(inv);
3442 // returns true if wasn't already contained in the set
3443 if (pto->setInventoryKnown.insert(inv).second)
3445 vInv.push_back(inv);
3446 if (vInv.size() >= 1000)
3448 pto->PushMessage("inv", vInv);
3453 pto->vInventoryToSend = vInvWait;
3456 pto->PushMessage("inv", vInv);
3462 vector<CInv> vGetData;
3463 int64 nNow = GetTime() * 1000000;
3465 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3467 const CInv& inv = (*pto->mapAskFor.begin()).second;
3468 if (!AlreadyHave(txdb, inv))
3470 printf("sending getdata: %s\n", inv.ToString().c_str());
3471 vGetData.push_back(inv);
3472 if (vGetData.size() >= 1000)
3474 pto->PushMessage("getdata", vGetData);
3478 mapAlreadyAskedFor[inv] = nNow;
3479 pto->mapAskFor.erase(pto->mapAskFor.begin());
3481 if (!vGetData.empty())
3482 pto->PushMessage("getdata", vGetData);
3501 //////////////////////////////////////////////////////////////////////////////
3506 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3508 unsigned char* pdata = (unsigned char*)pbuffer;
3509 unsigned int blocks = 1 + ((len + 8) / 64);
3510 unsigned char* pend = pdata + 64 * blocks;
3511 memset(pdata + len, 0, 64 * blocks - len);
3513 unsigned int bits = len * 8;
3514 pend[-1] = (bits >> 0) & 0xff;
3515 pend[-2] = (bits >> 8) & 0xff;
3516 pend[-3] = (bits >> 16) & 0xff;
3517 pend[-4] = (bits >> 24) & 0xff;
3521 static const unsigned int pSHA256InitState[8] =
3522 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3524 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3527 unsigned char data[64];
3531 for (int i = 0; i < 16; i++)
3532 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3534 for (int i = 0; i < 8; i++)
3535 ctx.h[i] = ((uint32_t*)pinit)[i];
3537 SHA256_Update(&ctx, data, sizeof(data));
3538 for (int i = 0; i < 8; i++)
3539 ((uint32_t*)pstate)[i] = ctx.h[i];
3543 // ScanHash scans nonces looking for a hash with at least some zero bits.
3544 // It operates on big endian data. Caller does the byte reversing.
3545 // All input buffers are 16-byte aligned. nNonce is usually preserved
3546 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3547 // the block is rebuilt and nNonce starts over at zero.
3549 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3551 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3555 // Hash pdata using pmidstate as the starting state into
3556 // preformatted buffer phash1, then hash phash1 into phash
3558 SHA256Transform(phash1, pdata, pmidstate);
3559 SHA256Transform(phash, phash1, pSHA256InitState);
3561 // Return the nonce if the hash has at least some zero bits,
3562 // caller will check if it has enough to reach the target
3563 if (((unsigned short*)phash)[14] == 0)
3566 // If nothing found after trying for a while, return -1
3567 if ((nNonce & 0xffff) == 0)
3569 nHashesDone = 0xffff+1;
3570 return (unsigned int) -1;
3575 // Some explaining would be appreciated
3580 set<uint256> setDependsOn;
3583 COrphan(CTransaction* ptxIn)
3591 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3592 BOOST_FOREACH(uint256 hash, setDependsOn)
3593 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3598 uint64 nLastBlockTx = 0;
3599 uint64 nLastBlockSize = 0;
3600 int64 nLastCoinStakeSearchInterval = 0;
3603 // fProofOfStake: try (best effort) to make a proof-of-stake block
3604 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
3606 CReserveKey reservekey(pwallet);
3609 auto_ptr<CBlock> pblock(new CBlock());
3613 // Create coinbase tx
3615 txNew.vin.resize(1);
3616 txNew.vin[0].prevout.SetNull();
3617 txNew.vout.resize(1);
3618 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3620 // Add our coinbase tx as first transaction
3621 pblock->vtx.push_back(txNew);
3623 // ppcoin: if coinstake available add coinstake tx
3624 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
3625 CBlockIndex* pindexPrev = pindexBest;
3627 if (fProofOfStake) // attemp to find a coinstake
3629 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
3630 CTransaction txCoinStake;
3631 int64 nSearchTime = GetAdjustedTime();
3632 if (nSearchTime > nLastCoinStakeSearchTime)
3634 if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
3636 pblock->vtx.push_back(txCoinStake);
3637 pblock->vtx[0].vout[0].SetEmpty();
3639 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
3640 nLastCoinStakeSearchTime = nSearchTime;
3644 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
3646 // Collect memory pool transactions into the block
3649 LOCK2(cs_main, mempool.cs);
3652 // Priority order to process transactions
3653 list<COrphan> vOrphan; // list memory doesn't move
3654 map<uint256, vector<COrphan*> > mapDependers;
3655 multimap<double, CTransaction*> mapPriority;
3656 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3658 CTransaction& tx = (*mi).second;
3659 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
3662 COrphan* porphan = NULL;
3663 double dPriority = 0;
3664 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3666 // Read prev transaction
3667 CTransaction txPrev;
3669 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3671 // Has to wait for dependencies
3674 // Use list for automatic deletion
3675 vOrphan.push_back(COrphan(&tx));
3676 porphan = &vOrphan.back();
3678 mapDependers[txin.prevout.hash].push_back(porphan);
3679 porphan->setDependsOn.insert(txin.prevout.hash);
3682 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3684 // Read block header
3685 int nConf = txindex.GetDepthInMainChain();
3687 dPriority += (double)nValueIn * nConf;
3689 if (fDebug && GetBoolArg("-printpriority"))
3690 printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3693 // Priority is sum(valuein * age) / txsize
3694 dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3697 porphan->dPriority = dPriority;
3699 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3701 if (fDebug && GetBoolArg("-printpriority"))
3703 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3710 // Collect transactions into block
3711 map<uint256, CTxIndex> mapTestPool;
3712 uint64 nBlockSize = 1000;
3713 uint64 nBlockTx = 0;
3714 int nBlockSigOps = 100;
3715 while (!mapPriority.empty())
3717 // Take highest priority transaction off priority queue
3718 CTransaction& tx = *(*mapPriority.begin()).second;
3719 mapPriority.erase(mapPriority.begin());
3722 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3723 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3726 // Legacy limits on sigOps:
3727 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
3728 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3732 if (tx.nTime > GetAdjustedTime())
3735 // ppcoin: simplify transaction fee - allow free = false
3736 int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
3738 // Connecting shouldn't fail due to dependency on other memory pool transactions
3739 // because we're already processing them in order of dependency
3740 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3741 MapPrevTx mapInputs;
3743 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3746 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3747 if (nTxFees < nMinFee)
3750 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3751 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3754 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3756 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3757 swap(mapTestPool, mapTestPoolTmp);
3760 pblock->vtx.push_back(tx);
3761 nBlockSize += nTxSize;
3763 nBlockSigOps += nTxSigOps;
3766 // Add transactions that depend on this one to the priority queue
3767 uint256 hash = tx.GetHash();
3768 if (mapDependers.count(hash))
3770 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3772 if (!porphan->setDependsOn.empty())
3774 porphan->setDependsOn.erase(hash);
3775 if (porphan->setDependsOn.empty())
3776 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3782 nLastBlockTx = nBlockTx;
3783 nLastBlockSize = nBlockSize;
3784 if (fDebug && GetBoolArg("-printpriority"))
3785 printf("CreateNewBlock(): total size %lu\n", nBlockSize);
3788 if (pblock->IsProofOfWork())
3789 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
3792 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3793 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3794 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
3795 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
3796 pblock->UpdateTime(pindexPrev);
3799 return pblock.release();
3803 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3805 // Update nExtraNonce
3806 static uint256 hashPrevBlock;
3807 if (hashPrevBlock != pblock->hashPrevBlock)
3810 hashPrevBlock = pblock->hashPrevBlock;
3813 pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
3814 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3816 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3820 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3823 // Prebuild hash buffers
3830 uint256 hashPrevBlock;
3831 uint256 hashMerkleRoot;
3834 unsigned int nNonce;
3837 unsigned char pchPadding0[64];
3839 unsigned char pchPadding1[64];
3842 memset(&tmp, 0, sizeof(tmp));
3844 tmp.block.nVersion = pblock->nVersion;
3845 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3846 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3847 tmp.block.nTime = pblock->nTime;
3848 tmp.block.nBits = pblock->nBits;
3849 tmp.block.nNonce = pblock->nNonce;
3851 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3852 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3854 // Byte swap all the input buffer
3855 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3856 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3858 // Precalc the first half of the first hash, which stays constant
3859 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3861 memcpy(pdata, &tmp.block, 128);
3862 memcpy(phash1, &tmp.hash1, 64);
3866 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3868 uint256 hash = pblock->GetHash();
3869 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3871 if (hash > hashTarget && pblock->IsProofOfWork())
3872 return error("BitcoinMiner : proof-of-work not meeting target");
3875 printf("BitcoinMiner:\n");
3876 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3878 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
3879 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3884 if (pblock->hashPrevBlock != hashBestChain)
3885 return error("BitcoinMiner : generated block is stale");
3887 // Remove key from key pool
3888 reservekey.KeepKey();
3890 // Track how many getdata requests this block gets
3892 LOCK(wallet.cs_wallet);
3893 wallet.mapRequestCount[pblock->GetHash()] = 0;
3896 // Process this block the same as if we had received it from another node
3897 if (!ProcessBlock(NULL, pblock))
3898 return error("BitcoinMiner : ProcessBlock, block not accepted");
3904 void static ThreadBitcoinMiner(void* parg);
3906 static bool fGenerateBitcoins = false;
3907 static bool fLimitProcessors = false;
3908 static int nLimitProcessors = -1;
3910 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake)
3912 printf("CPUMiner started for proof-of-%s\n", fProofOfStake? "stake" : "work");
3913 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3915 // Each thread has its own key and counter
3916 CReserveKey reservekey(pwallet);
3917 unsigned int nExtraNonce = 0;
3919 while (fGenerateBitcoins || fProofOfStake)
3923 while (vNodes.empty() || IsInitialBlockDownload())
3928 if ((!fGenerateBitcoins) && !fProofOfStake)
3932 while (pwallet->IsLocked())
3934 strMintWarning = strMintMessage;
3937 strMintWarning = "";
3942 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3943 CBlockIndex* pindexPrev = pindexBest;
3945 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
3949 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3953 // ppcoin: if proof-of-stake block found then process block
3954 if (pblock->IsProofOfStake())
3956 if (!pblock->SignBlock(*pwalletMain))
3958 strMintWarning = strMintMessage;
3961 strMintWarning = "";
3962 printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
3963 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3964 CheckWork(pblock.get(), *pwalletMain, reservekey);
3965 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3971 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3975 // Prebuild hash buffers
3977 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3978 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3979 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3981 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3983 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3984 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3990 int64 nStart = GetTime();
3991 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3993 uint256& hash = *alignup<16>(hashbuf);
3996 unsigned int nHashesDone = 0;
3997 unsigned int nNonceFound;
4000 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
4001 (char*)&hash, nHashesDone);
4003 // Check if something found
4004 if (nNonceFound != (unsigned int) -1)
4006 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
4007 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
4009 if (hash <= hashTarget)
4012 pblock->nNonce = ByteReverse(nNonceFound);
4013 assert(hash == pblock->GetHash());
4014 if (!pblock->SignBlock(*pwalletMain))
4016 strMintWarning = strMintMessage;
4019 strMintWarning = "";
4020 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4021 CheckWork(pblock.get(), *pwalletMain, reservekey);
4022 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4028 static int64 nHashCounter;
4029 if (nHPSTimerStart == 0)
4031 nHPSTimerStart = GetTimeMillis();
4035 nHashCounter += nHashesDone;
4036 if (GetTimeMillis() - nHPSTimerStart > 4000)
4038 static CCriticalSection cs;
4041 if (GetTimeMillis() - nHPSTimerStart > 4000)
4043 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
4044 nHPSTimerStart = GetTimeMillis();
4046 static int64 nLogTime;
4047 if (GetTime() - nLogTime > 30 * 60)
4049 nLogTime = GetTime();
4050 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
4051 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
4057 // Check for stop or if block needs to be rebuilt
4060 if (!fGenerateBitcoins)
4062 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4066 if (nBlockNonce >= 0xffff0000)
4068 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4070 if (pindexPrev != pindexBest)
4073 // Update nTime every few seconds
4074 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
4075 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4076 pblock->UpdateTime(pindexPrev);
4077 nBlockTime = ByteReverse(pblock->nTime);
4078 if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
4079 break; // need to update coinbase timestamp
4084 void static ThreadBitcoinMiner(void* parg)
4086 CWallet* pwallet = (CWallet*)parg;
4089 vnThreadsRunning[THREAD_MINER]++;
4090 BitcoinMiner(pwallet, false);
4091 vnThreadsRunning[THREAD_MINER]--;
4093 catch (std::exception& e) {
4094 vnThreadsRunning[THREAD_MINER]--;
4095 PrintException(&e, "ThreadBitcoinMiner()");
4097 vnThreadsRunning[THREAD_MINER]--;
4098 PrintException(NULL, "ThreadBitcoinMiner()");
4101 if (vnThreadsRunning[THREAD_MINER] == 0)
4103 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4107 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4109 fGenerateBitcoins = fGenerate;
4110 nLimitProcessors = GetArg("-genproclimit", -1);
4111 if (nLimitProcessors == 0)
4112 fGenerateBitcoins = false;
4113 fLimitProcessors = (nLimitProcessors != -1);
4117 int nProcessors = boost::thread::hardware_concurrency();
4118 printf("%d processors\n", nProcessors);
4119 if (nProcessors < 1)
4121 if (fLimitProcessors && nProcessors > nLimitProcessors)
4122 nProcessors = nLimitProcessors;
4123 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4124 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4125 for (int i = 0; i < nAddThreads; i++)
4127 if (!CreateThread(ThreadBitcoinMiner, pwallet))
4128 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");