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 CBlockIndex* pindexGenesisBlock = NULL;
37 uint64 nBestChainTrust = 0;
38 uint64 nBestInvalidTrust = 0;
39 uint256 hashBestChain = 0;
40 CBlockIndex* pindexBest = NULL;
41 int64 nTimeBestReceived = 0;
43 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
45 map<uint256, CBlock*> mapOrphanBlocks;
46 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
47 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
49 map<uint256, CDataStream*> mapOrphanTransactions;
50 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
52 // Constant stuff for coinbase transactions we create:
53 CScript COINBASE_FLAGS;
55 const string strMessageMagic = "PPCoin Signed Message:\n";
61 int64 nTransactionFee = MIN_TX_FEE;
65 //////////////////////////////////////////////////////////////////////////////
67 // dispatching functions
70 // These functions dispatch to one or all registered wallets
73 void RegisterWallet(CWallet* pwalletIn)
76 LOCK(cs_setpwalletRegistered);
77 setpwalletRegistered.insert(pwalletIn);
81 void UnregisterWallet(CWallet* pwalletIn)
84 LOCK(cs_setpwalletRegistered);
85 setpwalletRegistered.erase(pwalletIn);
89 // check whether the passed transaction is from us
90 bool static IsFromMe(CTransaction& tx)
92 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
93 if (pwallet->IsFromMe(tx))
98 // get the wallet transaction with the given hash (if it exists)
99 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
101 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
102 if (pwallet->GetTransaction(hashTx,wtx))
107 // erases transaction with the given hash from all wallets
108 void static EraseFromWallets(uint256 hash)
110 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
111 pwallet->EraseFromWallet(hash);
114 // make sure all wallets know about the given transaction, in the given block
115 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true)
119 // ppcoin: wallets need to refund inputs when disconnecting coinstake
120 if (tx.IsCoinStake())
122 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
123 if (pwallet->IsFromMe(tx))
124 pwallet->DisableTransaction(tx);
129 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
130 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
133 // notify wallets about a new best chain
134 void static SetBestChain(const CBlockLocator& loc)
136 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
137 pwallet->SetBestChain(loc);
140 // notify wallets about an updated transaction
141 void static UpdatedTransaction(const uint256& hashTx)
143 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
144 pwallet->UpdatedTransaction(hashTx);
148 void static PrintWallets(const CBlock& block)
150 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
151 pwallet->PrintWallet(block);
154 // notify wallets about an incoming inventory (for request counts)
155 void static Inventory(const uint256& hash)
157 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
158 pwallet->Inventory(hash);
161 // ask wallets to resend their transactions
162 void static ResendWalletTransactions()
164 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
165 pwallet->ResendWalletTransactions();
174 //////////////////////////////////////////////////////////////////////////////
176 // mapOrphanTransactions
179 bool AddOrphanTx(const CDataStream& vMsg)
182 CDataStream(vMsg) >> tx;
183 uint256 hash = tx.GetHash();
184 if (mapOrphanTransactions.count(hash))
187 CDataStream* pvMsg = new CDataStream(vMsg);
189 // Ignore big transactions, to avoid a
190 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
191 // large transaction with a missing parent then we assume
192 // it will rebroadcast it later, after the parent transaction(s)
193 // have been mined or received.
194 // 10,000 orphans, each of which is at most 5,000 bytes big is
195 // at most 500 megabytes of orphans:
196 if (pvMsg->size() > 5000)
198 printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
203 mapOrphanTransactions[hash] = pvMsg;
204 BOOST_FOREACH(const CTxIn& txin, tx.vin)
205 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
207 printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
208 mapOrphanTransactions.size());
212 void static EraseOrphanTx(uint256 hash)
214 if (!mapOrphanTransactions.count(hash))
216 const CDataStream* pvMsg = mapOrphanTransactions[hash];
218 CDataStream(*pvMsg) >> tx;
219 BOOST_FOREACH(const CTxIn& txin, tx.vin)
221 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
222 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
223 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
226 mapOrphanTransactions.erase(hash);
229 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
231 unsigned int nEvicted = 0;
232 while (mapOrphanTransactions.size() > nMaxOrphans)
234 // Evict a random orphan:
235 uint256 randomhash = GetRandHash();
236 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
237 if (it == mapOrphanTransactions.end())
238 it = mapOrphanTransactions.begin();
239 EraseOrphanTx(it->first);
251 //////////////////////////////////////////////////////////////////////////////
253 // CTransaction and CTxIndex
256 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
259 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
261 if (!ReadFromDisk(txindexRet.pos))
263 if (prevout.n >= vout.size())
271 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
274 return ReadFromDisk(txdb, prevout, txindex);
277 bool CTransaction::ReadFromDisk(COutPoint prevout)
281 return ReadFromDisk(txdb, prevout, txindex);
284 bool CTransaction::IsStandard() const
286 BOOST_FOREACH(const CTxIn& txin, vin)
288 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
289 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
290 // ~65-byte public keys, plus a few script ops.
291 if (txin.scriptSig.size() > 500)
293 if (!txin.scriptSig.IsPushOnly())
296 BOOST_FOREACH(const CTxOut& txout, vout)
297 if (!::IsStandard(txout.scriptPubKey))
303 // Check transaction inputs, and make sure any
304 // pay-to-script-hash transactions are evaluating IsStandard scripts
306 // Why bother? To avoid denial-of-service attacks; an attacker
307 // can submit a standard HASH... OP_EQUAL transaction,
308 // which will get accepted into blocks. The redemption
309 // script can be anything; an attacker could use a very
310 // expensive-to-check-upon-redemption script like:
311 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
313 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
316 return true; // Coinbases don't use vin normally
318 for (unsigned int i = 0; i < vin.size(); i++)
320 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
322 vector<vector<unsigned char> > vSolutions;
323 txnouttype whichType;
324 // get the scriptPubKey corresponding to this input:
325 const CScript& prevScript = prev.scriptPubKey;
326 if (!Solver(prevScript, whichType, vSolutions))
328 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
329 if (nArgsExpected < 0)
332 // Transactions with extra stuff in their scriptSigs are
333 // non-standard. Note that this EvalScript() call will
334 // be quick, because if there are any operations
335 // beside "push data" in the scriptSig the
336 // IsStandard() call returns false
337 vector<vector<unsigned char> > stack;
338 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
341 if (whichType == TX_SCRIPTHASH)
345 CScript subscript(stack.back().begin(), stack.back().end());
346 vector<vector<unsigned char> > vSolutions2;
347 txnouttype whichType2;
348 if (!Solver(subscript, whichType2, vSolutions2))
350 if (whichType2 == TX_SCRIPTHASH)
354 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
357 nArgsExpected += tmpExpected;
360 if (stack.size() != (unsigned int)nArgsExpected)
368 CTransaction::GetLegacySigOpCount() const
370 unsigned int nSigOps = 0;
371 BOOST_FOREACH(const CTxIn& txin, vin)
373 nSigOps += txin.scriptSig.GetSigOpCount(false);
375 BOOST_FOREACH(const CTxOut& txout, vout)
377 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
383 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
395 // Load the block this tx is in
397 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
399 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
404 // Update the tx's hashBlock
405 hashBlock = pblock->GetHash();
407 // Locate the transaction
408 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
409 if (pblock->vtx[nIndex] == *(CTransaction*)this)
411 if (nIndex == (int)pblock->vtx.size())
413 vMerkleBranch.clear();
415 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
419 // Fill in merkle branch
420 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
423 // Is the tx in a block that's in the main chain
424 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
425 if (mi == mapBlockIndex.end())
427 CBlockIndex* pindex = (*mi).second;
428 if (!pindex || !pindex->IsInMainChain())
431 return pindexBest->nHeight - pindex->nHeight + 1;
440 bool CTransaction::CheckTransaction() const
442 // Basic checks that don't depend on any context
444 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
446 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
448 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
449 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
451 // Check for negative or overflow output values
453 for (int i = 0; i < vout.size(); i++)
455 const CTxOut& txout = vout[i];
456 if (txout.IsEmpty() && (!IsCoinBase()) && (!IsCoinStake()))
457 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
458 if (txout.nValue < 0)
459 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
460 if (txout.nValue > MAX_MONEY)
461 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
462 nValueOut += txout.nValue;
463 if (!MoneyRange(nValueOut))
464 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
467 // Check for duplicate inputs
468 set<COutPoint> vInOutPoints;
469 BOOST_FOREACH(const CTxIn& txin, vin)
471 if (vInOutPoints.count(txin.prevout))
473 vInOutPoints.insert(txin.prevout);
478 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
479 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
483 BOOST_FOREACH(const CTxIn& txin, vin)
484 if (txin.prevout.IsNull())
485 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
491 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
492 bool* pfMissingInputs)
495 *pfMissingInputs = false;
497 if (!tx.CheckTransaction())
498 return error("CTxMemPool::accept() : CheckTransaction failed");
500 // Coinbase is only valid in a block, not as a loose transaction
502 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
503 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
504 if (tx.IsCoinStake())
505 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
507 // To help v0.1.5 clients who would see it as a negative number
508 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
509 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
511 // Rather not work on nonstandard transactions (unless -testnet)
512 if (!fTestNet && !tx.IsStandard())
513 return error("CTxMemPool::accept() : nonstandard transaction type");
515 // Do we already have it?
516 uint256 hash = tx.GetHash();
519 if (mapTx.count(hash))
523 if (txdb.ContainsTx(hash))
526 // Check for conflicts with in-memory transactions
527 CTransaction* ptxOld = NULL;
528 for (unsigned int i = 0; i < tx.vin.size(); i++)
530 COutPoint outpoint = tx.vin[i].prevout;
531 if (mapNextTx.count(outpoint))
533 // Disable replacement feature for now
536 // Allow replacing with a newer version of the same transaction
539 ptxOld = mapNextTx[outpoint].ptx;
540 if (ptxOld->IsFinal())
542 if (!tx.IsNewerThan(*ptxOld))
544 for (unsigned int i = 0; i < tx.vin.size(); i++)
546 COutPoint outpoint = tx.vin[i].prevout;
547 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
557 map<uint256, CTxIndex> mapUnused;
558 bool fInvalid = false;
559 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
562 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
564 *pfMissingInputs = true;
565 return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
568 // Check for non-standard pay-to-script-hash in inputs
569 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
570 return error("CTxMemPool::accept() : nonstandard transaction input");
572 // Note: if you modify this code to accept non-standard transactions, then
573 // you should add code here to check that the transaction does a
574 // reasonable number of ECDSA signature verifications.
576 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
577 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
579 // Don't accept it if it can't get into a block
580 if (nFees < tx.GetMinFee(1000, false, GMF_RELAY))
581 return error("CTxMemPool::accept() : not enough fees");
583 // Continuously rate-limit free transactions
584 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
585 // be annoying or make other's transactions take longer to confirm.
586 if (nFees < MIN_RELAY_TX_FEE)
588 static CCriticalSection cs;
589 static double dFreeCount;
590 static int64 nLastTime;
591 int64 nNow = GetTime();
595 // Use an exponentially decaying ~10-minute window:
596 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
598 // -limitfreerelay unit is thousand-bytes-per-minute
599 // At default rate it would take over a month to fill 1GB
600 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
601 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
603 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
608 // Check against previous transactions
609 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
610 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
612 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
616 // Store transaction in memory
621 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
627 ///// are we sure this is ok when loading transactions or restoring block txes
628 // If updated, erase old tx from wallet
630 EraseFromWallets(ptxOld->GetHash());
632 printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str());
636 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
638 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
641 bool CTxMemPool::addUnchecked(CTransaction &tx)
643 printf("addUnchecked(): size %lu\n", mapTx.size());
644 // Add to memory pool without checking anything. Don't call this directly,
645 // call CTxMemPool::accept to properly check the transaction first.
648 uint256 hash = tx.GetHash();
650 for (unsigned int i = 0; i < tx.vin.size(); i++)
651 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
652 nTransactionsUpdated++;
658 bool CTxMemPool::remove(CTransaction &tx)
660 // Remove transaction from memory pool
663 uint256 hash = tx.GetHash();
664 if (mapTx.count(hash))
666 BOOST_FOREACH(const CTxIn& txin, tx.vin)
667 mapNextTx.erase(txin.prevout);
669 nTransactionsUpdated++;
680 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
682 if (hashBlock == 0 || nIndex == -1)
685 // Find the block it claims to be in
686 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
687 if (mi == mapBlockIndex.end())
689 CBlockIndex* pindex = (*mi).second;
690 if (!pindex || !pindex->IsInMainChain())
693 // Make sure the merkle branch connects to this block
694 if (!fMerkleVerified)
696 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
698 fMerkleVerified = true;
702 return pindexBest->nHeight - pindex->nHeight + 1;
706 int CMerkleTx::GetBlocksToMaturity() const
708 if (!(IsCoinBase() || IsCoinStake()))
710 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
714 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
718 if (!IsInMainChain() && !ClientConnectInputs())
720 return CTransaction::AcceptToMemoryPool(txdb, false);
724 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
728 bool CMerkleTx::AcceptToMemoryPool()
731 return AcceptToMemoryPool(txdb);
736 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
741 // Add previous supporting transactions first
742 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
744 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
746 uint256 hash = tx.GetHash();
747 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
748 tx.AcceptToMemoryPool(txdb, fCheckInputs);
751 return AcceptToMemoryPool(txdb, fCheckInputs);
756 bool CWalletTx::AcceptWalletTransaction()
759 return AcceptWalletTransaction(txdb);
762 int CTxIndex::GetDepthInMainChain() const
766 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
768 // Find the block in the index
769 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
770 if (mi == mapBlockIndex.end())
772 CBlockIndex* pindex = (*mi).second;
773 if (!pindex || !pindex->IsInMainChain())
775 return 1 + nBestHeight - pindex->nHeight;
787 //////////////////////////////////////////////////////////////////////////////
789 // CBlock and CBlockIndex
792 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
794 if (!fReadTransactions)
796 *this = pindex->GetBlockHeader();
799 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
801 if (GetHash() != pindex->GetBlockHash())
802 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
806 uint256 static GetOrphanRoot(const CBlock* pblock)
808 // Work back to the first block in the orphan chain
809 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
810 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
811 return pblock->GetHash();
814 // ppcoin: find block wanted by given orphan block
815 uint256 WantedByOrphan(const CBlock* pblockOrphan)
817 // Work back to the first block in the orphan chain
818 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
819 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
820 return pblockOrphan->hashPrevBlock;
823 int64 static GetProofOfWorkReward(unsigned int nBits)
825 CBigNum bnSubsidyLimit = 9999 * COIN; // subsidy amount for difficulty 1
827 bnTarget.SetCompact(nBits);
828 CBigNum bnTargetLimit = bnProofOfWorkLimit;
829 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
831 // ppcoin: subsidy is cut in half every 16x multiply of difficulty
832 // A reasonably continuous curve is used to avoid shock to market
833 // (nSubsidyLimit / nSubsidy) ** 4 == bnProofOfWorkLimit / bnTarget
834 CBigNum bnLowerBound = CENT;
835 CBigNum bnUpperBound = bnSubsidyLimit;
836 while (bnLowerBound + CENT <= bnUpperBound)
838 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
839 if (fDebug && GetBoolArg("-printcreation"))
840 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
841 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
842 bnUpperBound = bnMidValue;
844 bnLowerBound = bnMidValue;
847 int64 nSubsidy = bnUpperBound.getuint64();
848 nSubsidy = (nSubsidy / CENT) * CENT;
849 if (fDebug && GetBoolArg("-printcreation"))
850 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
855 // ppcoin: miner's coin stake is rewarded based on coin age spent (coin-days)
856 int64 GetProofOfStakeReward(int64 nCoinAge)
858 static int64 nRewardCoinYear = CENT; // creation amount per coin-year
859 int64 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
860 if (fDebug && GetBoolArg("-printcreation"))
861 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nCoinAge);
865 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
866 static const int64 nTargetSpacingStake = 10 * 60; // ten minutes
867 static const int64 nTargetSpacingWorkMax = 2 * 60 * 60; // two hours
868 static const int64 nMaxClockDrift = 2 * 60 * 60; // two hours
871 // minimum amount of work that could possibly be required nTime after
872 // minimum work required was nBase
874 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
877 bnResult.SetCompact(nBase);
879 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
881 // Maximum 200% adjustment per day...
883 nTime -= 24 * 60 * 60;
885 if (bnResult > bnProofOfWorkLimit)
886 bnResult = bnProofOfWorkLimit;
887 return bnResult.GetCompact();
890 // ppcoin: find last block index up to pindex
891 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
893 while (pindex && (pindex->IsProofOfStake() != fProofOfStake))
894 pindex = pindex->pprev;
898 unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
900 // Genesis block and first block
901 if (pindexLast == NULL || pindexLast->pprev == NULL)
902 return bnProofOfWorkLimit.GetCompact();
904 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
905 if (pindexPrev == NULL)
906 return bnProofOfWorkLimit.GetCompact();
907 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
908 if (pindexPrevPrev == NULL)
909 return bnProofOfWorkLimit.GetCompact();
910 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
912 // ppcoin: target change every block
913 // ppcoin: retarget with exponential moving toward target spacing
915 bnNew.SetCompact(pindexPrev->nBits);
916 int64 nTargetSpacing = fProofOfStake? nTargetSpacingStake : min(nTargetSpacingWorkMax, nTargetSpacingStake * (1 + pindexLast->nHeight - pindexPrev->nHeight));
917 int64 nInterval = nTargetTimespan / nTargetSpacing;
918 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
919 bnNew /= ((nInterval + 1) * nTargetSpacing);
921 if (bnNew > bnProofOfWorkLimit)
922 bnNew = bnProofOfWorkLimit;
924 return bnNew.GetCompact();
927 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
930 bnTarget.SetCompact(nBits);
933 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
934 return error("CheckProofOfWork() : nBits below minimum work");
936 // Check proof of work matches claimed amount
937 if (hash > bnTarget.getuint256())
938 return error("CheckProofOfWork() : hash doesn't match nBits");
943 // Return maximum amount of blocks that other nodes claim to have
944 int GetNumBlocksOfPeers()
946 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
949 bool IsInitialBlockDownload()
951 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
953 static int64 nLastUpdate;
954 static CBlockIndex* pindexLastBest;
955 if (pindexBest != pindexLastBest)
957 pindexLastBest = pindexBest;
958 nLastUpdate = GetTime();
960 return (GetTime() - nLastUpdate < 10 &&
961 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
964 void static InvalidChainFound(CBlockIndex* pindexNew)
966 if (pindexNew->nChainTrust > nBestInvalidTrust)
968 nBestInvalidTrust = pindexNew->nChainTrust;
969 CTxDB().WriteBestInvalidTrust(nBestInvalidTrust);
972 printf("InvalidChainFound: invalid block=%s height=%d trust=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, CBigNum(pindexNew->nChainTrust).ToString().c_str());
973 printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
974 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
975 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
978 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
980 nTime = max(GetBlockTime(), GetAdjustedTime());
993 bool CTransaction::DisconnectInputs(CTxDB& txdb)
995 // Relinquish previous transactions' spent pointers
998 BOOST_FOREACH(const CTxIn& txin, vin)
1000 COutPoint prevout = txin.prevout;
1002 // Get prev txindex from disk
1004 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1005 return error("DisconnectInputs() : ReadTxIndex failed");
1007 if (prevout.n >= txindex.vSpent.size())
1008 return error("DisconnectInputs() : prevout.n out of range");
1010 // Mark outpoint as not spent
1011 txindex.vSpent[prevout.n].SetNull();
1014 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1015 return error("DisconnectInputs() : UpdateTxIndex failed");
1019 // Remove transaction from index
1020 // This can fail if a duplicate of this transaction was in a chain that got
1021 // reorganized away. This is only possible if this transaction was completely
1022 // spent, so erasing it would be a no-op anway.
1023 txdb.EraseTxIndex(*this);
1029 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1030 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1032 // FetchInputs can return false either because we just haven't seen some inputs
1033 // (in which case the transaction should be stored as an orphan)
1034 // or because the transaction is malformed (in which case the transaction should
1035 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1039 return true; // Coinbase transactions have no inputs to fetch.
1041 for (unsigned int i = 0; i < vin.size(); i++)
1043 COutPoint prevout = vin[i].prevout;
1044 if (inputsRet.count(prevout.hash))
1045 continue; // Got it already
1048 CTxIndex& txindex = inputsRet[prevout.hash].first;
1050 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1052 // Get txindex from current proposed changes
1053 txindex = mapTestPool.find(prevout.hash)->second;
1057 // Read txindex from txdb
1058 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1060 if (!fFound && (fBlock || fMiner))
1061 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());
1064 CTransaction& txPrev = inputsRet[prevout.hash].second;
1065 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1067 // Get prev tx from single transactions in memory
1070 if (!mempool.exists(prevout.hash))
1071 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());
1072 txPrev = mempool.lookup(prevout.hash);
1075 txindex.vSpent.resize(txPrev.vout.size());
1079 // Get prev tx from disk
1080 if (!txPrev.ReadFromDisk(txindex.pos))
1081 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1085 // Make sure all prevout.n's are valid:
1086 for (unsigned int i = 0; i < vin.size(); i++)
1088 const COutPoint prevout = vin[i].prevout;
1089 assert(inputsRet.count(prevout.hash) != 0);
1090 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1091 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1092 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1094 // Revisit this if/when transaction replacement is implemented and allows
1097 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()));
1104 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1106 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1107 if (mi == inputs.end())
1108 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1110 const CTransaction& txPrev = (mi->second).second;
1111 if (input.prevout.n >= txPrev.vout.size())
1112 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1114 return txPrev.vout[input.prevout.n];
1117 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1123 for (unsigned int i = 0; i < vin.size(); i++)
1125 nResult += GetOutputFor(vin[i], inputs).nValue;
1131 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1136 unsigned int nSigOps = 0;
1137 for (unsigned int i = 0; i < vin.size(); i++)
1139 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1140 if (prevout.scriptPubKey.IsPayToScriptHash())
1141 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1146 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1147 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1148 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1150 // Take over previous transactions' spent pointers
1151 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1152 // fMiner is true when called from the internal bitcoin miner
1153 // ... both are false when called from CTransaction::AcceptToMemoryPool
1158 for (unsigned int i = 0; i < vin.size(); i++)
1160 COutPoint prevout = vin[i].prevout;
1161 assert(inputs.count(prevout.hash) > 0);
1162 CTxIndex& txindex = inputs[prevout.hash].first;
1163 CTransaction& txPrev = inputs[prevout.hash].second;
1165 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1166 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()));
1168 // If prev is coinbase/coinstake, check that it's matured
1169 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1170 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1171 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1172 return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight);
1174 // ppcoin: check transaction timestamp
1175 if (txPrev.nTime > nTime)
1176 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1178 // Check for negative or overflow input values
1179 nValueIn += txPrev.vout[prevout.n].nValue;
1180 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1181 return DoS(100, error("ConnectInputs() : txin values out of range"));
1184 // The first loop above does all the inexpensive checks.
1185 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1186 // Helps prevent CPU exhaustion attacks.
1187 for (unsigned int i = 0; i < vin.size(); i++)
1189 COutPoint prevout = vin[i].prevout;
1190 assert(inputs.count(prevout.hash) > 0);
1191 CTxIndex& txindex = inputs[prevout.hash].first;
1192 CTransaction& txPrev = inputs[prevout.hash].second;
1194 // Check for conflicts (double-spend)
1195 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1196 // for an attacker to attempt to split the network.
1197 if (!txindex.vSpent[prevout.n].IsNull())
1198 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());
1200 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1201 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1202 // still computed and checked, and any change will be caught at the next checkpoint.
1203 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1206 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1208 // only during transition phase for P2SH: do not invoke anti-DoS code for
1209 // potentially old clients relaying bad P2SH transactions
1210 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1211 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1213 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1217 // Mark outpoints as spent
1218 txindex.vSpent[prevout.n] = posThisTx;
1221 if (fBlock || fMiner)
1223 mapTestPool[prevout.hash] = txindex;
1229 // ppcoin: coin stake tx earns reward instead of paying fee
1231 if (!GetCoinAge(txdb, nCoinAge))
1232 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1233 int64 nStakeReward = GetValueOut() - nValueIn;
1234 if (nStakeReward > GetProofOfStakeReward(nCoinAge))
1235 return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
1239 if (nValueIn < GetValueOut())
1240 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1242 // Tally transaction fees
1243 int64 nTxFee = nValueIn - GetValueOut();
1245 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1246 // ppcoin: enforce transaction fees for every block
1247 if (nTxFee < GetMinFee())
1248 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;
1250 if (!MoneyRange(nFees))
1251 return DoS(100, error("ConnectInputs() : nFees out of range"));
1259 bool CTransaction::ClientConnectInputs()
1264 // Take over previous transactions' spent pointers
1268 for (unsigned int i = 0; i < vin.size(); i++)
1270 // Get prev tx from single transactions in memory
1271 COutPoint prevout = vin[i].prevout;
1272 if (!mempool.exists(prevout.hash))
1274 CTransaction& txPrev = mempool.lookup(prevout.hash);
1276 if (prevout.n >= txPrev.vout.size())
1280 if (!VerifySignature(txPrev, *this, i, true, 0))
1281 return error("ConnectInputs() : VerifySignature failed");
1283 ///// this is redundant with the mempool.mapNextTx stuff,
1284 ///// not sure which I want to get rid of
1285 ///// this has to go away now that posNext is gone
1286 // // Check for conflicts
1287 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1288 // return error("ConnectInputs() : prev tx already used");
1290 // // Flag outpoints as used
1291 // txPrev.vout[prevout.n].posNext = posThisTx;
1293 nValueIn += txPrev.vout[prevout.n].nValue;
1295 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1296 return error("ClientConnectInputs() : txin values out of range");
1298 if (GetValueOut() > nValueIn)
1308 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1310 // Disconnect in reverse order
1311 for (int i = vtx.size()-1; i >= 0; i--)
1312 if (!vtx[i].DisconnectInputs(txdb))
1315 // Update block index on disk without changing it in memory.
1316 // The memory index structure will be changed after the db commits.
1319 CDiskBlockIndex blockindexPrev(pindex->pprev);
1320 blockindexPrev.hashNext = 0;
1321 if (!txdb.WriteBlockIndex(blockindexPrev))
1322 return error("DisconnectBlock() : WriteBlockIndex failed");
1325 // ppcoin: clean up wallet after disconnecting coinstake
1326 BOOST_FOREACH(CTransaction& tx, vtx)
1327 SyncWithWallets(tx, this, false, false);
1332 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1334 // Check it again in case a previous version let a bad block in
1338 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1339 // unless those are already completely spent.
1340 // If such overwrites are allowed, coinbases and transactions depending upon those
1341 // can be duplicated to remove the ability to spend the first instance -- even after
1342 // being sent to another address.
1343 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1344 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1345 // already refuses previously-known transaction id's entirely.
1346 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1347 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1348 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1350 BOOST_FOREACH(CTransaction& tx, vtx)
1352 CTxIndex txindexOld;
1353 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1355 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1362 // BIP16 didn't become active until Apr 1 2012 (Feb 15 on testnet)
1363 int64 nBIP16SwitchTime = fTestNet ? 1329264000 : 1333238400;
1364 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1366 //// issue here: it doesn't know the version
1367 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1369 map<uint256, CTxIndex> mapQueuedChanges;
1371 unsigned int nSigOps = 0;
1372 BOOST_FOREACH(CTransaction& tx, vtx)
1374 nSigOps += tx.GetLegacySigOpCount();
1375 if (nSigOps > MAX_BLOCK_SIGOPS)
1376 return DoS(100, error("ConnectBlock() : too many sigops"));
1378 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1379 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1381 MapPrevTx mapInputs;
1382 if (!tx.IsCoinBase())
1385 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1388 if (fStrictPayToScriptHash)
1390 // Add in sigops done by pay-to-script-hash inputs;
1391 // this is to prevent a "rogue miner" from creating
1392 // an incredibly-expensive-to-validate block.
1393 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1394 if (nSigOps > MAX_BLOCK_SIGOPS)
1395 return DoS(100, error("ConnectBlock() : too many sigops"));
1398 if (!tx.IsCoinStake())
1399 nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
1401 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1405 mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
1408 // Write queued txindex changes
1409 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1411 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1412 return error("ConnectBlock() : UpdateTxIndex failed");
1415 // ppcoin: fees are not collected by miners as in bitcoin
1416 // ppcoin: fees are destroyed to compensate the entire network
1417 if (IsProofOfWork() && vtx[0].GetValueOut() > GetProofOfWorkReward(nBits))
1419 if (fDebug && GetBoolArg("-printcreation"))
1420 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1422 // Update block index on disk without changing it in memory.
1423 // The memory index structure will be changed after the db commits.
1426 CDiskBlockIndex blockindexPrev(pindex->pprev);
1427 blockindexPrev.hashNext = pindex->GetBlockHash();
1428 if (!txdb.WriteBlockIndex(blockindexPrev))
1429 return error("ConnectBlock() : WriteBlockIndex failed");
1432 // Watch for transactions paying to me
1433 BOOST_FOREACH(CTransaction& tx, vtx)
1434 SyncWithWallets(tx, this, true);
1439 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1441 printf("REORGANIZE\n");
1444 CBlockIndex* pfork = pindexBest;
1445 CBlockIndex* plonger = pindexNew;
1446 while (pfork != plonger)
1448 while (plonger->nHeight > pfork->nHeight)
1449 if (!(plonger = plonger->pprev))
1450 return error("Reorganize() : plonger->pprev is null");
1451 if (pfork == plonger)
1453 if (!(pfork = pfork->pprev))
1454 return error("Reorganize() : pfork->pprev is null");
1457 // List of what to disconnect
1458 vector<CBlockIndex*> vDisconnect;
1459 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1460 vDisconnect.push_back(pindex);
1462 // List of what to connect
1463 vector<CBlockIndex*> vConnect;
1464 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1465 vConnect.push_back(pindex);
1466 reverse(vConnect.begin(), vConnect.end());
1468 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());
1469 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());
1471 // Disconnect shorter branch
1472 vector<CTransaction> vResurrect;
1473 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1476 if (!block.ReadFromDisk(pindex))
1477 return error("Reorganize() : ReadFromDisk for disconnect failed");
1478 if (!block.DisconnectBlock(txdb, pindex))
1479 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1481 // Queue memory transactions to resurrect
1482 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1483 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1484 vResurrect.push_back(tx);
1487 // Connect longer branch
1488 vector<CTransaction> vDelete;
1489 for (unsigned int i = 0; i < vConnect.size(); i++)
1491 CBlockIndex* pindex = vConnect[i];
1493 if (!block.ReadFromDisk(pindex))
1494 return error("Reorganize() : ReadFromDisk for connect failed");
1495 if (!block.ConnectBlock(txdb, pindex))
1499 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1502 // Queue memory transactions to delete
1503 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1504 vDelete.push_back(tx);
1506 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1507 return error("Reorganize() : WriteHashBestChain failed");
1509 // Make sure it's successfully written to disk before changing memory structure
1510 if (!txdb.TxnCommit())
1511 return error("Reorganize() : TxnCommit failed");
1513 // Disconnect shorter branch
1514 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1516 pindex->pprev->pnext = NULL;
1518 // Connect longer branch
1519 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1521 pindex->pprev->pnext = pindex;
1523 // Resurrect memory transactions that were in the disconnected branch
1524 BOOST_FOREACH(CTransaction& tx, vResurrect)
1525 tx.AcceptToMemoryPool(txdb, false);
1527 // Delete redundant memory transactions that are in the connected branch
1528 BOOST_FOREACH(CTransaction& tx, vDelete)
1531 printf("REORGANIZE: done\n");
1538 runCommand(std::string strCommand)
1540 int nErr = ::system(strCommand.c_str());
1542 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1545 // Called from inside SetBestChain: attaches a block to the new best chain being built
1546 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1548 uint256 hash = GetHash();
1550 // Adding to current best branch
1551 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1554 InvalidChainFound(pindexNew);
1557 if (!txdb.TxnCommit())
1558 return error("SetBestChain() : TxnCommit failed");
1560 // Add to current best branch
1561 pindexNew->pprev->pnext = pindexNew;
1563 // Delete redundant memory transactions
1564 BOOST_FOREACH(CTransaction& tx, vtx)
1570 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1572 uint256 hash = GetHash();
1574 if (!txdb.TxnBegin())
1575 return error("SetBestChain() : TxnBegin failed");
1577 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1579 txdb.WriteHashBestChain(hash);
1580 if (!txdb.TxnCommit())
1581 return error("SetBestChain() : TxnCommit failed");
1582 pindexGenesisBlock = pindexNew;
1584 else if (hashPrevBlock == hashBestChain)
1586 if (!SetBestChainInner(txdb, pindexNew))
1587 return error("SetBestChain() : SetBestChainInner failed");
1591 // the first block in the new chain that will cause it to become the new best chain
1592 CBlockIndex *pindexIntermediate = pindexNew;
1594 // list of blocks that need to be connected afterwards
1595 std::vector<CBlockIndex*> vpindexSecondary;
1597 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1598 // Try to limit how much needs to be done inside
1599 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1601 vpindexSecondary.push_back(pindexIntermediate);
1602 pindexIntermediate = pindexIntermediate->pprev;
1605 if (!vpindexSecondary.empty())
1606 printf("Postponing %i reconnects\n", vpindexSecondary.size());
1608 // Switch to new best branch
1609 if (!Reorganize(txdb, pindexIntermediate))
1612 InvalidChainFound(pindexNew);
1613 return error("SetBestChain() : Reorganize failed");
1616 // Connect futher blocks
1617 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1620 if (!block.ReadFromDisk(pindex))
1622 printf("SetBestChain() : ReadFromDisk failed\n");
1625 if (!txdb.TxnBegin()) {
1626 printf("SetBestChain() : TxnBegin 2 failed\n");
1629 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1630 if (!block.SetBestChainInner(txdb, pindex))
1635 // Update best block in wallet (so we can detect restored wallets)
1636 bool fIsInitialDownload = IsInitialBlockDownload();
1637 if (!fIsInitialDownload)
1639 const CBlockLocator locator(pindexNew);
1640 ::SetBestChain(locator);
1644 hashBestChain = hash;
1645 pindexBest = pindexNew;
1646 nBestHeight = pindexBest->nHeight;
1647 nBestChainTrust = pindexNew->nChainTrust;
1648 nTimeBestReceived = GetTime();
1649 nTransactionsUpdated++;
1650 printf("SetBestChain: new best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
1652 std::string strCmd = GetArg("-blocknotify", "");
1654 if (!fIsInitialDownload && !strCmd.empty())
1656 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1657 boost::thread t(runCommand, strCmd); // thread runs free
1664 // ppcoin: coinstake must meet hash target according to the protocol:
1665 // input 0 must meet the formula
1666 // hash(nBits + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDay
1667 // this ensures that the chance of getting a coinstake is proportional to the
1668 // amount of coin age one owns.
1669 // The reason this hash is chosen is the following:
1670 // nBits: encodes all past block timestamps, making computing hash in advance
1672 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
1673 // generate transaction for future advantage
1674 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
1675 // nodes generating coinstake at the same time
1676 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
1678 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
1679 // generating coinstake at the same time
1680 // block/tx hash should not be used here as they can be generated in vast
1681 // quantities so as to generate blocks faster, degrading the system back into
1682 // a proof-of-work situation.
1684 bool CTransaction::CheckProofOfStake(unsigned int nBits) const
1686 CBigNum bnTargetPerCoinDay;
1687 bnTargetPerCoinDay.SetCompact(nBits);
1692 // Input 0 must match the stake hash target per coin age (nBits)
1693 const CTxIn& txin = vin[0];
1695 // First try finding the previous transaction in database
1697 CTransaction txPrev;
1699 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1700 return false; // previous transaction not in main chain
1702 if (nTime < txPrev.nTime)
1703 return false; // Transaction timestamp violation
1706 if (!VerifySignature(txPrev, *this, 0, true, 0))
1707 return DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", GetHash().ToString().c_str()));
1709 // Read block header
1711 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1712 return false; // unable to read block of previous transaction
1713 if (block.GetBlockTime() + STAKE_MIN_AGE > nTime)
1714 return false; // only count coins meeting min age requirement
1716 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1717 CBigNum bnCoinDay = CBigNum(nValueIn) * (nTime-txPrev.nTime) / COIN / (24 * 60 * 60);
1719 CDataStream ss(SER_GETHASH, 0);
1720 ss << nBits << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << txPrev.nTime << txin.prevout.n << nTime;
1721 if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1724 return DoS(100, error("CheckProofOfStake() : check target failed on coinstake %s", GetHash().ToString().c_str()));
1727 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1728 // Only those coins meeting minimum age requirement counts. As those
1729 // transactions not in main chain are not currently indexed so we
1730 // might not find out about their coin age. Older transactions are
1731 // guaranteed to be in main chain by sync-checkpoint. This rule is
1732 // introduced to help nodes establish a consistent view of the coin
1733 // age (trust score) of competing branches.
1734 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1736 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1742 BOOST_FOREACH(const CTxIn& txin, vin)
1744 // First try finding the previous transaction in database
1745 CTransaction txPrev;
1747 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1748 continue; // previous transaction not in main chain
1749 if (nTime < txPrev.nTime)
1750 return false; // Transaction timestamp violation
1752 // Read block header
1754 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1755 return false; // unable to read block of previous transaction
1756 if (block.GetBlockTime() + STAKE_MIN_AGE > nTime)
1757 continue; // only count coins meeting min age requirement
1759 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1760 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1762 if (fDebug && GetBoolArg("-printcoinage"))
1763 printf("coin age nValueIn=%-12I64d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1766 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1767 if (fDebug && GetBoolArg("-printcoinage"))
1768 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1769 nCoinAge = bnCoinDay.getuint64();
1773 // ppcoin: total coin age spent in block, in the unit of coin-days.
1774 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1779 BOOST_FOREACH(const CTransaction& tx, vtx)
1782 if (tx.GetCoinAge(txdb, nTxCoinAge))
1783 nCoinAge += nTxCoinAge;
1788 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1790 if (fDebug && GetBoolArg("-printcoinage"))
1791 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1796 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1798 // Check for duplicate
1799 uint256 hash = GetHash();
1800 if (mapBlockIndex.count(hash))
1801 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1803 // Construct new block index object
1804 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1806 return error("AddToBlockIndex() : new CBlockIndex failed");
1807 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1808 if (pindexNew->fProofOfStake)
1809 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
1811 pindexNew->phashBlock = &((*mi).first);
1812 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1813 if (miPrev != mapBlockIndex.end())
1815 pindexNew->pprev = (*miPrev).second;
1816 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1819 // ppcoin: compute chain trust score
1821 if (!GetCoinAge(nCoinAge))
1822 return error("AddToBlockIndex() : invalid transaction in block");
1823 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + nCoinAge;
1826 if (!txdb.TxnBegin())
1828 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1829 if (!txdb.TxnCommit())
1833 if (pindexNew->nChainTrust > nBestChainTrust)
1834 if (!SetBestChain(txdb, pindexNew))
1839 if (pindexNew == pindexBest)
1841 // Notify UI to display prev block's coinbase if it was ours
1842 static uint256 hashPrevBestCoinBase;
1843 UpdatedTransaction(hashPrevBestCoinBase);
1844 hashPrevBestCoinBase = vtx[0].GetHash();
1854 bool CBlock::CheckBlock() const
1856 // These are checks that are independent of context
1857 // that can be verified before saving an orphan block.
1860 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
1861 return DoS(100, error("CheckBlock() : size limits failed"));
1863 // Check proof of work matches claimed amount
1864 if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1865 return DoS(50, error("CheckBlock() : proof of work failed"));
1868 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
1869 return error("CheckBlock() : block timestamp too far in the future");
1871 // First transaction must be coinbase, the rest must not be
1872 if (vtx.empty() || !vtx[0].IsCoinBase())
1873 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1874 for (unsigned int i = 1; i < vtx.size(); i++)
1875 if (vtx[i].IsCoinBase())
1876 return DoS(100, error("CheckBlock() : more than one coinbase"));
1878 // ppcoin: only the second transaction can be the optional coinstake
1879 for (int i = 2; i < vtx.size(); i++)
1880 if (vtx[i].IsCoinStake())
1881 return DoS(100, error("CheckBlock() : coinstake in wrong position"));
1883 // ppcoin: coinbase output should be empty if proof-of-stake block
1884 if (IsProofOfStake() && !vtx[0].vout[0].IsEmpty())
1885 return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
1887 // Check coinbase timestamp
1888 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
1889 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
1891 // Check coinstake timestamp
1892 if (IsProofOfStake() && GetBlockTime() > (int64)vtx[1].nTime + nMaxClockDrift)
1893 return DoS(50, error("CheckBlock() : coinstake timestamp is too early"));
1895 // Check transactions
1896 BOOST_FOREACH(const CTransaction& tx, vtx)
1898 if (!tx.CheckTransaction())
1899 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1900 // ppcoin: check transaction timestamp
1901 if (GetBlockTime() < (int64)tx.nTime)
1902 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
1905 // Check for duplicate txids. This is caught by ConnectInputs(),
1906 // but catching it earlier avoids a potential DoS attack:
1907 set<uint256> uniqueTx;
1908 BOOST_FOREACH(const CTransaction& tx, vtx)
1910 uniqueTx.insert(tx.GetHash());
1912 if (uniqueTx.size() != vtx.size())
1913 return DoS(100, error("CheckBlock() : duplicate transaction"));
1915 unsigned int nSigOps = 0;
1916 BOOST_FOREACH(const CTransaction& tx, vtx)
1918 nSigOps += tx.GetLegacySigOpCount();
1920 if (nSigOps > MAX_BLOCK_SIGOPS)
1921 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1924 if (hashMerkleRoot != BuildMerkleTree())
1925 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1927 // ppcoin: check block signature
1928 if (!CheckBlockSignature())
1929 return DoS(100, error("CheckBlock() : bad block signature"));
1934 bool CBlock::AcceptBlock()
1936 // Check for duplicate
1937 uint256 hash = GetHash();
1938 if (mapBlockIndex.count(hash))
1939 return error("AcceptBlock() : block already in mapBlockIndex");
1941 // Get prev block index
1942 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1943 if (mi == mapBlockIndex.end())
1944 return DoS(10, error("AcceptBlock() : prev block not found"));
1945 CBlockIndex* pindexPrev = (*mi).second;
1946 int nHeight = pindexPrev->nHeight+1;
1948 // Check proof-of-work or proof-of-stake
1949 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
1950 return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake"));
1952 // Check timestamp against prev
1953 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
1954 return error("AcceptBlock() : block's timestamp is too early");
1956 // Check that all transactions are finalized
1957 BOOST_FOREACH(const CTransaction& tx, vtx)
1958 if (!tx.IsFinal(nHeight, GetBlockTime()))
1959 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1961 // Check that the block chain matches the known block chain up to a hardened checkpoint
1962 if (!Checkpoints::CheckHardened(nHeight, hash))
1963 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight));
1965 // ppcoin: check that the block satisfies synchronized checkpoint
1966 if (!Checkpoints::CheckSync(hash, pindexPrev))
1967 return error("AcceptBlock() : rejected by synchronized checkpoint");
1969 // Write block to history file
1970 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
1971 return error("AcceptBlock() : out of disk space");
1972 unsigned int nFile = -1;
1973 unsigned int nBlockPos = 0;
1974 if (!WriteToDisk(nFile, nBlockPos))
1975 return error("AcceptBlock() : WriteToDisk failed");
1976 if (!AddToBlockIndex(nFile, nBlockPos))
1977 return error("AcceptBlock() : AddToBlockIndex failed");
1979 // Relay inventory, but don't relay old inventory during initial block download
1980 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1981 if (hashBestChain == hash)
1984 BOOST_FOREACH(CNode* pnode, vNodes)
1985 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1986 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1989 // ppcoin: check pending sync-checkpoint
1990 Checkpoints::AcceptPendingSyncCheckpoint();
1995 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1997 // Check for duplicate
1998 uint256 hash = pblock->GetHash();
1999 if (mapBlockIndex.count(hash))
2000 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2001 if (mapOrphanBlocks.count(hash))
2002 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2004 // ppcoin: check proof-of-stake
2005 // Limited duplicity on stake: prevents block flood attack
2006 // Duplicate stake allowed only when there is orphan child block
2007 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2008 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());
2010 // Preliminary checks
2011 if (!pblock->CheckBlock())
2012 return error("ProcessBlock() : CheckBlock FAILED");
2014 // ppcoin: verify hash target and signature of coinstake tx
2015 if (pblock->IsProofOfStake() && !pblock->vtx[1].CheckProofOfStake(pblock->nBits))
2016 return error("ProcessBlock() : check proof-of-stake failed for block %s", hash.ToString().c_str());
2018 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2019 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2021 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2022 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2024 bnNewBlock.SetCompact(pblock->nBits);
2026 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime));
2028 if (bnNewBlock > bnRequired)
2031 pfrom->Misbehaving(100);
2032 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2036 // ppcoin: ask for pending sync-checkpoint if any
2037 if (!IsInitialBlockDownload())
2038 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2040 // If don't already have its previous block, shunt it off to holding area until we get it
2041 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2043 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2044 CBlock* pblock2 = new CBlock(*pblock);
2045 // ppcoin: check proof-of-stake
2046 if (pblock2->IsProofOfStake())
2048 // Limited duplicity on stake: prevents block flood attack
2049 // Duplicate stake allowed only when there is orphan child block
2050 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2051 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());
2053 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2055 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2056 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2058 // Ask this guy to fill in what we're missing
2061 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2062 // ppcoin: getblocks may not obtain the ancestor block rejected
2063 // earlier by duplicate-stake check so we ask for it again directly
2064 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2070 if (!pblock->AcceptBlock())
2071 return error("ProcessBlock() : AcceptBlock FAILED");
2073 // Recursively process any orphan blocks that depended on this one
2074 vector<uint256> vWorkQueue;
2075 vWorkQueue.push_back(hash);
2076 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2078 uint256 hashPrev = vWorkQueue[i];
2079 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2080 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2083 CBlock* pblockOrphan = (*mi).second;
2084 if (pblockOrphan->AcceptBlock())
2085 vWorkQueue.push_back(pblockOrphan->GetHash());
2086 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2087 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2088 delete pblockOrphan;
2090 mapOrphanBlocksByPrev.erase(hashPrev);
2093 printf("ProcessBlock: ACCEPTED\n");
2095 // ppcoin: if responsible for sync-checkpoint send it
2096 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2097 Checkpoints::SendSyncCheckpoint(hashBestChain);
2102 // ppcoin: sign block
2103 bool CBlock::SignBlock(const CKeyStore& keystore)
2105 vector<valtype> vSolutions;
2106 txnouttype whichType;
2107 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
2109 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2111 if (whichType == TX_PUBKEY)
2114 const valtype& vchPubKey = vSolutions[0];
2116 if (!keystore.GetKey(Hash160(vchPubKey), key))
2118 if (key.GetPubKey() != vchPubKey)
2120 return key.Sign(GetHash(), vchBlockSig);
2125 // ppcoin: check block signature
2126 bool CBlock::CheckBlockSignature() const
2128 if (GetHash() == hashGenesisBlock)
2129 return vchBlockSig.empty();
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)
2139 const valtype& vchPubKey = vSolutions[0];
2141 if (!key.SetPubKey(vchPubKey))
2143 if (vchBlockSig.empty())
2145 return key.Verify(GetHash(), vchBlockSig);
2155 bool CheckDiskSpace(uint64 nAdditionalBytes)
2157 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2159 // Check for 15MB because database could create another 10MB log file at any time
2160 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
2163 string strMessage = _("Warning: Disk space is low");
2164 strMiscWarning = strMessage;
2165 printf("*** %s\n", strMessage.c_str());
2166 ThreadSafeMessageBox(strMessage, "PPCoin", wxOK | wxICON_EXCLAMATION | wxMODAL);
2173 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2177 FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
2180 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2182 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2191 static unsigned int nCurrentBlockFile = 1;
2193 FILE* AppendBlockFile(unsigned int& nFileRet)
2198 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2201 if (fseek(file, 0, SEEK_END) != 0)
2203 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2204 if (ftell(file) < 0x7F000000 - MAX_SIZE)
2206 nFileRet = nCurrentBlockFile;
2210 nCurrentBlockFile++;
2214 bool LoadBlockIndex(bool fAllowNew)
2218 hashGenesisBlock = hashGenesisBlockTestNet;
2219 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
2220 pchMessageStart[0] = 0xfa;
2221 pchMessageStart[1] = 0xbf;
2222 pchMessageStart[2] = 0xb5;
2223 pchMessageStart[3] = 0xda;
2230 if (!txdb.LoadBlockIndex())
2235 // Init with genesis block
2237 if (mapBlockIndex.empty())
2243 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
2244 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2245 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
2246 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
2247 // vMerkleTree: 4a5e1e
2250 const char* pszTimestamp = "MarketWatch 07/Nov/2011 Gold tops $1,790 to end at over six-week high";
2252 txNew.nTime = 1339538219;
2253 txNew.vin.resize(1);
2254 txNew.vout.resize(1);
2255 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2256 txNew.vout[0].SetEmpty();
2258 block.vtx.push_back(txNew);
2259 block.hashPrevBlock = 0;
2260 block.hashMerkleRoot = block.BuildMerkleTree();
2262 block.nTime = 1339540307;
2263 block.nBits = bnProofOfWorkLimit.GetCompact();
2264 block.nNonce = 1281822831;
2268 block.nTime = 1296688602;
2269 block.nBits = 0x1d07fff8;
2270 block.nNonce = 384568319;
2274 printf("%s\n", block.GetHash().ToString().c_str());
2275 printf("%s\n", hashGenesisBlock.ToString().c_str());
2276 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
2277 assert(block.hashMerkleRoot == uint256("0x1557f46a17fcf8843dbe4c0c0edfd1d17eeff2c3c48d73a59d11f5d176e4b54d"));
2279 assert(block.GetHash() == hashGenesisBlock);
2280 assert(block.CheckBlock());
2282 // Start new block file
2284 unsigned int nBlockPos;
2285 if (!block.WriteToDisk(nFile, nBlockPos))
2286 return error("LoadBlockIndex() : writing genesis block to disk failed");
2287 if (!block.AddToBlockIndex(nFile, nBlockPos))
2288 return error("LoadBlockIndex() : genesis block not accepted");
2290 // ppcoin: initialize synchronized checkpoint
2291 if (!Checkpoints::WriteSyncCheckpoint(hashGenesisBlock))
2292 return error("LoadBlockIndex() : failed to init sync checkpoint");
2295 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2298 string strPubKey = "";
2299 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2301 // write checkpoint master key to db
2303 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2304 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2305 if (!txdb.TxnCommit())
2306 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2307 if (!Checkpoints::ResetSyncCheckpoint())
2308 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2318 void PrintBlockTree()
2320 // precompute tree structure
2321 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2322 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2324 CBlockIndex* pindex = (*mi).second;
2325 mapNext[pindex->pprev].push_back(pindex);
2327 //while (rand() % 3 == 0)
2328 // mapNext[pindex->pprev].push_back(pindex);
2331 vector<pair<int, CBlockIndex*> > vStack;
2332 vStack.push_back(make_pair(0, pindexGenesisBlock));
2335 while (!vStack.empty())
2337 int nCol = vStack.back().first;
2338 CBlockIndex* pindex = vStack.back().second;
2341 // print split or gap
2342 if (nCol > nPrevCol)
2344 for (int i = 0; i < nCol-1; i++)
2348 else if (nCol < nPrevCol)
2350 for (int i = 0; i < nCol; i++)
2357 for (int i = 0; i < nCol; i++)
2362 block.ReadFromDisk(pindex);
2363 printf("%d (%u,%u) %s %08lx %s tx %d",
2367 block.GetHash().ToString().substr(0,20).c_str(),
2369 DateTimeStrFormat(block.GetBlockTime()).c_str(),
2372 PrintWallets(block);
2374 // put the main timechain first
2375 vector<CBlockIndex*>& vNext = mapNext[pindex];
2376 for (unsigned int i = 0; i < vNext.size(); i++)
2378 if (vNext[i]->pnext)
2380 swap(vNext[0], vNext[i]);
2386 for (unsigned int i = 0; i < vNext.size(); i++)
2387 vStack.push_back(make_pair(nCol+i, vNext[i]));
2400 //////////////////////////////////////////////////////////////////////////////
2405 map<uint256, CAlert> mapAlerts;
2406 CCriticalSection cs_mapAlerts;
2408 string GetWarnings(string strFor)
2411 string strStatusBar;
2413 if (GetBoolArg("-testsafemode"))
2416 // Misc warnings like out of disk space and clock is wrong
2417 if (strMiscWarning != "")
2420 strStatusBar = strMiscWarning;
2423 // Longer invalid proof-of-work chain
2424 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
2427 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2430 if (Checkpoints::hashInvalidCheckpoint != 0)
2433 strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2439 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2441 const CAlert& alert = item.second;
2442 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2444 nPriority = alert.nPriority;
2445 strStatusBar = alert.strStatusBar;
2450 if (strFor == "statusbar")
2451 return strStatusBar;
2452 else if (strFor == "rpc")
2454 assert(!"GetWarnings() : invalid parameter");
2458 bool CAlert::ProcessAlert()
2460 if (!CheckSignature())
2467 // Cancel previous alerts
2468 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2470 const CAlert& alert = (*mi).second;
2473 printf("cancelling alert %d\n", alert.nID);
2474 mapAlerts.erase(mi++);
2476 else if (!alert.IsInEffect())
2478 printf("expiring alert %d\n", alert.nID);
2479 mapAlerts.erase(mi++);
2485 // Check if this alert has been cancelled
2486 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2488 const CAlert& alert = item.second;
2489 if (alert.Cancels(*this))
2491 printf("alert already cancelled by %d\n", alert.nID);
2497 mapAlerts.insert(make_pair(GetHash(), *this));
2500 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2512 //////////////////////////////////////////////////////////////////////////////
2518 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2524 bool txInMap = false;
2527 txInMap = (mempool.exists(inv.hash));
2530 mapOrphanTransactions.count(inv.hash) ||
2531 txdb.ContainsTx(inv.hash);
2535 return mapBlockIndex.count(inv.hash) ||
2536 mapOrphanBlocks.count(inv.hash);
2538 // Don't know what it is, just say we already got one
2545 // The message start string is designed to be unlikely to occur in normal data.
2546 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2547 // a large 4-byte int at any alignment.
2548 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2551 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2553 static map<CService, vector<unsigned char> > mapReuseKey;
2554 RandAddSeedPerfmon();
2556 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
2557 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2559 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2561 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2569 if (strCommand == "version")
2571 // Each connection can only send one version message
2572 if (pfrom->nVersion != 0)
2574 pfrom->Misbehaving(1);
2582 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2583 if (pfrom->nVersion < MIN_PROTO_VERSION)
2585 // Since February 20, 2012, the protocol is initiated at version 209,
2586 // and earlier versions are no longer supported
2587 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2588 pfrom->fDisconnect = true;
2592 if (pfrom->nVersion == 10300)
2593 pfrom->nVersion = 300;
2595 vRecv >> addrFrom >> nNonce;
2597 vRecv >> pfrom->strSubVer;
2599 vRecv >> pfrom->nStartingHeight;
2601 // Disconnect if we connected to ourself
2602 if (nNonce == nLocalHostNonce && nNonce > 1)
2604 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2605 pfrom->fDisconnect = true;
2609 // ppcoin: record my external IP reported by peer
2610 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
2611 addrSeenByPeer = addrMe;
2613 // Be shy and don't send version until we hear
2614 if (pfrom->fInbound)
2615 pfrom->PushVersion();
2617 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2619 AddTimeData(pfrom->addr, nTime);
2622 pfrom->PushMessage("verack");
2623 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2625 if (!pfrom->fInbound)
2627 // Advertise our address
2628 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() &&
2629 !IsInitialBlockDownload())
2631 CAddress addr(addrLocalHost);
2632 addr.nTime = GetAdjustedTime();
2633 pfrom->PushAddress(addr);
2636 // Get recent addresses
2637 if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2639 pfrom->PushMessage("getaddr");
2640 pfrom->fGetAddr = true;
2642 addrman.Good(pfrom->addr);
2644 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2646 addrman.Add(addrFrom, addrFrom);
2647 addrman.Good(addrFrom);
2651 // Ask the first connected node for block updates
2652 static int nAskedForBlocks = 0;
2653 if (!pfrom->fClient &&
2654 (pfrom->nVersion < NOBLKS_VERSION_START ||
2655 pfrom->nVersion >= NOBLKS_VERSION_END) &&
2656 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2659 pfrom->PushGetBlocks(pindexBest, uint256(0));
2665 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2666 item.second.RelayTo(pfrom);
2669 // ppcoin: relay sync-checkpoint
2671 LOCK(Checkpoints::cs_hashSyncCheckpoint);
2672 if (!Checkpoints::checkpointMessage.IsNull())
2673 Checkpoints::checkpointMessage.RelayTo(pfrom);
2676 pfrom->fSuccessfullyConnected = true;
2678 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2680 cPeerBlockCounts.input(pfrom->nStartingHeight);
2682 // ppcoin: ask for pending sync-checkpoint if any
2683 if (!IsInitialBlockDownload())
2684 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2688 else if (pfrom->nVersion == 0)
2690 // Must have a version message before anything else
2691 pfrom->Misbehaving(1);
2696 else if (strCommand == "verack")
2698 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2702 else if (strCommand == "addr")
2704 vector<CAddress> vAddr;
2707 // Don't want addr from older versions unless seeding
2708 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2710 if (vAddr.size() > 1000)
2712 pfrom->Misbehaving(20);
2713 return error("message addr size() = %d", vAddr.size());
2716 // Store the new addresses
2717 int64 nNow = GetAdjustedTime();
2718 int64 nSince = nNow - 10 * 60;
2719 BOOST_FOREACH(CAddress& addr, vAddr)
2723 // ignore IPv6 for now, since it isn't implemented anyway
2726 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2727 addr.nTime = nNow - 5 * 24 * 60 * 60;
2728 pfrom->AddAddressKnown(addr);
2729 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2731 // Relay to a limited number of other nodes
2734 // Use deterministic randomness to send to the same nodes for 24 hours
2735 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2736 static uint256 hashSalt;
2738 hashSalt = GetRandHash();
2739 int64 hashAddr = addr.GetHash();
2740 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2741 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2742 multimap<uint256, CNode*> mapMix;
2743 BOOST_FOREACH(CNode* pnode, vNodes)
2745 if (pnode->nVersion < CADDR_TIME_VERSION)
2747 unsigned int nPointer;
2748 memcpy(&nPointer, &pnode, sizeof(nPointer));
2749 uint256 hashKey = hashRand ^ nPointer;
2750 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2751 mapMix.insert(make_pair(hashKey, pnode));
2753 int nRelayNodes = 2;
2754 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2755 ((*mi).second)->PushAddress(addr);
2759 addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60);
2760 if (vAddr.size() < 1000)
2761 pfrom->fGetAddr = false;
2765 else if (strCommand == "inv")
2769 if (vInv.size() > 50000)
2771 pfrom->Misbehaving(20);
2772 return error("message inv size() = %d", vInv.size());
2775 // find last block in inv vector
2776 unsigned int nLastBlock = (unsigned int)(-1);
2777 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
2778 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
2779 nLastBlock = vInv.size() - 1 - nInv;
2784 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
2786 const CInv &inv = vInv[nInv];
2790 pfrom->AddInventoryKnown(inv);
2792 bool fAlreadyHave = AlreadyHave(txdb, inv);
2794 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2798 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
2799 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2800 } else if (nInv == nLastBlock) {
2801 // In case we are on a very long side-chain, it is possible that we already have
2802 // the last block in an inv bundle sent in response to getblocks. Try to detect
2803 // this situation and push another getblocks to continue.
2804 std::vector<CInv> vGetData(1,inv);
2805 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
2807 printf("force request: %s\n", inv.ToString().c_str());
2810 // Track requests for our stuff
2811 Inventory(inv.hash);
2816 else if (strCommand == "getdata")
2820 if (vInv.size() > 50000)
2822 pfrom->Misbehaving(20);
2823 return error("message getdata size() = %d", vInv.size());
2826 BOOST_FOREACH(const CInv& inv, vInv)
2830 printf("received getdata for: %s\n", inv.ToString().c_str());
2832 if (inv.type == MSG_BLOCK)
2834 // Send block from disk
2835 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2836 if (mi != mapBlockIndex.end())
2839 block.ReadFromDisk((*mi).second);
2840 pfrom->PushMessage("block", block);
2842 // Trigger them to send a getblocks request for the next batch of inventory
2843 if (inv.hash == pfrom->hashContinue)
2845 // Bypass PushInventory, this must send even if redundant,
2846 // and we want it right after the last block so they don't
2847 // wait for other stuff first.
2848 // ppcoin: send latest proof-of-work block to allow the
2849 // download node to accept as orphan (proof-of-stake
2850 // block might be rejected by stake connection check)
2852 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
2853 pfrom->PushMessage("inv", vInv);
2854 pfrom->hashContinue = 0;
2858 else if (inv.IsKnownType())
2860 // Send stream from relay memory
2863 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2864 if (mi != mapRelay.end())
2865 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2869 // Track requests for our stuff
2870 Inventory(inv.hash);
2875 else if (strCommand == "getblocks")
2877 CBlockLocator locator;
2879 vRecv >> locator >> hashStop;
2881 // Find the last block the caller has in the main chain
2882 CBlockIndex* pindex = locator.GetBlockIndex();
2884 // Send the rest of the chain
2886 pindex = pindex->pnext;
2887 int nLimit = 500 + locator.GetDistanceBack();
2888 unsigned int nBytes = 0;
2889 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2890 for (; pindex; pindex = pindex->pnext)
2892 if (pindex->GetBlockHash() == hashStop)
2894 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2897 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2899 block.ReadFromDisk(pindex, true);
2900 nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
2901 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2903 // When this block is requested, we'll send an inv that'll make them
2904 // getblocks the next batch of inventory.
2905 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2906 pfrom->hashContinue = pindex->GetBlockHash();
2913 else if (strCommand == "getheaders")
2915 CBlockLocator locator;
2917 vRecv >> locator >> hashStop;
2919 CBlockIndex* pindex = NULL;
2920 if (locator.IsNull())
2922 // If locator is null, return the hashStop block
2923 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2924 if (mi == mapBlockIndex.end())
2926 pindex = (*mi).second;
2930 // Find the last block the caller has in the main chain
2931 pindex = locator.GetBlockIndex();
2933 pindex = pindex->pnext;
2936 vector<CBlock> vHeaders;
2938 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
2939 for (; pindex; pindex = pindex->pnext)
2941 vHeaders.push_back(pindex->GetBlockHeader());
2942 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2945 pfrom->PushMessage("headers", vHeaders);
2949 else if (strCommand == "tx")
2951 vector<uint256> vWorkQueue;
2952 vector<uint256> vEraseQueue;
2953 CDataStream vMsg(vRecv);
2958 CInv inv(MSG_TX, tx.GetHash());
2959 pfrom->AddInventoryKnown(inv);
2961 bool fMissingInputs = false;
2962 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
2964 SyncWithWallets(tx, NULL, true);
2965 RelayMessage(inv, vMsg);
2966 mapAlreadyAskedFor.erase(inv);
2967 vWorkQueue.push_back(inv.hash);
2968 vEraseQueue.push_back(inv.hash);
2970 // Recursively process any orphan transactions that depended on this one
2971 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2973 uint256 hashPrev = vWorkQueue[i];
2974 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
2975 mi != mapOrphanTransactionsByPrev[hashPrev].end();
2978 const CDataStream& vMsg = *((*mi).second);
2980 CDataStream(vMsg) >> tx;
2981 CInv inv(MSG_TX, tx.GetHash());
2982 bool fMissingInputs2 = false;
2984 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
2986 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2987 SyncWithWallets(tx, NULL, true);
2988 RelayMessage(inv, vMsg);
2989 mapAlreadyAskedFor.erase(inv);
2990 vWorkQueue.push_back(inv.hash);
2991 vEraseQueue.push_back(inv.hash);
2993 else if (!fMissingInputs2)
2996 vEraseQueue.push_back(inv.hash);
2997 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3002 BOOST_FOREACH(uint256 hash, vEraseQueue)
3003 EraseOrphanTx(hash);
3005 else if (fMissingInputs)
3009 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3010 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3012 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3014 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3018 else if (strCommand == "block")
3023 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3026 CInv inv(MSG_BLOCK, block.GetHash());
3027 pfrom->AddInventoryKnown(inv);
3029 if (ProcessBlock(pfrom, &block))
3030 mapAlreadyAskedFor.erase(inv);
3031 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3035 else if (strCommand == "getaddr")
3037 pfrom->vAddrToSend.clear();
3038 vector<CAddress> vAddr = addrman.GetAddr();
3039 BOOST_FOREACH(const CAddress &addr, vAddr)
3040 pfrom->PushAddress(addr);
3044 else if (strCommand == "checkorder")
3049 if (!GetBoolArg("-allowreceivebyip"))
3051 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3058 /// we have a chance to check the order here
3060 // Keep giving the same key to the same ip until they use it
3061 if (!mapReuseKey.count(pfrom->addr))
3062 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3064 // Send back approval of order and pubkey to use
3065 CScript scriptPubKey;
3066 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3067 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3071 else if (strCommand == "reply")
3076 CRequestTracker tracker;
3078 LOCK(pfrom->cs_mapRequests);
3079 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3080 if (mi != pfrom->mapRequests.end())
3082 tracker = (*mi).second;
3083 pfrom->mapRequests.erase(mi);
3086 if (!tracker.IsNull())
3087 tracker.fn(tracker.param1, vRecv);
3091 else if (strCommand == "ping")
3093 if (pfrom->nVersion > BIP0031_VERSION)
3097 // Echo the message back with the nonce. This allows for two useful features:
3099 // 1) A remote node can quickly check if the connection is operational
3100 // 2) Remote nodes can measure the latency of the network thread. If this node
3101 // is overloaded it won't respond to pings quickly and the remote node can
3102 // avoid sending us more work, like chain download requests.
3104 // The nonce stops the remote getting confused between different pings: without
3105 // it, if the remote node sends a ping once per second and this node takes 5
3106 // seconds to respond to each, the 5th ping the remote sends would appear to
3107 // return very quickly.
3108 pfrom->PushMessage("pong", nonce);
3113 else if (strCommand == "alert")
3118 if (alert.ProcessAlert())
3121 pfrom->setKnown.insert(alert.GetHash());
3124 BOOST_FOREACH(CNode* pnode, vNodes)
3125 alert.RelayTo(pnode);
3130 else if (strCommand == "checkpoint")
3132 CSyncCheckpoint checkpoint;
3133 vRecv >> checkpoint;
3135 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3138 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3140 BOOST_FOREACH(CNode* pnode, vNodes)
3141 checkpoint.RelayTo(pnode);
3147 // Ignore unknown commands for extensibility
3151 // Update the last seen time for this node's address
3152 if (pfrom->fNetworkNode)
3153 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3154 AddressCurrentlyConnected(pfrom->addr);
3160 bool ProcessMessages(CNode* pfrom)
3162 CDataStream& vRecv = pfrom->vRecv;
3166 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3170 // (4) message start
3179 // Scan for message start
3180 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3181 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3182 if (vRecv.end() - pstart < nHeaderSize)
3184 if ((int)vRecv.size() > nHeaderSize)
3186 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3187 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3191 if (pstart - vRecv.begin() > 0)
3192 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
3193 vRecv.erase(vRecv.begin(), pstart);
3196 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3201 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3204 string strCommand = hdr.GetCommand();
3207 unsigned int nMessageSize = hdr.nMessageSize;
3208 if (nMessageSize > MAX_SIZE)
3210 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3213 if (nMessageSize > vRecv.size())
3215 // Rewind and wait for rest of message
3216 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3221 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3222 unsigned int nChecksum = 0;
3223 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3224 if (nChecksum != hdr.nChecksum)
3226 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3227 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3231 // Copy message to its own buffer
3232 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3233 vRecv.ignore(nMessageSize);
3241 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3246 catch (std::ios_base::failure& e)
3248 if (strstr(e.what(), "end of data"))
3250 // Allow exceptions from underlength message on vRecv
3251 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());
3253 else if (strstr(e.what(), "size too large"))
3255 // Allow exceptions from overlong size
3256 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3260 PrintExceptionContinue(&e, "ProcessMessages()");
3263 catch (std::exception& e) {
3264 PrintExceptionContinue(&e, "ProcessMessages()");
3266 PrintExceptionContinue(NULL, "ProcessMessages()");
3270 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3278 bool SendMessages(CNode* pto, bool fSendTrickle)
3280 TRY_LOCK(cs_main, lockMain);
3282 // Don't send anything until we get their version message
3283 if (pto->nVersion == 0)
3286 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3288 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3290 if (pto->nVersion > BIP0031_VERSION)
3291 pto->PushMessage("ping", nonce);
3293 pto->PushMessage("ping");
3296 // Resend wallet transactions that haven't gotten in a block yet
3297 ResendWalletTransactions();
3299 // Address refresh broadcast
3300 static int64 nLastRebroadcast;
3301 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3305 BOOST_FOREACH(CNode* pnode, vNodes)
3307 // Periodically clear setAddrKnown to allow refresh broadcasts
3308 if (nLastRebroadcast)
3309 pnode->setAddrKnown.clear();
3311 // Rebroadcast our address
3312 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable())
3314 CAddress addr(addrLocalHost);
3315 addr.nTime = GetAdjustedTime();
3316 pnode->PushAddress(addr);
3320 nLastRebroadcast = GetTime();
3328 vector<CAddress> vAddr;
3329 vAddr.reserve(pto->vAddrToSend.size());
3330 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3332 // returns true if wasn't already contained in the set
3333 if (pto->setAddrKnown.insert(addr).second)
3335 vAddr.push_back(addr);
3336 // receiver rejects addr messages larger than 1000
3337 if (vAddr.size() >= 1000)
3339 pto->PushMessage("addr", vAddr);
3344 pto->vAddrToSend.clear();
3346 pto->PushMessage("addr", vAddr);
3351 // Message: inventory
3354 vector<CInv> vInvWait;
3356 LOCK(pto->cs_inventory);
3357 vInv.reserve(pto->vInventoryToSend.size());
3358 vInvWait.reserve(pto->vInventoryToSend.size());
3359 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3361 if (pto->setInventoryKnown.count(inv))
3364 // trickle out tx inv to protect privacy
3365 if (inv.type == MSG_TX && !fSendTrickle)
3367 // 1/4 of tx invs blast to all immediately
3368 static uint256 hashSalt;
3370 hashSalt = GetRandHash();
3371 uint256 hashRand = inv.hash ^ hashSalt;
3372 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3373 bool fTrickleWait = ((hashRand & 3) != 0);
3375 // always trickle our own transactions
3379 if (GetTransaction(inv.hash, wtx))
3381 fTrickleWait = true;
3386 vInvWait.push_back(inv);
3391 // returns true if wasn't already contained in the set
3392 if (pto->setInventoryKnown.insert(inv).second)
3394 vInv.push_back(inv);
3395 if (vInv.size() >= 1000)
3397 pto->PushMessage("inv", vInv);
3402 pto->vInventoryToSend = vInvWait;
3405 pto->PushMessage("inv", vInv);
3411 vector<CInv> vGetData;
3412 int64 nNow = GetTime() * 1000000;
3414 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3416 const CInv& inv = (*pto->mapAskFor.begin()).second;
3417 if (!AlreadyHave(txdb, inv))
3419 printf("sending getdata: %s\n", inv.ToString().c_str());
3420 vGetData.push_back(inv);
3421 if (vGetData.size() >= 1000)
3423 pto->PushMessage("getdata", vGetData);
3427 mapAlreadyAskedFor[inv] = nNow;
3428 pto->mapAskFor.erase(pto->mapAskFor.begin());
3430 if (!vGetData.empty())
3431 pto->PushMessage("getdata", vGetData);
3450 //////////////////////////////////////////////////////////////////////////////
3455 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3457 unsigned char* pdata = (unsigned char*)pbuffer;
3458 unsigned int blocks = 1 + ((len + 8) / 64);
3459 unsigned char* pend = pdata + 64 * blocks;
3460 memset(pdata + len, 0, 64 * blocks - len);
3462 unsigned int bits = len * 8;
3463 pend[-1] = (bits >> 0) & 0xff;
3464 pend[-2] = (bits >> 8) & 0xff;
3465 pend[-3] = (bits >> 16) & 0xff;
3466 pend[-4] = (bits >> 24) & 0xff;
3470 static const unsigned int pSHA256InitState[8] =
3471 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3473 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3476 unsigned char data[64];
3480 for (int i = 0; i < 16; i++)
3481 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3483 for (int i = 0; i < 8; i++)
3484 ctx.h[i] = ((uint32_t*)pinit)[i];
3486 SHA256_Update(&ctx, data, sizeof(data));
3487 for (int i = 0; i < 8; i++)
3488 ((uint32_t*)pstate)[i] = ctx.h[i];
3492 // ScanHash scans nonces looking for a hash with at least some zero bits.
3493 // It operates on big endian data. Caller does the byte reversing.
3494 // All input buffers are 16-byte aligned. nNonce is usually preserved
3495 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3496 // the block is rebuilt and nNonce starts over at zero.
3498 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3500 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3504 // Hash pdata using pmidstate as the starting state into
3505 // preformatted buffer phash1, then hash phash1 into phash
3507 SHA256Transform(phash1, pdata, pmidstate);
3508 SHA256Transform(phash, phash1, pSHA256InitState);
3510 // Return the nonce if the hash has at least some zero bits,
3511 // caller will check if it has enough to reach the target
3512 if (((unsigned short*)phash)[14] == 0)
3515 // If nothing found after trying for a while, return -1
3516 if ((nNonce & 0xffff) == 0)
3518 nHashesDone = 0xffff+1;
3519 return (unsigned int) -1;
3524 // Some explaining would be appreciated
3529 set<uint256> setDependsOn;
3532 COrphan(CTransaction* ptxIn)
3540 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3541 BOOST_FOREACH(uint256 hash, setDependsOn)
3542 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3547 uint64 nLastBlockTx = 0;
3548 uint64 nLastBlockSize = 0;
3550 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfWorkOnly)
3552 CReserveKey reservekey(pwallet);
3555 auto_ptr<CBlock> pblock(new CBlock());
3559 // Create coinbase tx
3561 txNew.vin.resize(1);
3562 txNew.vin[0].prevout.SetNull();
3563 txNew.vout.resize(1);
3564 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3566 // Add our coinbase tx as first transaction
3567 pblock->vtx.push_back(txNew);
3569 // ppcoin: if coinstake available add coinstake tx
3570 static unsigned int nLastCoinStakeCheckTime = GetAdjustedTime() - nMaxClockDrift + 60; // only initialized at startup
3571 CBlockIndex* pindexPrev = pindexBest;
3573 if (!fProofOfWorkOnly)
3575 while (nLastCoinStakeCheckTime < GetAdjustedTime())
3577 pindexPrev = pindexBest; // get best block again to avoid getting stale
3578 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
3579 CTransaction txCoinStake;
3581 static CCriticalSection cs;
3583 // mining may have been suspended for a while so
3584 // need to take max to satisfy the timestamp protocol
3585 nLastCoinStakeCheckTime++;
3586 nLastCoinStakeCheckTime = max(nLastCoinStakeCheckTime, (unsigned int) (GetAdjustedTime() - nMaxClockDrift + 60));
3587 txCoinStake.nTime = nLastCoinStakeCheckTime;
3589 if (pwallet->CreateCoinStake(pblock->nBits, txCoinStake))
3591 pblock->vtx.push_back(txCoinStake);
3592 pblock->vtx[0].vout[0].SetEmpty();
3598 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
3600 // Collect memory pool transactions into the block
3603 LOCK2(cs_main, mempool.cs);
3606 // Priority order to process transactions
3607 list<COrphan> vOrphan; // list memory doesn't move
3608 map<uint256, vector<COrphan*> > mapDependers;
3609 multimap<double, CTransaction*> mapPriority;
3610 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3612 CTransaction& tx = (*mi).second;
3613 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
3616 COrphan* porphan = NULL;
3617 double dPriority = 0;
3618 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3620 // Read prev transaction
3621 CTransaction txPrev;
3623 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3625 // Has to wait for dependencies
3628 // Use list for automatic deletion
3629 vOrphan.push_back(COrphan(&tx));
3630 porphan = &vOrphan.back();
3632 mapDependers[txin.prevout.hash].push_back(porphan);
3633 porphan->setDependsOn.insert(txin.prevout.hash);
3636 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3638 // Read block header
3639 int nConf = txindex.GetDepthInMainChain();
3641 dPriority += (double)nValueIn * nConf;
3643 if (fDebug && GetBoolArg("-printpriority"))
3644 printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3647 // Priority is sum(valuein * age) / txsize
3648 dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3651 porphan->dPriority = dPriority;
3653 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3655 if (fDebug && GetBoolArg("-printpriority"))
3657 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3664 // Collect transactions into block
3665 map<uint256, CTxIndex> mapTestPool;
3666 uint64 nBlockSize = 1000;
3667 uint64 nBlockTx = 0;
3668 int nBlockSigOps = 100;
3669 while (!mapPriority.empty())
3671 // Take highest priority transaction off priority queue
3672 CTransaction& tx = *(*mapPriority.begin()).second;
3673 mapPriority.erase(mapPriority.begin());
3676 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3677 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3680 // Legacy limits on sigOps:
3681 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
3682 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3686 if (tx.nTime > GetAdjustedTime())
3689 // ppcoin: simplify transaction fee - allow free = false
3690 int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
3692 // Connecting shouldn't fail due to dependency on other memory pool transactions
3693 // because we're already processing them in order of dependency
3694 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3695 MapPrevTx mapInputs;
3697 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3700 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3701 if (nTxFees < nMinFee)
3704 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3705 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3708 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3710 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3711 swap(mapTestPool, mapTestPoolTmp);
3714 pblock->vtx.push_back(tx);
3715 nBlockSize += nTxSize;
3717 nBlockSigOps += nTxSigOps;
3720 // Add transactions that depend on this one to the priority queue
3721 uint256 hash = tx.GetHash();
3722 if (mapDependers.count(hash))
3724 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3726 if (!porphan->setDependsOn.empty())
3728 porphan->setDependsOn.erase(hash);
3729 if (porphan->setDependsOn.empty())
3730 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3736 nLastBlockTx = nBlockTx;
3737 nLastBlockSize = nBlockSize;
3738 printf("CreateNewBlock(): total size %lu\n", nBlockSize);
3741 if (pblock->IsProofOfWork())
3742 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
3745 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3746 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3747 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3748 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
3749 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
3750 pblock->UpdateTime(pindexPrev);
3753 return pblock.release();
3757 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3759 // Update nExtraNonce
3760 static uint256 hashPrevBlock;
3761 if (hashPrevBlock != pblock->hashPrevBlock)
3764 hashPrevBlock = pblock->hashPrevBlock;
3767 pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
3768 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3770 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3774 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3777 // Prebuild hash buffers
3784 uint256 hashPrevBlock;
3785 uint256 hashMerkleRoot;
3788 unsigned int nNonce;
3791 unsigned char pchPadding0[64];
3793 unsigned char pchPadding1[64];
3796 memset(&tmp, 0, sizeof(tmp));
3798 tmp.block.nVersion = pblock->nVersion;
3799 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3800 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3801 tmp.block.nTime = pblock->nTime;
3802 tmp.block.nBits = pblock->nBits;
3803 tmp.block.nNonce = pblock->nNonce;
3805 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3806 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3808 // Byte swap all the input buffer
3809 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3810 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3812 // Precalc the first half of the first hash, which stays constant
3813 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3815 memcpy(pdata, &tmp.block, 128);
3816 memcpy(phash1, &tmp.hash1, 64);
3820 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3822 uint256 hash = pblock->GetHash();
3823 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3825 if (hash > hashTarget && pblock->IsProofOfWork())
3826 return error("BitcoinMiner : proof-of-work not meeting target");
3829 printf("BitcoinMiner:\n");
3830 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3832 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
3833 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3838 if (pblock->hashPrevBlock != hashBestChain)
3839 return error("BitcoinMiner : generated block is stale");
3841 // Remove key from key pool
3842 reservekey.KeepKey();
3844 // Track how many getdata requests this block gets
3846 LOCK(wallet.cs_wallet);
3847 wallet.mapRequestCount[pblock->GetHash()] = 0;
3850 // Process this block the same as if we had received it from another node
3851 if (!ProcessBlock(NULL, pblock))
3852 return error("BitcoinMiner : ProcessBlock, block not accepted");
3858 void static ThreadBitcoinMiner(void* parg);
3860 static bool fGenerateBitcoins = false;
3861 static bool fLimitProcessors = false;
3862 static int nLimitProcessors = -1;
3864 void static BitcoinMiner(CWallet *pwallet)
3866 printf("BitcoinMiner started\n");
3867 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3869 // Each thread has its own key and counter
3870 CReserveKey reservekey(pwallet);
3871 unsigned int nExtraNonce = 0;
3873 while (fGenerateBitcoins)
3877 while (vNodes.empty() || IsInitialBlockDownload())
3882 if (!fGenerateBitcoins)
3890 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3891 CBlockIndex* pindexPrev = pindexBest;
3893 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet));
3897 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3899 // ppcoin: if proof-of-stake block found then process block
3900 if (pblock->IsProofOfStake())
3902 if (!pblock->SignBlock(*pwalletMain))
3904 error("BitcoinMiner: Unable to sign new proof-of-stake block");
3907 printf("BitcoinMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
3908 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3909 CheckWork(pblock.get(), *pwalletMain, reservekey);
3910 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3914 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3918 // Prebuild hash buffers
3920 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3921 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3922 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3924 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3926 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3927 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3933 int64 nStart = GetTime();
3934 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3936 uint256& hash = *alignup<16>(hashbuf);
3939 unsigned int nHashesDone = 0;
3940 unsigned int nNonceFound;
3943 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3944 (char*)&hash, nHashesDone);
3946 // Check if something found
3947 if (nNonceFound != (unsigned int) -1)
3949 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
3950 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3952 if (hash <= hashTarget)
3955 pblock->nNonce = ByteReverse(nNonceFound);
3956 assert(hash == pblock->GetHash());
3957 if (!pblock->SignBlock(*pwalletMain))
3959 error("BitcoinMiner: Unable to sign new proof-of-work block");
3963 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3964 CheckWork(pblock.get(), *pwalletMain, reservekey);
3965 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3971 static int64 nHashCounter;
3972 if (nHPSTimerStart == 0)
3974 nHPSTimerStart = GetTimeMillis();
3978 nHashCounter += nHashesDone;
3979 if (GetTimeMillis() - nHPSTimerStart > 4000)
3981 static CCriticalSection cs;
3984 if (GetTimeMillis() - nHPSTimerStart > 4000)
3986 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3987 nHPSTimerStart = GetTimeMillis();
3989 static int64 nLogTime;
3990 if (GetTime() - nLogTime > 30 * 60)
3992 nLogTime = GetTime();
3993 printf("%s ", DateTimeStrFormat(GetTime()).c_str());
3994 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
4000 // Check for stop or if block needs to be rebuilt
4003 if (!fGenerateBitcoins)
4005 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4009 if (nBlockNonce >= 0xffff0000)
4011 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4013 if (pindexPrev != pindexBest)
4016 // Update nTime every few seconds
4017 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
4018 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
4019 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4020 pblock->UpdateTime(pindexPrev);
4021 nBlockTime = ByteReverse(pblock->nTime);
4022 if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
4023 break; // need to update coinbase timestamp
4028 void static ThreadBitcoinMiner(void* parg)
4030 CWallet* pwallet = (CWallet*)parg;
4033 vnThreadsRunning[THREAD_MINER]++;
4034 BitcoinMiner(pwallet);
4035 vnThreadsRunning[THREAD_MINER]--;
4037 catch (std::exception& e) {
4038 vnThreadsRunning[THREAD_MINER]--;
4039 PrintException(&e, "ThreadBitcoinMiner()");
4041 vnThreadsRunning[THREAD_MINER]--;
4042 PrintException(NULL, "ThreadBitcoinMiner()");
4045 if (vnThreadsRunning[THREAD_MINER] == 0)
4047 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4051 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4053 fGenerateBitcoins = fGenerate;
4054 nLimitProcessors = GetArg("-genproclimit", -1);
4055 if (nLimitProcessors == 0)
4056 fGenerateBitcoins = false;
4057 fLimitProcessors = (nLimitProcessors != -1);
4061 int nProcessors = boost::thread::hardware_concurrency();
4062 printf("%d processors\n", nProcessors);
4063 if (nProcessors < 1)
4065 if (fLimitProcessors && nProcessors > nLimitProcessors)
4066 nProcessors = nLimitProcessors;
4067 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4068 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4069 for (int i = 0; i < nAddThreads; i++)
4071 if (!CreateThread(ThreadBitcoinMiner, pwallet))
4072 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");