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 = "Bitcoin Signed Message:\n";
61 int64 nTransactionFee = MIN_TX_FEE;
62 int64 nBalanceReserve = 0;
66 //////////////////////////////////////////////////////////////////////////////
68 // dispatching functions
71 // These functions dispatch to one or all registered wallets
74 void RegisterWallet(CWallet* pwalletIn)
77 LOCK(cs_setpwalletRegistered);
78 setpwalletRegistered.insert(pwalletIn);
82 void UnregisterWallet(CWallet* pwalletIn)
85 LOCK(cs_setpwalletRegistered);
86 setpwalletRegistered.erase(pwalletIn);
90 // check whether the passed transaction is from us
91 bool static IsFromMe(CTransaction& tx)
93 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
94 if (pwallet->IsFromMe(tx))
99 // get the wallet transaction with the given hash (if it exists)
100 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
102 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
103 if (pwallet->GetTransaction(hashTx,wtx))
108 // erases transaction with the given hash from all wallets
109 void static EraseFromWallets(uint256 hash)
111 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
112 pwallet->EraseFromWallet(hash);
115 // make sure all wallets know about the given transaction, in the given block
116 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true)
120 // ppcoin: wallets need to refund inputs when disconnecting coinstake
121 if (tx.IsCoinStake())
123 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
124 if (pwallet->IsFromMe(tx))
125 pwallet->DisableTransaction(tx);
130 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
131 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
134 // notify wallets about a new best chain
135 void static SetBestChain(const CBlockLocator& loc)
137 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
138 pwallet->SetBestChain(loc);
141 // notify wallets about an updated transaction
142 void static UpdatedTransaction(const uint256& hashTx)
144 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
145 pwallet->UpdatedTransaction(hashTx);
149 void static PrintWallets(const CBlock& block)
151 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
152 pwallet->PrintWallet(block);
155 // notify wallets about an incoming inventory (for request counts)
156 void static Inventory(const uint256& hash)
158 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
159 pwallet->Inventory(hash);
162 // ask wallets to resend their transactions
163 void static ResendWalletTransactions()
165 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
166 pwallet->ResendWalletTransactions();
175 //////////////////////////////////////////////////////////////////////////////
177 // mapOrphanTransactions
180 bool AddOrphanTx(const CDataStream& vMsg)
183 CDataStream(vMsg) >> tx;
184 uint256 hash = tx.GetHash();
185 if (mapOrphanTransactions.count(hash))
188 CDataStream* pvMsg = new CDataStream(vMsg);
190 // Ignore big transactions, to avoid a
191 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
192 // large transaction with a missing parent then we assume
193 // it will rebroadcast it later, after the parent transaction(s)
194 // have been mined or received.
195 // 10,000 orphans, each of which is at most 5,000 bytes big is
196 // at most 500 megabytes of orphans:
197 if (pvMsg->size() > 5000)
199 printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
204 mapOrphanTransactions[hash] = pvMsg;
205 BOOST_FOREACH(const CTxIn& txin, tx.vin)
206 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
208 printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
209 mapOrphanTransactions.size());
213 void static EraseOrphanTx(uint256 hash)
215 if (!mapOrphanTransactions.count(hash))
217 const CDataStream* pvMsg = mapOrphanTransactions[hash];
219 CDataStream(*pvMsg) >> tx;
220 BOOST_FOREACH(const CTxIn& txin, tx.vin)
222 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
223 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
224 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
227 mapOrphanTransactions.erase(hash);
230 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
232 unsigned int nEvicted = 0;
233 while (mapOrphanTransactions.size() > nMaxOrphans)
235 // Evict a random orphan:
236 uint256 randomhash = GetRandHash();
237 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
238 if (it == mapOrphanTransactions.end())
239 it = mapOrphanTransactions.begin();
240 EraseOrphanTx(it->first);
252 //////////////////////////////////////////////////////////////////////////////
254 // CTransaction and CTxIndex
257 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
260 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
262 if (!ReadFromDisk(txindexRet.pos))
264 if (prevout.n >= vout.size())
272 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
275 return ReadFromDisk(txdb, prevout, txindex);
278 bool CTransaction::ReadFromDisk(COutPoint prevout)
282 return ReadFromDisk(txdb, prevout, txindex);
285 bool CTransaction::IsStandard() const
287 BOOST_FOREACH(const CTxIn& txin, vin)
289 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
290 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
291 // ~65-byte public keys, plus a few script ops.
292 if (txin.scriptSig.size() > 500)
294 if (!txin.scriptSig.IsPushOnly())
297 BOOST_FOREACH(const CTxOut& txout, vout)
298 if (!::IsStandard(txout.scriptPubKey))
304 // Check transaction inputs, and make sure any
305 // pay-to-script-hash transactions are evaluating IsStandard scripts
307 // Why bother? To avoid denial-of-service attacks; an attacker
308 // can submit a standard HASH... OP_EQUAL transaction,
309 // which will get accepted into blocks. The redemption
310 // script can be anything; an attacker could use a very
311 // expensive-to-check-upon-redemption script like:
312 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
314 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
317 return true; // Coinbases don't use vin normally
319 for (unsigned int i = 0; i < vin.size(); i++)
321 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
323 vector<vector<unsigned char> > vSolutions;
324 txnouttype whichType;
325 // get the scriptPubKey corresponding to this input:
326 const CScript& prevScript = prev.scriptPubKey;
327 if (!Solver(prevScript, whichType, vSolutions))
329 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
330 if (nArgsExpected < 0)
333 // Transactions with extra stuff in their scriptSigs are
334 // non-standard. Note that this EvalScript() call will
335 // be quick, because if there are any operations
336 // beside "push data" in the scriptSig the
337 // IsStandard() call returns false
338 vector<vector<unsigned char> > stack;
339 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
342 if (whichType == TX_SCRIPTHASH)
346 CScript subscript(stack.back().begin(), stack.back().end());
347 vector<vector<unsigned char> > vSolutions2;
348 txnouttype whichType2;
349 if (!Solver(subscript, whichType2, vSolutions2))
351 if (whichType2 == TX_SCRIPTHASH)
355 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
358 nArgsExpected += tmpExpected;
361 if (stack.size() != (unsigned int)nArgsExpected)
369 CTransaction::GetLegacySigOpCount() const
371 unsigned int nSigOps = 0;
372 BOOST_FOREACH(const CTxIn& txin, vin)
374 nSigOps += txin.scriptSig.GetSigOpCount(false);
376 BOOST_FOREACH(const CTxOut& txout, vout)
378 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
384 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
396 // Load the block this tx is in
398 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
400 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
405 // Update the tx's hashBlock
406 hashBlock = pblock->GetHash();
408 // Locate the transaction
409 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
410 if (pblock->vtx[nIndex] == *(CTransaction*)this)
412 if (nIndex == (int)pblock->vtx.size())
414 vMerkleBranch.clear();
416 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
420 // Fill in merkle branch
421 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
424 // Is the tx in a block that's in the main chain
425 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
426 if (mi == mapBlockIndex.end())
428 CBlockIndex* pindex = (*mi).second;
429 if (!pindex || !pindex->IsInMainChain())
432 return pindexBest->nHeight - pindex->nHeight + 1;
441 bool CTransaction::CheckTransaction() const
443 // Basic checks that don't depend on any context
445 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
447 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
449 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
450 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
452 // Check for negative or overflow output values
454 for (int i = 0; i < vout.size(); i++)
456 const CTxOut& txout = vout[i];
457 if (txout.IsEmpty() && (!IsCoinBase()) && (!IsCoinStake()))
458 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
459 if (txout.nValue < 0)
460 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
461 if (txout.nValue > MAX_MONEY)
462 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
463 nValueOut += txout.nValue;
464 if (!MoneyRange(nValueOut))
465 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
468 // Check for duplicate inputs
469 set<COutPoint> vInOutPoints;
470 BOOST_FOREACH(const CTxIn& txin, vin)
472 if (vInOutPoints.count(txin.prevout))
474 vInOutPoints.insert(txin.prevout);
479 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
480 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
484 BOOST_FOREACH(const CTxIn& txin, vin)
485 if (txin.prevout.IsNull())
486 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
492 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
493 bool* pfMissingInputs)
496 *pfMissingInputs = false;
498 if (!tx.CheckTransaction())
499 return error("CTxMemPool::accept() : CheckTransaction failed");
501 // Coinbase is only valid in a block, not as a loose transaction
503 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
504 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
505 if (tx.IsCoinStake())
506 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
508 // To help v0.1.5 clients who would see it as a negative number
509 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
510 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
512 // Rather not work on nonstandard transactions (unless -testnet)
513 if (!fTestNet && !tx.IsStandard())
514 return error("CTxMemPool::accept() : nonstandard transaction type");
516 // Do we already have it?
517 uint256 hash = tx.GetHash();
520 if (mapTx.count(hash))
524 if (txdb.ContainsTx(hash))
527 // Check for conflicts with in-memory transactions
528 CTransaction* ptxOld = NULL;
529 for (unsigned int i = 0; i < tx.vin.size(); i++)
531 COutPoint outpoint = tx.vin[i].prevout;
532 if (mapNextTx.count(outpoint))
534 // Disable replacement feature for now
537 // Allow replacing with a newer version of the same transaction
540 ptxOld = mapNextTx[outpoint].ptx;
541 if (ptxOld->IsFinal())
543 if (!tx.IsNewerThan(*ptxOld))
545 for (unsigned int i = 0; i < tx.vin.size(); i++)
547 COutPoint outpoint = tx.vin[i].prevout;
548 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
558 map<uint256, CTxIndex> mapUnused;
559 bool fInvalid = false;
560 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
563 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
565 *pfMissingInputs = true;
566 return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
569 // Check for non-standard pay-to-script-hash in inputs
570 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
571 return error("CTxMemPool::accept() : nonstandard transaction input");
573 // Note: if you modify this code to accept non-standard transactions, then
574 // you should add code here to check that the transaction does a
575 // reasonable number of ECDSA signature verifications.
577 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
578 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
580 // Don't accept it if it can't get into a block
581 if (nFees < tx.GetMinFee(1000, false, GMF_RELAY))
582 return error("CTxMemPool::accept() : not enough fees");
584 // Continuously rate-limit free transactions
585 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
586 // be annoying or make other's transactions take longer to confirm.
587 if (nFees < MIN_RELAY_TX_FEE)
589 static CCriticalSection cs;
590 static double dFreeCount;
591 static int64 nLastTime;
592 int64 nNow = GetTime();
596 // Use an exponentially decaying ~10-minute window:
597 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
599 // -limitfreerelay unit is thousand-bytes-per-minute
600 // At default rate it would take over a month to fill 1GB
601 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
602 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
604 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
609 // Check against previous transactions
610 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
611 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
613 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
617 // Store transaction in memory
622 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
628 ///// are we sure this is ok when loading transactions or restoring block txes
629 // If updated, erase old tx from wallet
631 EraseFromWallets(ptxOld->GetHash());
633 printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str());
637 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
639 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
642 bool CTxMemPool::addUnchecked(CTransaction &tx)
644 printf("addUnchecked(): size %lu\n", mapTx.size());
645 // Add to memory pool without checking anything. Don't call this directly,
646 // call CTxMemPool::accept to properly check the transaction first.
649 uint256 hash = tx.GetHash();
651 for (unsigned int i = 0; i < tx.vin.size(); i++)
652 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
653 nTransactionsUpdated++;
659 bool CTxMemPool::remove(CTransaction &tx)
661 // Remove transaction from memory pool
664 uint256 hash = tx.GetHash();
665 if (mapTx.count(hash))
667 BOOST_FOREACH(const CTxIn& txin, tx.vin)
668 mapNextTx.erase(txin.prevout);
670 nTransactionsUpdated++;
681 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
683 if (hashBlock == 0 || nIndex == -1)
686 // Find the block it claims to be in
687 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
688 if (mi == mapBlockIndex.end())
690 CBlockIndex* pindex = (*mi).second;
691 if (!pindex || !pindex->IsInMainChain())
694 // Make sure the merkle branch connects to this block
695 if (!fMerkleVerified)
697 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
699 fMerkleVerified = true;
703 return pindexBest->nHeight - pindex->nHeight + 1;
707 int CMerkleTx::GetBlocksToMaturity() const
709 if (!(IsCoinBase() || IsCoinStake()))
711 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
715 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
719 if (!IsInMainChain() && !ClientConnectInputs())
721 return CTransaction::AcceptToMemoryPool(txdb, false);
725 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
729 bool CMerkleTx::AcceptToMemoryPool()
732 return AcceptToMemoryPool(txdb);
737 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
742 // Add previous supporting transactions first
743 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
745 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
747 uint256 hash = tx.GetHash();
748 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
749 tx.AcceptToMemoryPool(txdb, fCheckInputs);
752 return AcceptToMemoryPool(txdb, fCheckInputs);
757 bool CWalletTx::AcceptWalletTransaction()
760 return AcceptWalletTransaction(txdb);
763 int CTxIndex::GetDepthInMainChain() const
767 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
769 // Find the block in the index
770 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
771 if (mi == mapBlockIndex.end())
773 CBlockIndex* pindex = (*mi).second;
774 if (!pindex || !pindex->IsInMainChain())
776 return 1 + nBestHeight - pindex->nHeight;
788 //////////////////////////////////////////////////////////////////////////////
790 // CBlock and CBlockIndex
793 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
795 if (!fReadTransactions)
797 *this = pindex->GetBlockHeader();
800 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
802 if (GetHash() != pindex->GetBlockHash())
803 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
807 uint256 static GetOrphanRoot(const CBlock* pblock)
809 // Work back to the first block in the orphan chain
810 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
811 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
812 return pblock->GetHash();
815 // ppcoin: find block wanted by given orphan block
816 uint256 WantedByOrphan(const CBlock* pblockOrphan)
818 // Work back to the first block in the orphan chain
819 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
820 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
821 return pblockOrphan->hashPrevBlock;
824 int64 static GetProofOfWorkReward(unsigned int nBits)
826 CBigNum bnSubsidyLimit = 9999 * COIN; // subsidy amount for difficulty 1
828 bnTarget.SetCompact(nBits);
829 CBigNum bnTargetLimit = bnProofOfWorkLimit;
830 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
832 // ppcoin: subsidy is cut in half every 16x multiply of difficulty
833 // A reasonably continuous curve is used to avoid shock to market
834 // (nSubsidyLimit / nSubsidy) ** 4 == bnProofOfWorkLimit / bnTarget
835 CBigNum bnLowerBound = CENT;
836 CBigNum bnUpperBound = bnSubsidyLimit;
837 while (bnLowerBound + CENT <= bnUpperBound)
839 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
840 if (fDebug && GetBoolArg("-printcreation"))
841 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
842 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
843 bnUpperBound = bnMidValue;
845 bnLowerBound = bnMidValue;
848 int64 nSubsidy = bnUpperBound.getuint64();
849 nSubsidy = (nSubsidy / CENT) * CENT;
850 if (fDebug && GetBoolArg("-printcreation"))
851 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
856 // ppcoin: miner's coin stake is rewarded based on coin age spent (coin-days)
857 int64 GetProofOfStakeReward(int64 nCoinAge)
859 static int64 nRewardCoinYear = CENT; // creation amount per coin-year
860 int64 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
861 if (fDebug && GetBoolArg("-printcreation"))
862 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nCoinAge);
866 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
867 static const int64 nTargetSpacingStake = 10 * 60; // ten minutes
868 static const int64 nTargetSpacingWorkMax = 2 * 60 * 60; // two hours
869 static const int64 nMaxClockDrift = 2 * 60 * 60; // two hours
872 // minimum amount of work that could possibly be required nTime after
873 // minimum work required was nBase
875 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
878 bnResult.SetCompact(nBase);
880 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
882 // Maximum 200% adjustment per day...
884 nTime -= 24 * 60 * 60;
886 if (bnResult > bnProofOfWorkLimit)
887 bnResult = bnProofOfWorkLimit;
888 return bnResult.GetCompact();
891 // ppcoin: find last block index up to pindex
892 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
894 while (pindex && (pindex->IsProofOfStake() != fProofOfStake))
895 pindex = pindex->pprev;
899 unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
901 // Genesis block and first block
902 if (pindexLast == NULL || pindexLast->pprev == NULL)
903 return bnProofOfWorkLimit.GetCompact();
905 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
906 if (pindexPrev == NULL)
907 return bnProofOfWorkLimit.GetCompact();
908 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
909 if (pindexPrevPrev == NULL)
910 return bnProofOfWorkLimit.GetCompact();
911 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
913 // ppcoin: target change every block
914 // ppcoin: retarget with exponential moving toward target spacing
916 bnNew.SetCompact(pindexPrev->nBits);
917 int64 nTargetSpacing = fProofOfStake? nTargetSpacingStake : min(nTargetSpacingWorkMax, nTargetSpacingStake * (1 + pindexLast->nHeight - pindexPrev->nHeight));
918 int64 nInterval = nTargetTimespan / nTargetSpacing;
919 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
920 bnNew /= ((nInterval + 1) * nTargetSpacing);
922 if (bnNew > bnProofOfWorkLimit)
923 bnNew = bnProofOfWorkLimit;
925 return bnNew.GetCompact();
928 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
931 bnTarget.SetCompact(nBits);
934 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
935 return error("CheckProofOfWork() : nBits below minimum work");
937 // Check proof of work matches claimed amount
938 if (hash > bnTarget.getuint256())
939 return error("CheckProofOfWork() : hash doesn't match nBits");
944 // Return maximum amount of blocks that other nodes claim to have
945 int GetNumBlocksOfPeers()
947 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
950 bool IsInitialBlockDownload()
952 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
954 static int64 nLastUpdate;
955 static CBlockIndex* pindexLastBest;
956 if (pindexBest != pindexLastBest)
958 pindexLastBest = pindexBest;
959 nLastUpdate = GetTime();
961 return (GetTime() - nLastUpdate < 10 &&
962 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
965 void static InvalidChainFound(CBlockIndex* pindexNew)
967 if (pindexNew->nChainTrust > nBestInvalidTrust)
969 nBestInvalidTrust = pindexNew->nChainTrust;
970 CTxDB().WriteBestInvalidTrust(nBestInvalidTrust);
973 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());
974 printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
975 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
976 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
979 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
981 nTime = max(GetBlockTime(), GetAdjustedTime());
994 bool CTransaction::DisconnectInputs(CTxDB& txdb)
996 // Relinquish previous transactions' spent pointers
999 BOOST_FOREACH(const CTxIn& txin, vin)
1001 COutPoint prevout = txin.prevout;
1003 // Get prev txindex from disk
1005 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1006 return error("DisconnectInputs() : ReadTxIndex failed");
1008 if (prevout.n >= txindex.vSpent.size())
1009 return error("DisconnectInputs() : prevout.n out of range");
1011 // Mark outpoint as not spent
1012 txindex.vSpent[prevout.n].SetNull();
1015 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1016 return error("DisconnectInputs() : UpdateTxIndex failed");
1020 // Remove transaction from index
1021 // This can fail if a duplicate of this transaction was in a chain that got
1022 // reorganized away. This is only possible if this transaction was completely
1023 // spent, so erasing it would be a no-op anway.
1024 txdb.EraseTxIndex(*this);
1030 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1031 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1033 // FetchInputs can return false either because we just haven't seen some inputs
1034 // (in which case the transaction should be stored as an orphan)
1035 // or because the transaction is malformed (in which case the transaction should
1036 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1040 return true; // Coinbase transactions have no inputs to fetch.
1042 for (unsigned int i = 0; i < vin.size(); i++)
1044 COutPoint prevout = vin[i].prevout;
1045 if (inputsRet.count(prevout.hash))
1046 continue; // Got it already
1049 CTxIndex& txindex = inputsRet[prevout.hash].first;
1051 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1053 // Get txindex from current proposed changes
1054 txindex = mapTestPool.find(prevout.hash)->second;
1058 // Read txindex from txdb
1059 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1061 if (!fFound && (fBlock || fMiner))
1062 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());
1065 CTransaction& txPrev = inputsRet[prevout.hash].second;
1066 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1068 // Get prev tx from single transactions in memory
1071 if (!mempool.exists(prevout.hash))
1072 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());
1073 txPrev = mempool.lookup(prevout.hash);
1076 txindex.vSpent.resize(txPrev.vout.size());
1080 // Get prev tx from disk
1081 if (!txPrev.ReadFromDisk(txindex.pos))
1082 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1086 // Make sure all prevout.n's are valid:
1087 for (unsigned int i = 0; i < vin.size(); i++)
1089 const COutPoint prevout = vin[i].prevout;
1090 assert(inputsRet.count(prevout.hash) != 0);
1091 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1092 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1093 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1095 // Revisit this if/when transaction replacement is implemented and allows
1098 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()));
1105 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1107 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1108 if (mi == inputs.end())
1109 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1111 const CTransaction& txPrev = (mi->second).second;
1112 if (input.prevout.n >= txPrev.vout.size())
1113 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1115 return txPrev.vout[input.prevout.n];
1118 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1124 for (unsigned int i = 0; i < vin.size(); i++)
1126 nResult += GetOutputFor(vin[i], inputs).nValue;
1132 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1137 unsigned int nSigOps = 0;
1138 for (unsigned int i = 0; i < vin.size(); i++)
1140 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1141 if (prevout.scriptPubKey.IsPayToScriptHash())
1142 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1147 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1148 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1149 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1151 // Take over previous transactions' spent pointers
1152 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1153 // fMiner is true when called from the internal bitcoin miner
1154 // ... both are false when called from CTransaction::AcceptToMemoryPool
1159 for (unsigned int i = 0; i < vin.size(); i++)
1161 COutPoint prevout = vin[i].prevout;
1162 assert(inputs.count(prevout.hash) > 0);
1163 CTxIndex& txindex = inputs[prevout.hash].first;
1164 CTransaction& txPrev = inputs[prevout.hash].second;
1166 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1167 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()));
1169 // If prev is coinbase/coinstake, check that it's matured
1170 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1171 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1172 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1173 return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight);
1175 // ppcoin: check transaction timestamp
1176 if (txPrev.nTime > nTime)
1177 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1179 // Check for negative or overflow input values
1180 nValueIn += txPrev.vout[prevout.n].nValue;
1181 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1182 return DoS(100, error("ConnectInputs() : txin values out of range"));
1185 // The first loop above does all the inexpensive checks.
1186 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1187 // Helps prevent CPU exhaustion attacks.
1188 for (unsigned int i = 0; i < vin.size(); i++)
1190 COutPoint prevout = vin[i].prevout;
1191 assert(inputs.count(prevout.hash) > 0);
1192 CTxIndex& txindex = inputs[prevout.hash].first;
1193 CTransaction& txPrev = inputs[prevout.hash].second;
1195 // Check for conflicts (double-spend)
1196 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1197 // for an attacker to attempt to split the network.
1198 if (!txindex.vSpent[prevout.n].IsNull())
1199 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());
1201 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1202 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1203 // still computed and checked, and any change will be caught at the next checkpoint.
1204 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1207 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1209 // only during transition phase for P2SH: do not invoke anti-DoS code for
1210 // potentially old clients relaying bad P2SH transactions
1211 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1212 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1214 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1218 // Mark outpoints as spent
1219 txindex.vSpent[prevout.n] = posThisTx;
1222 if (fBlock || fMiner)
1224 mapTestPool[prevout.hash] = txindex;
1230 // ppcoin: coin stake tx earns reward instead of paying fee
1232 if (!GetCoinAge(txdb, nCoinAge))
1233 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1234 int64 nStakeReward = GetValueOut() - nValueIn;
1235 if (nStakeReward > GetProofOfStakeReward(nCoinAge))
1236 return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
1240 if (nValueIn < GetValueOut())
1241 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1243 // Tally transaction fees
1244 int64 nTxFee = nValueIn - GetValueOut();
1246 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1247 // ppcoin: enforce transaction fees for every block
1248 if (nTxFee < GetMinFee())
1249 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;
1251 if (!MoneyRange(nFees))
1252 return DoS(100, error("ConnectInputs() : nFees out of range"));
1260 bool CTransaction::ClientConnectInputs()
1265 // Take over previous transactions' spent pointers
1269 for (unsigned int i = 0; i < vin.size(); i++)
1271 // Get prev tx from single transactions in memory
1272 COutPoint prevout = vin[i].prevout;
1273 if (!mempool.exists(prevout.hash))
1275 CTransaction& txPrev = mempool.lookup(prevout.hash);
1277 if (prevout.n >= txPrev.vout.size())
1281 if (!VerifySignature(txPrev, *this, i, true, 0))
1282 return error("ConnectInputs() : VerifySignature failed");
1284 ///// this is redundant with the mempool.mapNextTx stuff,
1285 ///// not sure which I want to get rid of
1286 ///// this has to go away now that posNext is gone
1287 // // Check for conflicts
1288 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1289 // return error("ConnectInputs() : prev tx already used");
1291 // // Flag outpoints as used
1292 // txPrev.vout[prevout.n].posNext = posThisTx;
1294 nValueIn += txPrev.vout[prevout.n].nValue;
1296 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1297 return error("ClientConnectInputs() : txin values out of range");
1299 if (GetValueOut() > nValueIn)
1309 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1311 // Disconnect in reverse order
1312 for (int i = vtx.size()-1; i >= 0; i--)
1313 if (!vtx[i].DisconnectInputs(txdb))
1316 // Update block index on disk without changing it in memory.
1317 // The memory index structure will be changed after the db commits.
1320 CDiskBlockIndex blockindexPrev(pindex->pprev);
1321 blockindexPrev.hashNext = 0;
1322 if (!txdb.WriteBlockIndex(blockindexPrev))
1323 return error("DisconnectBlock() : WriteBlockIndex failed");
1326 // ppcoin: clean up wallet after disconnecting coinstake
1327 BOOST_FOREACH(CTransaction& tx, vtx)
1328 SyncWithWallets(tx, this, false, false);
1333 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1335 // Check it again in case a previous version let a bad block in
1339 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1340 // unless those are already completely spent.
1341 // If such overwrites are allowed, coinbases and transactions depending upon those
1342 // can be duplicated to remove the ability to spend the first instance -- even after
1343 // being sent to another address.
1344 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1345 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1346 // already refuses previously-known transaction id's entirely.
1347 // This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
1348 // On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
1349 if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
1351 BOOST_FOREACH(CTransaction& tx, vtx)
1353 CTxIndex txindexOld;
1354 if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
1356 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1363 // BIP16 didn't become active until Apr 1 2012 (Feb 15 on testnet)
1364 int64 nBIP16SwitchTime = fTestNet ? 1329264000 : 1333238400;
1365 bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
1367 //// issue here: it doesn't know the version
1368 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1370 map<uint256, CTxIndex> mapQueuedChanges;
1372 unsigned int nSigOps = 0;
1373 BOOST_FOREACH(CTransaction& tx, vtx)
1375 nSigOps += tx.GetLegacySigOpCount();
1376 if (nSigOps > MAX_BLOCK_SIGOPS)
1377 return DoS(100, error("ConnectBlock() : too many sigops"));
1379 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1380 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1382 MapPrevTx mapInputs;
1383 if (!tx.IsCoinBase())
1386 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1389 if (fStrictPayToScriptHash)
1391 // Add in sigops done by pay-to-script-hash inputs;
1392 // this is to prevent a "rogue miner" from creating
1393 // an incredibly-expensive-to-validate block.
1394 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1395 if (nSigOps > MAX_BLOCK_SIGOPS)
1396 return DoS(100, error("ConnectBlock() : too many sigops"));
1399 if (!tx.IsCoinStake())
1400 nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
1402 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1406 mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
1409 // Write queued txindex changes
1410 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1412 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1413 return error("ConnectBlock() : UpdateTxIndex failed");
1416 // ppcoin: fees are not collected by miners as in bitcoin
1417 // ppcoin: fees are destroyed to compensate the entire network
1418 if (IsProofOfWork() && vtx[0].GetValueOut() > GetProofOfWorkReward(nBits))
1420 if (fDebug && GetBoolArg("-printcreation"))
1421 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1423 // Update block index on disk without changing it in memory.
1424 // The memory index structure will be changed after the db commits.
1427 CDiskBlockIndex blockindexPrev(pindex->pprev);
1428 blockindexPrev.hashNext = pindex->GetBlockHash();
1429 if (!txdb.WriteBlockIndex(blockindexPrev))
1430 return error("ConnectBlock() : WriteBlockIndex failed");
1433 // Watch for transactions paying to me
1434 BOOST_FOREACH(CTransaction& tx, vtx)
1435 SyncWithWallets(tx, this, true);
1440 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1442 printf("REORGANIZE\n");
1445 CBlockIndex* pfork = pindexBest;
1446 CBlockIndex* plonger = pindexNew;
1447 while (pfork != plonger)
1449 while (plonger->nHeight > pfork->nHeight)
1450 if (!(plonger = plonger->pprev))
1451 return error("Reorganize() : plonger->pprev is null");
1452 if (pfork == plonger)
1454 if (!(pfork = pfork->pprev))
1455 return error("Reorganize() : pfork->pprev is null");
1458 // List of what to disconnect
1459 vector<CBlockIndex*> vDisconnect;
1460 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1461 vDisconnect.push_back(pindex);
1463 // List of what to connect
1464 vector<CBlockIndex*> vConnect;
1465 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1466 vConnect.push_back(pindex);
1467 reverse(vConnect.begin(), vConnect.end());
1469 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());
1470 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());
1472 // Disconnect shorter branch
1473 vector<CTransaction> vResurrect;
1474 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1477 if (!block.ReadFromDisk(pindex))
1478 return error("Reorganize() : ReadFromDisk for disconnect failed");
1479 if (!block.DisconnectBlock(txdb, pindex))
1480 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1482 // Queue memory transactions to resurrect
1483 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1484 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1485 vResurrect.push_back(tx);
1488 // Connect longer branch
1489 vector<CTransaction> vDelete;
1490 for (unsigned int i = 0; i < vConnect.size(); i++)
1492 CBlockIndex* pindex = vConnect[i];
1494 if (!block.ReadFromDisk(pindex))
1495 return error("Reorganize() : ReadFromDisk for connect failed");
1496 if (!block.ConnectBlock(txdb, pindex))
1500 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1503 // Queue memory transactions to delete
1504 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1505 vDelete.push_back(tx);
1507 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1508 return error("Reorganize() : WriteHashBestChain failed");
1510 // Make sure it's successfully written to disk before changing memory structure
1511 if (!txdb.TxnCommit())
1512 return error("Reorganize() : TxnCommit failed");
1514 // Disconnect shorter branch
1515 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1517 pindex->pprev->pnext = NULL;
1519 // Connect longer branch
1520 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1522 pindex->pprev->pnext = pindex;
1524 // Resurrect memory transactions that were in the disconnected branch
1525 BOOST_FOREACH(CTransaction& tx, vResurrect)
1526 tx.AcceptToMemoryPool(txdb, false);
1528 // Delete redundant memory transactions that are in the connected branch
1529 BOOST_FOREACH(CTransaction& tx, vDelete)
1532 printf("REORGANIZE: done\n");
1539 runCommand(std::string strCommand)
1541 int nErr = ::system(strCommand.c_str());
1543 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1546 // Called from inside SetBestChain: attaches a block to the new best chain being built
1547 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1549 uint256 hash = GetHash();
1551 // Adding to current best branch
1552 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1555 InvalidChainFound(pindexNew);
1558 if (!txdb.TxnCommit())
1559 return error("SetBestChain() : TxnCommit failed");
1561 // Add to current best branch
1562 pindexNew->pprev->pnext = pindexNew;
1564 // Delete redundant memory transactions
1565 BOOST_FOREACH(CTransaction& tx, vtx)
1571 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1573 uint256 hash = GetHash();
1575 if (!txdb.TxnBegin())
1576 return error("SetBestChain() : TxnBegin failed");
1578 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1580 txdb.WriteHashBestChain(hash);
1581 if (!txdb.TxnCommit())
1582 return error("SetBestChain() : TxnCommit failed");
1583 pindexGenesisBlock = pindexNew;
1585 else if (hashPrevBlock == hashBestChain)
1587 if (!SetBestChainInner(txdb, pindexNew))
1588 return error("SetBestChain() : SetBestChainInner failed");
1592 // the first block in the new chain that will cause it to become the new best chain
1593 CBlockIndex *pindexIntermediate = pindexNew;
1595 // list of blocks that need to be connected afterwards
1596 std::vector<CBlockIndex*> vpindexSecondary;
1598 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1599 // Try to limit how much needs to be done inside
1600 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1602 vpindexSecondary.push_back(pindexIntermediate);
1603 pindexIntermediate = pindexIntermediate->pprev;
1606 if (!vpindexSecondary.empty())
1607 printf("Postponing %i reconnects\n", vpindexSecondary.size());
1609 // Switch to new best branch
1610 if (!Reorganize(txdb, pindexIntermediate))
1613 InvalidChainFound(pindexNew);
1614 return error("SetBestChain() : Reorganize failed");
1617 // Connect futher blocks
1618 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1621 if (!block.ReadFromDisk(pindex))
1623 printf("SetBestChain() : ReadFromDisk failed\n");
1626 if (!txdb.TxnBegin()) {
1627 printf("SetBestChain() : TxnBegin 2 failed\n");
1630 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1631 if (!block.SetBestChainInner(txdb, pindex))
1636 // Update best block in wallet (so we can detect restored wallets)
1637 bool fIsInitialDownload = IsInitialBlockDownload();
1638 if (!fIsInitialDownload)
1640 const CBlockLocator locator(pindexNew);
1641 ::SetBestChain(locator);
1645 hashBestChain = hash;
1646 pindexBest = pindexNew;
1647 nBestHeight = pindexBest->nHeight;
1648 nBestChainTrust = pindexNew->nChainTrust;
1649 nTimeBestReceived = GetTime();
1650 nTransactionsUpdated++;
1651 printf("SetBestChain: new best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
1653 std::string strCmd = GetArg("-blocknotify", "");
1655 if (!fIsInitialDownload && !strCmd.empty())
1657 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1658 boost::thread t(runCommand, strCmd); // thread runs free
1665 // ppcoin: coinstake must meet hash target according to the protocol:
1666 // input 0 must meet the formula
1667 // hash(nBits + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDay
1668 // this ensures that the chance of getting a coinstake is proportional to the
1669 // amount of coin age one owns.
1670 // The reason this hash is chosen is the following:
1671 // nBits: encodes all past block timestamps, making computing hash in advance
1673 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
1674 // generate transaction for future advantage
1675 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
1676 // nodes generating coinstake at the same time
1677 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
1679 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
1680 // generating coinstake at the same time
1681 // block/tx hash should not be used here as they can be generated in vast
1682 // quantities so as to generate blocks faster, degrading the system back into
1683 // a proof-of-work situation.
1685 bool CTransaction::CheckProofOfStake(unsigned int nBits) const
1687 CBigNum bnTargetPerCoinDay;
1688 bnTargetPerCoinDay.SetCompact(nBits);
1693 // Input 0 must match the stake hash target per coin age (nBits)
1694 const CTxIn& txin = vin[0];
1696 // First try finding the previous transaction in database
1698 CTransaction txPrev;
1700 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1701 return false; // previous transaction not in main chain
1703 if (nTime < txPrev.nTime)
1704 return false; // Transaction timestamp violation
1707 if (!VerifySignature(txPrev, *this, 0, true, 0))
1708 return DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", GetHash().ToString().c_str()));
1710 // Read block header
1712 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1713 return false; // unable to read block of previous transaction
1714 if (block.GetBlockTime() + STAKE_MIN_AGE > nTime)
1715 return false; // only count coins meeting min age requirement
1717 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1718 CBigNum bnCoinDay = CBigNum(nValueIn) * (nTime-txPrev.nTime) / COIN / (24 * 60 * 60);
1720 CDataStream ss(SER_GETHASH, 0);
1721 ss << nBits << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << txPrev.nTime << txin.prevout.n << nTime;
1722 if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1725 return DoS(100, error("CheckProofOfStake() : check target failed on coinstake %s", GetHash().ToString().c_str()));
1728 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1729 // Only those coins meeting minimum age requirement counts. As those
1730 // transactions not in main chain are not currently indexed so we
1731 // might not find out about their coin age. Older transactions are
1732 // guaranteed to be in main chain by sync-checkpoint. This rule is
1733 // introduced to help nodes establish a consistent view of the coin
1734 // age (trust score) of competing branches.
1735 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1737 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1743 BOOST_FOREACH(const CTxIn& txin, vin)
1745 // First try finding the previous transaction in database
1746 CTransaction txPrev;
1748 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1749 continue; // previous transaction not in main chain
1750 if (nTime < txPrev.nTime)
1751 return false; // Transaction timestamp violation
1753 // Read block header
1755 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1756 return false; // unable to read block of previous transaction
1757 if (block.GetBlockTime() + STAKE_MIN_AGE > nTime)
1758 continue; // only count coins meeting min age requirement
1760 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1761 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1763 if (fDebug && GetBoolArg("-printcoinage"))
1764 printf("coin age nValueIn=%-12I64d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1767 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1768 if (fDebug && GetBoolArg("-printcoinage"))
1769 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1770 nCoinAge = bnCoinDay.getuint64();
1774 // ppcoin: total coin age spent in block, in the unit of coin-days.
1775 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1780 BOOST_FOREACH(const CTransaction& tx, vtx)
1783 if (tx.GetCoinAge(txdb, nTxCoinAge))
1784 nCoinAge += nTxCoinAge;
1789 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1791 if (fDebug && GetBoolArg("-printcoinage"))
1792 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1797 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1799 // Check for duplicate
1800 uint256 hash = GetHash();
1801 if (mapBlockIndex.count(hash))
1802 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1804 // Construct new block index object
1805 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1807 return error("AddToBlockIndex() : new CBlockIndex failed");
1808 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1809 if (pindexNew->fProofOfStake)
1810 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
1812 pindexNew->phashBlock = &((*mi).first);
1813 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1814 if (miPrev != mapBlockIndex.end())
1816 pindexNew->pprev = (*miPrev).second;
1817 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1820 // ppcoin: compute chain trust score
1822 if (!GetCoinAge(nCoinAge))
1823 return error("AddToBlockIndex() : invalid transaction in block");
1824 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + nCoinAge;
1827 if (!txdb.TxnBegin())
1829 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1830 if (!txdb.TxnCommit())
1834 if (pindexNew->nChainTrust > nBestChainTrust)
1835 if (!SetBestChain(txdb, pindexNew))
1840 if (pindexNew == pindexBest)
1842 // Notify UI to display prev block's coinbase if it was ours
1843 static uint256 hashPrevBestCoinBase;
1844 UpdatedTransaction(hashPrevBestCoinBase);
1845 hashPrevBestCoinBase = vtx[0].GetHash();
1855 bool CBlock::CheckBlock() const
1857 // These are checks that are independent of context
1858 // that can be verified before saving an orphan block.
1861 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
1862 return DoS(100, error("CheckBlock() : size limits failed"));
1864 // Check proof of work matches claimed amount
1865 if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1866 return DoS(50, error("CheckBlock() : proof of work failed"));
1869 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
1870 return error("CheckBlock() : block timestamp too far in the future");
1872 // First transaction must be coinbase, the rest must not be
1873 if (vtx.empty() || !vtx[0].IsCoinBase())
1874 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1875 for (unsigned int i = 1; i < vtx.size(); i++)
1876 if (vtx[i].IsCoinBase())
1877 return DoS(100, error("CheckBlock() : more than one coinbase"));
1879 // ppcoin: only the second transaction can be the optional coinstake
1880 for (int i = 2; i < vtx.size(); i++)
1881 if (vtx[i].IsCoinStake())
1882 return DoS(100, error("CheckBlock() : coinstake in wrong position"));
1884 // ppcoin: coinbase output should be empty if proof-of-stake block
1885 if (IsProofOfStake() && !vtx[0].vout[0].IsEmpty())
1886 return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
1888 // Check coinbase timestamp
1889 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
1890 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
1892 // Check coinstake timestamp
1893 if (IsProofOfStake() && GetBlockTime() > (int64)vtx[1].nTime + nMaxClockDrift)
1894 return DoS(50, error("CheckBlock() : coinstake timestamp is too early"));
1896 // Check transactions
1897 BOOST_FOREACH(const CTransaction& tx, vtx)
1899 if (!tx.CheckTransaction())
1900 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1901 // ppcoin: check transaction timestamp
1902 if (GetBlockTime() < (int64)tx.nTime)
1903 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
1906 // Check for duplicate txids. This is caught by ConnectInputs(),
1907 // but catching it earlier avoids a potential DoS attack:
1908 set<uint256> uniqueTx;
1909 BOOST_FOREACH(const CTransaction& tx, vtx)
1911 uniqueTx.insert(tx.GetHash());
1913 if (uniqueTx.size() != vtx.size())
1914 return DoS(100, error("CheckBlock() : duplicate transaction"));
1916 unsigned int nSigOps = 0;
1917 BOOST_FOREACH(const CTransaction& tx, vtx)
1919 nSigOps += tx.GetLegacySigOpCount();
1921 if (nSigOps > MAX_BLOCK_SIGOPS)
1922 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1925 if (hashMerkleRoot != BuildMerkleTree())
1926 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1928 // ppcoin: check block signature
1929 if (!CheckBlockSignature())
1930 return DoS(100, error("CheckBlock() : bad block signature"));
1935 bool CBlock::AcceptBlock()
1937 // Check for duplicate
1938 uint256 hash = GetHash();
1939 if (mapBlockIndex.count(hash))
1940 return error("AcceptBlock() : block already in mapBlockIndex");
1942 // Get prev block index
1943 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1944 if (mi == mapBlockIndex.end())
1945 return DoS(10, error("AcceptBlock() : prev block not found"));
1946 CBlockIndex* pindexPrev = (*mi).second;
1947 int nHeight = pindexPrev->nHeight+1;
1949 // Check proof-of-work or proof-of-stake
1950 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
1951 return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake"));
1953 // Check timestamp against prev
1954 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
1955 return error("AcceptBlock() : block's timestamp is too early");
1957 // Check that all transactions are finalized
1958 BOOST_FOREACH(const CTransaction& tx, vtx)
1959 if (!tx.IsFinal(nHeight, GetBlockTime()))
1960 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1962 // Check that the block chain matches the known block chain up to a hardened checkpoint
1963 if (!Checkpoints::CheckHardened(nHeight, hash))
1964 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight));
1966 // ppcoin: check that the block satisfies synchronized checkpoint
1967 if (!Checkpoints::CheckSync(hash, pindexPrev))
1968 return error("AcceptBlock() : rejected by synchronized checkpoint");
1970 // Write block to history file
1971 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
1972 return error("AcceptBlock() : out of disk space");
1973 unsigned int nFile = -1;
1974 unsigned int nBlockPos = 0;
1975 if (!WriteToDisk(nFile, nBlockPos))
1976 return error("AcceptBlock() : WriteToDisk failed");
1977 if (!AddToBlockIndex(nFile, nBlockPos))
1978 return error("AcceptBlock() : AddToBlockIndex failed");
1980 // Relay inventory, but don't relay old inventory during initial block download
1981 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
1982 if (hashBestChain == hash)
1985 BOOST_FOREACH(CNode* pnode, vNodes)
1986 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
1987 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1990 // ppcoin: check pending sync-checkpoint
1991 Checkpoints::AcceptPendingSyncCheckpoint();
1996 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1998 // Check for duplicate
1999 uint256 hash = pblock->GetHash();
2000 if (mapBlockIndex.count(hash))
2001 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2002 if (mapOrphanBlocks.count(hash))
2003 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2005 // ppcoin: check proof-of-stake
2006 // Limited duplicity on stake: prevents block flood attack
2007 // Duplicate stake allowed only when there is orphan child block
2008 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2009 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());
2011 // Preliminary checks
2012 if (!pblock->CheckBlock())
2013 return error("ProcessBlock() : CheckBlock FAILED");
2015 // ppcoin: verify hash target and signature of coinstake tx
2016 if (pblock->IsProofOfStake() && !pblock->vtx[1].CheckProofOfStake(pblock->nBits))
2017 return error("ProcessBlock() : check proof-of-stake failed for block %s", hash.ToString().c_str());
2019 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2020 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2022 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2023 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2025 bnNewBlock.SetCompact(pblock->nBits);
2027 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime));
2029 if (bnNewBlock > bnRequired)
2032 pfrom->Misbehaving(100);
2033 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2037 // ppcoin: ask for pending sync-checkpoint if any
2038 if (!IsInitialBlockDownload())
2039 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2041 // If don't already have its previous block, shunt it off to holding area until we get it
2042 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2044 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2045 CBlock* pblock2 = new CBlock(*pblock);
2046 // ppcoin: check proof-of-stake
2047 if (pblock2->IsProofOfStake())
2049 // Limited duplicity on stake: prevents block flood attack
2050 // Duplicate stake allowed only when there is orphan child block
2051 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2052 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());
2054 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2056 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2057 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2059 // Ask this guy to fill in what we're missing
2062 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2063 // ppcoin: getblocks may not obtain the ancestor block rejected
2064 // earlier by duplicate-stake check so we ask for it again directly
2065 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2071 if (!pblock->AcceptBlock())
2072 return error("ProcessBlock() : AcceptBlock FAILED");
2074 // Recursively process any orphan blocks that depended on this one
2075 vector<uint256> vWorkQueue;
2076 vWorkQueue.push_back(hash);
2077 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2079 uint256 hashPrev = vWorkQueue[i];
2080 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2081 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2084 CBlock* pblockOrphan = (*mi).second;
2085 if (pblockOrphan->AcceptBlock())
2086 vWorkQueue.push_back(pblockOrphan->GetHash());
2087 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2088 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2089 delete pblockOrphan;
2091 mapOrphanBlocksByPrev.erase(hashPrev);
2094 printf("ProcessBlock: ACCEPTED\n");
2098 // ppcoin: sign block
2099 bool CBlock::SignBlock(const CKeyStore& keystore)
2101 vector<valtype> vSolutions;
2102 txnouttype whichType;
2103 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
2105 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2107 if (whichType == TX_PUBKEY)
2110 const valtype& vchPubKey = vSolutions[0];
2112 if (!keystore.GetKey(Hash160(vchPubKey), key))
2114 if (key.GetPubKey() != vchPubKey)
2116 return key.Sign(GetHash(), vchBlockSig);
2121 // ppcoin: check block signature
2122 bool CBlock::CheckBlockSignature() const
2124 if (GetHash() == hashGenesisBlock)
2125 return vchBlockSig.empty();
2127 vector<valtype> vSolutions;
2128 txnouttype whichType;
2129 const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
2131 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2133 if (whichType == TX_PUBKEY)
2135 const valtype& vchPubKey = vSolutions[0];
2137 if (!key.SetPubKey(vchPubKey))
2139 if (vchBlockSig.empty())
2141 return key.Verify(GetHash(), vchBlockSig);
2151 bool CheckDiskSpace(uint64 nAdditionalBytes)
2153 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2155 // Check for 15MB because database could create another 10MB log file at any time
2156 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
2159 string strMessage = _("Warning: Disk space is low");
2160 strMiscWarning = strMessage;
2161 printf("*** %s\n", strMessage.c_str());
2162 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION | wxMODAL);
2169 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2173 FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
2176 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2178 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2187 static unsigned int nCurrentBlockFile = 1;
2189 FILE* AppendBlockFile(unsigned int& nFileRet)
2194 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2197 if (fseek(file, 0, SEEK_END) != 0)
2199 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2200 if (ftell(file) < 0x7F000000 - MAX_SIZE)
2202 nFileRet = nCurrentBlockFile;
2206 nCurrentBlockFile++;
2210 bool LoadBlockIndex(bool fAllowNew)
2214 hashGenesisBlock = hashGenesisBlockTestNet;
2215 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
2216 pchMessageStart[0] = 0xfa;
2217 pchMessageStart[1] = 0xbf;
2218 pchMessageStart[2] = 0xb5;
2219 pchMessageStart[3] = 0xda;
2226 if (!txdb.LoadBlockIndex())
2231 // Init with genesis block
2233 if (mapBlockIndex.empty())
2239 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
2240 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2241 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
2242 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
2243 // vMerkleTree: 4a5e1e
2246 const char* pszTimestamp = "MarketWatch 07/Nov/2011 Gold tops $1,790 to end at over six-week high";
2248 txNew.nTime = 1339538219;
2249 txNew.vin.resize(1);
2250 txNew.vout.resize(1);
2251 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2252 txNew.vout[0].SetEmpty();
2254 block.vtx.push_back(txNew);
2255 block.hashPrevBlock = 0;
2256 block.hashMerkleRoot = block.BuildMerkleTree();
2258 block.nTime = 1339540307;
2259 block.nBits = bnProofOfWorkLimit.GetCompact();
2260 block.nNonce = 1281822831;
2264 block.nTime = 1296688602;
2265 block.nBits = 0x1d07fff8;
2266 block.nNonce = 384568319;
2270 printf("%s\n", block.GetHash().ToString().c_str());
2271 printf("%s\n", hashGenesisBlock.ToString().c_str());
2272 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
2273 assert(block.hashMerkleRoot == uint256("0x1557f46a17fcf8843dbe4c0c0edfd1d17eeff2c3c48d73a59d11f5d176e4b54d"));
2275 assert(block.GetHash() == hashGenesisBlock);
2276 assert(block.CheckBlock());
2278 // Start new block file
2280 unsigned int nBlockPos;
2281 if (!block.WriteToDisk(nFile, nBlockPos))
2282 return error("LoadBlockIndex() : writing genesis block to disk failed");
2283 if (!block.AddToBlockIndex(nFile, nBlockPos))
2284 return error("LoadBlockIndex() : genesis block not accepted");
2286 // ppcoin: initialize synchronized checkpoint
2287 if (!Checkpoints::WriteSyncCheckpoint(hashGenesisBlock))
2288 return error("LoadBlockIndex() : failed to init sync checkpoint");
2291 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2294 string strPubKey = "";
2295 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2297 // write checkpoint master key to db
2299 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2300 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2301 if (!txdb.TxnCommit())
2302 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2303 if (!Checkpoints::ResetSyncCheckpoint())
2304 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2314 void PrintBlockTree()
2316 // precompute tree structure
2317 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2318 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2320 CBlockIndex* pindex = (*mi).second;
2321 mapNext[pindex->pprev].push_back(pindex);
2323 //while (rand() % 3 == 0)
2324 // mapNext[pindex->pprev].push_back(pindex);
2327 vector<pair<int, CBlockIndex*> > vStack;
2328 vStack.push_back(make_pair(0, pindexGenesisBlock));
2331 while (!vStack.empty())
2333 int nCol = vStack.back().first;
2334 CBlockIndex* pindex = vStack.back().second;
2337 // print split or gap
2338 if (nCol > nPrevCol)
2340 for (int i = 0; i < nCol-1; i++)
2344 else if (nCol < nPrevCol)
2346 for (int i = 0; i < nCol; i++)
2353 for (int i = 0; i < nCol; i++)
2358 block.ReadFromDisk(pindex);
2359 printf("%d (%u,%u) %s %08lx %s tx %d",
2363 block.GetHash().ToString().substr(0,20).c_str(),
2365 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2368 PrintWallets(block);
2370 // put the main timechain first
2371 vector<CBlockIndex*>& vNext = mapNext[pindex];
2372 for (unsigned int i = 0; i < vNext.size(); i++)
2374 if (vNext[i]->pnext)
2376 swap(vNext[0], vNext[i]);
2382 for (unsigned int i = 0; i < vNext.size(); i++)
2383 vStack.push_back(make_pair(nCol+i, vNext[i]));
2396 //////////////////////////////////////////////////////////////////////////////
2401 map<uint256, CAlert> mapAlerts;
2402 CCriticalSection cs_mapAlerts;
2404 string GetWarnings(string strFor)
2407 string strStatusBar;
2409 if (GetBoolArg("-testsafemode"))
2412 // Misc warnings like out of disk space and clock is wrong
2413 if (strMiscWarning != "")
2416 strStatusBar = strMiscWarning;
2419 // Longer invalid proof-of-work chain
2420 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
2423 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2426 if (Checkpoints::hashInvalidCheckpoint != 0)
2429 strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
2435 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2437 const CAlert& alert = item.second;
2438 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2440 nPriority = alert.nPriority;
2441 strStatusBar = alert.strStatusBar;
2446 if (strFor == "statusbar")
2447 return strStatusBar;
2448 else if (strFor == "rpc")
2450 assert(!"GetWarnings() : invalid parameter");
2454 bool CAlert::ProcessAlert()
2456 if (!CheckSignature())
2463 // Cancel previous alerts
2464 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
2466 const CAlert& alert = (*mi).second;
2469 printf("cancelling alert %d\n", alert.nID);
2470 mapAlerts.erase(mi++);
2472 else if (!alert.IsInEffect())
2474 printf("expiring alert %d\n", alert.nID);
2475 mapAlerts.erase(mi++);
2481 // Check if this alert has been cancelled
2482 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2484 const CAlert& alert = item.second;
2485 if (alert.Cancels(*this))
2487 printf("alert already cancelled by %d\n", alert.nID);
2493 mapAlerts.insert(make_pair(GetHash(), *this));
2496 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2508 //////////////////////////////////////////////////////////////////////////////
2514 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2520 bool txInMap = false;
2523 txInMap = (mempool.exists(inv.hash));
2526 mapOrphanTransactions.count(inv.hash) ||
2527 txdb.ContainsTx(inv.hash);
2531 return mapBlockIndex.count(inv.hash) ||
2532 mapOrphanBlocks.count(inv.hash);
2534 // Don't know what it is, just say we already got one
2541 // The message start string is designed to be unlikely to occur in normal data.
2542 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2543 // a large 4-byte int at any alignment.
2544 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2547 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2549 static map<CService, vector<unsigned char> > mapReuseKey;
2550 RandAddSeedPerfmon();
2552 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2553 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2555 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2557 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2565 if (strCommand == "version")
2567 // Each connection can only send one version message
2568 if (pfrom->nVersion != 0)
2570 pfrom->Misbehaving(1);
2578 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2579 if (pfrom->nVersion < MIN_PROTO_VERSION)
2581 // Since February 20, 2012, the protocol is initiated at version 209,
2582 // and earlier versions are no longer supported
2583 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
2584 pfrom->fDisconnect = true;
2588 if (pfrom->nVersion == 10300)
2589 pfrom->nVersion = 300;
2591 vRecv >> addrFrom >> nNonce;
2593 vRecv >> pfrom->strSubVer;
2595 vRecv >> pfrom->nStartingHeight;
2597 // Disconnect if we connected to ourself
2598 if (nNonce == nLocalHostNonce && nNonce > 1)
2600 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2601 pfrom->fDisconnect = true;
2605 // ppcoin: record my external IP reported by peer
2606 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
2607 addrSeenByPeer = addrMe;
2609 // Be shy and don't send version until we hear
2610 if (pfrom->fInbound)
2611 pfrom->PushVersion();
2613 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2615 AddTimeData(pfrom->addr, nTime);
2618 pfrom->PushMessage("verack");
2619 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2621 if (!pfrom->fInbound)
2623 // Advertise our address
2624 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable() &&
2625 !IsInitialBlockDownload())
2627 CAddress addr(addrLocalHost);
2628 addr.nTime = GetAdjustedTime();
2629 pfrom->PushAddress(addr);
2632 // Get recent addresses
2633 if (pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
2635 pfrom->PushMessage("getaddr");
2636 pfrom->fGetAddr = true;
2638 addrman.Good(pfrom->addr);
2640 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
2642 addrman.Add(addrFrom, addrFrom);
2643 addrman.Good(addrFrom);
2647 // Ask the first connected node for block updates
2648 static int nAskedForBlocks = 0;
2649 if (!pfrom->fClient &&
2650 (pfrom->nVersion < NOBLKS_VERSION_START ||
2651 pfrom->nVersion >= NOBLKS_VERSION_END) &&
2652 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2655 pfrom->PushGetBlocks(pindexBest, uint256(0));
2661 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2662 item.second.RelayTo(pfrom);
2665 // ppcoin: relay sync-checkpoint
2667 LOCK(Checkpoints::cs_hashSyncCheckpoint);
2668 if (!Checkpoints::checkpointMessage.IsNull())
2669 Checkpoints::checkpointMessage.RelayTo(pfrom);
2672 pfrom->fSuccessfullyConnected = true;
2674 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2676 cPeerBlockCounts.input(pfrom->nStartingHeight);
2678 // ppcoin: ask for pending sync-checkpoint if any
2679 if (!IsInitialBlockDownload())
2680 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2684 else if (pfrom->nVersion == 0)
2686 // Must have a version message before anything else
2687 pfrom->Misbehaving(1);
2692 else if (strCommand == "verack")
2694 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
2698 else if (strCommand == "addr")
2700 vector<CAddress> vAddr;
2703 // Don't want addr from older versions unless seeding
2704 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
2706 if (vAddr.size() > 1000)
2708 pfrom->Misbehaving(20);
2709 return error("message addr size() = %d", vAddr.size());
2712 // Store the new addresses
2713 int64 nNow = GetAdjustedTime();
2714 int64 nSince = nNow - 10 * 60;
2715 BOOST_FOREACH(CAddress& addr, vAddr)
2719 // ignore IPv6 for now, since it isn't implemented anyway
2722 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2723 addr.nTime = nNow - 5 * 24 * 60 * 60;
2724 pfrom->AddAddressKnown(addr);
2725 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2727 // Relay to a limited number of other nodes
2730 // Use deterministic randomness to send to the same nodes for 24 hours
2731 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2732 static uint256 hashSalt;
2734 hashSalt = GetRandHash();
2735 int64 hashAddr = addr.GetHash();
2736 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
2737 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2738 multimap<uint256, CNode*> mapMix;
2739 BOOST_FOREACH(CNode* pnode, vNodes)
2741 if (pnode->nVersion < CADDR_TIME_VERSION)
2743 unsigned int nPointer;
2744 memcpy(&nPointer, &pnode, sizeof(nPointer));
2745 uint256 hashKey = hashRand ^ nPointer;
2746 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2747 mapMix.insert(make_pair(hashKey, pnode));
2749 int nRelayNodes = 2;
2750 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2751 ((*mi).second)->PushAddress(addr);
2755 addrman.Add(vAddr, pfrom->addr, 2 * 60 * 60);
2756 if (vAddr.size() < 1000)
2757 pfrom->fGetAddr = false;
2761 else if (strCommand == "inv")
2765 if (vInv.size() > 50000)
2767 pfrom->Misbehaving(20);
2768 return error("message inv size() = %d", vInv.size());
2771 // find last block in inv vector
2772 unsigned int nLastBlock = (unsigned int)(-1);
2773 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
2774 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
2775 nLastBlock = vInv.size() - 1 - nInv;
2780 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
2782 const CInv &inv = vInv[nInv];
2786 pfrom->AddInventoryKnown(inv);
2788 bool fAlreadyHave = AlreadyHave(txdb, inv);
2790 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2794 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
2795 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2796 } else if (nInv == nLastBlock) {
2797 // In case we are on a very long side-chain, it is possible that we already have
2798 // the last block in an inv bundle sent in response to getblocks. Try to detect
2799 // this situation and push another getblocks to continue.
2800 std::vector<CInv> vGetData(1,inv);
2801 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
2803 printf("force request: %s\n", inv.ToString().c_str());
2806 // Track requests for our stuff
2807 Inventory(inv.hash);
2812 else if (strCommand == "getdata")
2816 if (vInv.size() > 50000)
2818 pfrom->Misbehaving(20);
2819 return error("message getdata size() = %d", vInv.size());
2822 BOOST_FOREACH(const CInv& inv, vInv)
2826 printf("received getdata for: %s\n", inv.ToString().c_str());
2828 if (inv.type == MSG_BLOCK)
2830 // Send block from disk
2831 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2832 if (mi != mapBlockIndex.end())
2835 block.ReadFromDisk((*mi).second);
2836 pfrom->PushMessage("block", block);
2838 // Trigger them to send a getblocks request for the next batch of inventory
2839 if (inv.hash == pfrom->hashContinue)
2841 // Bypass PushInventory, this must send even if redundant,
2842 // and we want it right after the last block so they don't
2843 // wait for other stuff first.
2845 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2846 pfrom->PushMessage("inv", vInv);
2847 pfrom->hashContinue = 0;
2851 else if (inv.IsKnownType())
2853 // Send stream from relay memory
2856 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2857 if (mi != mapRelay.end())
2858 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2862 // Track requests for our stuff
2863 Inventory(inv.hash);
2868 else if (strCommand == "getblocks")
2870 CBlockLocator locator;
2872 vRecv >> locator >> hashStop;
2874 // Find the last block the caller has in the main chain
2875 CBlockIndex* pindex = locator.GetBlockIndex();
2877 // Send the rest of the chain
2879 pindex = pindex->pnext;
2880 int nLimit = 500 + locator.GetDistanceBack();
2881 unsigned int nBytes = 0;
2882 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2883 for (; pindex; pindex = pindex->pnext)
2885 if (pindex->GetBlockHash() == hashStop)
2887 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2890 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2892 block.ReadFromDisk(pindex, true);
2893 nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
2894 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2896 // When this block is requested, we'll send an inv that'll make them
2897 // getblocks the next batch of inventory.
2898 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2899 pfrom->hashContinue = pindex->GetBlockHash();
2906 else if (strCommand == "getheaders")
2908 CBlockLocator locator;
2910 vRecv >> locator >> hashStop;
2912 CBlockIndex* pindex = NULL;
2913 if (locator.IsNull())
2915 // If locator is null, return the hashStop block
2916 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2917 if (mi == mapBlockIndex.end())
2919 pindex = (*mi).second;
2923 // Find the last block the caller has in the main chain
2924 pindex = locator.GetBlockIndex();
2926 pindex = pindex->pnext;
2929 vector<CBlock> vHeaders;
2931 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
2932 for (; pindex; pindex = pindex->pnext)
2934 vHeaders.push_back(pindex->GetBlockHeader());
2935 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2938 pfrom->PushMessage("headers", vHeaders);
2942 else if (strCommand == "tx")
2944 vector<uint256> vWorkQueue;
2945 vector<uint256> vEraseQueue;
2946 CDataStream vMsg(vRecv);
2951 CInv inv(MSG_TX, tx.GetHash());
2952 pfrom->AddInventoryKnown(inv);
2954 bool fMissingInputs = false;
2955 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
2957 SyncWithWallets(tx, NULL, true);
2958 RelayMessage(inv, vMsg);
2959 mapAlreadyAskedFor.erase(inv);
2960 vWorkQueue.push_back(inv.hash);
2961 vEraseQueue.push_back(inv.hash);
2963 // Recursively process any orphan transactions that depended on this one
2964 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2966 uint256 hashPrev = vWorkQueue[i];
2967 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
2968 mi != mapOrphanTransactionsByPrev[hashPrev].end();
2971 const CDataStream& vMsg = *((*mi).second);
2973 CDataStream(vMsg) >> tx;
2974 CInv inv(MSG_TX, tx.GetHash());
2975 bool fMissingInputs2 = false;
2977 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
2979 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2980 SyncWithWallets(tx, NULL, true);
2981 RelayMessage(inv, vMsg);
2982 mapAlreadyAskedFor.erase(inv);
2983 vWorkQueue.push_back(inv.hash);
2984 vEraseQueue.push_back(inv.hash);
2986 else if (!fMissingInputs2)
2989 vEraseQueue.push_back(inv.hash);
2990 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2995 BOOST_FOREACH(uint256 hash, vEraseQueue)
2996 EraseOrphanTx(hash);
2998 else if (fMissingInputs)
3002 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3003 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3005 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3007 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3011 else if (strCommand == "block")
3016 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3019 CInv inv(MSG_BLOCK, block.GetHash());
3020 pfrom->AddInventoryKnown(inv);
3022 if (ProcessBlock(pfrom, &block))
3023 mapAlreadyAskedFor.erase(inv);
3024 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3028 else if (strCommand == "getaddr")
3030 pfrom->vAddrToSend.clear();
3031 vector<CAddress> vAddr = addrman.GetAddr();
3032 BOOST_FOREACH(const CAddress &addr, vAddr)
3033 pfrom->PushAddress(addr);
3037 else if (strCommand == "checkorder")
3042 if (!GetBoolArg("-allowreceivebyip"))
3044 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3051 /// we have a chance to check the order here
3053 // Keep giving the same key to the same ip until they use it
3054 if (!mapReuseKey.count(pfrom->addr))
3055 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3057 // Send back approval of order and pubkey to use
3058 CScript scriptPubKey;
3059 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3060 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3064 else if (strCommand == "reply")
3069 CRequestTracker tracker;
3071 LOCK(pfrom->cs_mapRequests);
3072 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3073 if (mi != pfrom->mapRequests.end())
3075 tracker = (*mi).second;
3076 pfrom->mapRequests.erase(mi);
3079 if (!tracker.IsNull())
3080 tracker.fn(tracker.param1, vRecv);
3084 else if (strCommand == "ping")
3086 if (pfrom->nVersion > BIP0031_VERSION)
3090 // Echo the message back with the nonce. This allows for two useful features:
3092 // 1) A remote node can quickly check if the connection is operational
3093 // 2) Remote nodes can measure the latency of the network thread. If this node
3094 // is overloaded it won't respond to pings quickly and the remote node can
3095 // avoid sending us more work, like chain download requests.
3097 // The nonce stops the remote getting confused between different pings: without
3098 // it, if the remote node sends a ping once per second and this node takes 5
3099 // seconds to respond to each, the 5th ping the remote sends would appear to
3100 // return very quickly.
3101 pfrom->PushMessage("pong", nonce);
3106 else if (strCommand == "alert")
3111 if (alert.ProcessAlert())
3114 pfrom->setKnown.insert(alert.GetHash());
3117 BOOST_FOREACH(CNode* pnode, vNodes)
3118 alert.RelayTo(pnode);
3123 else if (strCommand == "checkpoint")
3125 CSyncCheckpoint checkpoint;
3126 vRecv >> checkpoint;
3128 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3131 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3133 BOOST_FOREACH(CNode* pnode, vNodes)
3134 checkpoint.RelayTo(pnode);
3140 // Ignore unknown commands for extensibility
3144 // Update the last seen time for this node's address
3145 if (pfrom->fNetworkNode)
3146 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3147 AddressCurrentlyConnected(pfrom->addr);
3153 bool ProcessMessages(CNode* pfrom)
3155 CDataStream& vRecv = pfrom->vRecv;
3159 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3163 // (4) message start
3172 // Scan for message start
3173 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3174 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3175 if (vRecv.end() - pstart < nHeaderSize)
3177 if ((int)vRecv.size() > nHeaderSize)
3179 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3180 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3184 if (pstart - vRecv.begin() > 0)
3185 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
3186 vRecv.erase(vRecv.begin(), pstart);
3189 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3194 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3197 string strCommand = hdr.GetCommand();
3200 unsigned int nMessageSize = hdr.nMessageSize;
3201 if (nMessageSize > MAX_SIZE)
3203 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3206 if (nMessageSize > vRecv.size())
3208 // Rewind and wait for rest of message
3209 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3214 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3215 unsigned int nChecksum = 0;
3216 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3217 if (nChecksum != hdr.nChecksum)
3219 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3220 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3224 // Copy message to its own buffer
3225 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3226 vRecv.ignore(nMessageSize);
3234 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3239 catch (std::ios_base::failure& e)
3241 if (strstr(e.what(), "end of data"))
3243 // Allow exceptions from underlength message on vRecv
3244 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());
3246 else if (strstr(e.what(), "size too large"))
3248 // Allow exceptions from overlong size
3249 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3253 PrintExceptionContinue(&e, "ProcessMessages()");
3256 catch (std::exception& e) {
3257 PrintExceptionContinue(&e, "ProcessMessages()");
3259 PrintExceptionContinue(NULL, "ProcessMessages()");
3263 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3271 bool SendMessages(CNode* pto, bool fSendTrickle)
3273 TRY_LOCK(cs_main, lockMain);
3275 // Don't send anything until we get their version message
3276 if (pto->nVersion == 0)
3279 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3281 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3283 if (pto->nVersion > BIP0031_VERSION)
3284 pto->PushMessage("ping", nonce);
3286 pto->PushMessage("ping");
3289 // Resend wallet transactions that haven't gotten in a block yet
3290 ResendWalletTransactions();
3292 // Address refresh broadcast
3293 static int64 nLastRebroadcast;
3294 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3298 BOOST_FOREACH(CNode* pnode, vNodes)
3300 // Periodically clear setAddrKnown to allow refresh broadcasts
3301 if (nLastRebroadcast)
3302 pnode->setAddrKnown.clear();
3304 // Rebroadcast our address
3305 if (!fNoListen && !fUseProxy && addrLocalHost.IsRoutable())
3307 CAddress addr(addrLocalHost);
3308 addr.nTime = GetAdjustedTime();
3309 pnode->PushAddress(addr);
3313 nLastRebroadcast = GetTime();
3321 vector<CAddress> vAddr;
3322 vAddr.reserve(pto->vAddrToSend.size());
3323 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3325 // returns true if wasn't already contained in the set
3326 if (pto->setAddrKnown.insert(addr).second)
3328 vAddr.push_back(addr);
3329 // receiver rejects addr messages larger than 1000
3330 if (vAddr.size() >= 1000)
3332 pto->PushMessage("addr", vAddr);
3337 pto->vAddrToSend.clear();
3339 pto->PushMessage("addr", vAddr);
3344 // Message: inventory
3347 vector<CInv> vInvWait;
3349 LOCK(pto->cs_inventory);
3350 vInv.reserve(pto->vInventoryToSend.size());
3351 vInvWait.reserve(pto->vInventoryToSend.size());
3352 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3354 if (pto->setInventoryKnown.count(inv))
3357 // trickle out tx inv to protect privacy
3358 if (inv.type == MSG_TX && !fSendTrickle)
3360 // 1/4 of tx invs blast to all immediately
3361 static uint256 hashSalt;
3363 hashSalt = GetRandHash();
3364 uint256 hashRand = inv.hash ^ hashSalt;
3365 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3366 bool fTrickleWait = ((hashRand & 3) != 0);
3368 // always trickle our own transactions
3372 if (GetTransaction(inv.hash, wtx))
3374 fTrickleWait = true;
3379 vInvWait.push_back(inv);
3384 // returns true if wasn't already contained in the set
3385 if (pto->setInventoryKnown.insert(inv).second)
3387 vInv.push_back(inv);
3388 if (vInv.size() >= 1000)
3390 pto->PushMessage("inv", vInv);
3395 pto->vInventoryToSend = vInvWait;
3398 pto->PushMessage("inv", vInv);
3404 vector<CInv> vGetData;
3405 int64 nNow = GetTime() * 1000000;
3407 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3409 const CInv& inv = (*pto->mapAskFor.begin()).second;
3410 if (!AlreadyHave(txdb, inv))
3412 printf("sending getdata: %s\n", inv.ToString().c_str());
3413 vGetData.push_back(inv);
3414 if (vGetData.size() >= 1000)
3416 pto->PushMessage("getdata", vGetData);
3420 mapAlreadyAskedFor[inv] = nNow;
3421 pto->mapAskFor.erase(pto->mapAskFor.begin());
3423 if (!vGetData.empty())
3424 pto->PushMessage("getdata", vGetData);
3443 //////////////////////////////////////////////////////////////////////////////
3448 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3450 unsigned char* pdata = (unsigned char*)pbuffer;
3451 unsigned int blocks = 1 + ((len + 8) / 64);
3452 unsigned char* pend = pdata + 64 * blocks;
3453 memset(pdata + len, 0, 64 * blocks - len);
3455 unsigned int bits = len * 8;
3456 pend[-1] = (bits >> 0) & 0xff;
3457 pend[-2] = (bits >> 8) & 0xff;
3458 pend[-3] = (bits >> 16) & 0xff;
3459 pend[-4] = (bits >> 24) & 0xff;
3463 static const unsigned int pSHA256InitState[8] =
3464 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3466 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3469 unsigned char data[64];
3473 for (int i = 0; i < 16; i++)
3474 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
3476 for (int i = 0; i < 8; i++)
3477 ctx.h[i] = ((uint32_t*)pinit)[i];
3479 SHA256_Update(&ctx, data, sizeof(data));
3480 for (int i = 0; i < 8; i++)
3481 ((uint32_t*)pstate)[i] = ctx.h[i];
3485 // ScanHash scans nonces looking for a hash with at least some zero bits.
3486 // It operates on big endian data. Caller does the byte reversing.
3487 // All input buffers are 16-byte aligned. nNonce is usually preserved
3488 // between calls, but periodically or if nNonce is 0xffff0000 or above,
3489 // the block is rebuilt and nNonce starts over at zero.
3491 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
3493 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
3497 // Hash pdata using pmidstate as the starting state into
3498 // preformatted buffer phash1, then hash phash1 into phash
3500 SHA256Transform(phash1, pdata, pmidstate);
3501 SHA256Transform(phash, phash1, pSHA256InitState);
3503 // Return the nonce if the hash has at least some zero bits,
3504 // caller will check if it has enough to reach the target
3505 if (((unsigned short*)phash)[14] == 0)
3508 // If nothing found after trying for a while, return -1
3509 if ((nNonce & 0xffff) == 0)
3511 nHashesDone = 0xffff+1;
3512 return (unsigned int) -1;
3517 // Some explaining would be appreciated
3522 set<uint256> setDependsOn;
3525 COrphan(CTransaction* ptxIn)
3533 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3534 BOOST_FOREACH(uint256 hash, setDependsOn)
3535 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3540 uint64 nLastBlockTx = 0;
3541 uint64 nLastBlockSize = 0;
3543 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfWorkOnly)
3545 CReserveKey reservekey(pwallet);
3548 auto_ptr<CBlock> pblock(new CBlock());
3552 // Create coinbase tx
3554 txNew.vin.resize(1);
3555 txNew.vin[0].prevout.SetNull();
3556 txNew.vout.resize(1);
3557 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3559 // Add our coinbase tx as first transaction
3560 pblock->vtx.push_back(txNew);
3562 // ppcoin: if coinstake available add coinstake tx
3563 static unsigned int nLastCoinStakeCheckTime = GetAdjustedTime() - nMaxClockDrift + 60; // only initialized at startup
3564 CBlockIndex* pindexPrev = pindexBest;
3566 if (!fProofOfWorkOnly)
3568 while (nLastCoinStakeCheckTime < GetAdjustedTime())
3570 pindexPrev = pindexBest; // get best block again to avoid getting stale
3571 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
3572 CTransaction txCoinStake;
3574 static CCriticalSection cs;
3576 // mining may have been suspended for a while so
3577 // need to take max to satisfy the timestamp protocol
3578 nLastCoinStakeCheckTime++;
3579 nLastCoinStakeCheckTime = max(nLastCoinStakeCheckTime, (unsigned int) (GetAdjustedTime() - nMaxClockDrift + 60));
3580 txCoinStake.nTime = nLastCoinStakeCheckTime;
3582 if (pwallet->CreateCoinStake(pblock->nBits, txCoinStake))
3584 pblock->vtx.push_back(txCoinStake);
3585 pblock->vtx[0].vout[0].SetEmpty();
3591 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
3593 // Collect memory pool transactions into the block
3596 LOCK2(cs_main, mempool.cs);
3599 // Priority order to process transactions
3600 list<COrphan> vOrphan; // list memory doesn't move
3601 map<uint256, vector<COrphan*> > mapDependers;
3602 multimap<double, CTransaction*> mapPriority;
3603 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
3605 CTransaction& tx = (*mi).second;
3606 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
3609 COrphan* porphan = NULL;
3610 double dPriority = 0;
3611 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3613 // Read prev transaction
3614 CTransaction txPrev;
3616 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3618 // Has to wait for dependencies
3621 // Use list for automatic deletion
3622 vOrphan.push_back(COrphan(&tx));
3623 porphan = &vOrphan.back();
3625 mapDependers[txin.prevout.hash].push_back(porphan);
3626 porphan->setDependsOn.insert(txin.prevout.hash);
3629 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3631 // Read block header
3632 int nConf = txindex.GetDepthInMainChain();
3634 dPriority += (double)nValueIn * nConf;
3636 if (fDebug && GetBoolArg("-printpriority"))
3637 printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3640 // Priority is sum(valuein * age) / txsize
3641 dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3644 porphan->dPriority = dPriority;
3646 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3648 if (fDebug && GetBoolArg("-printpriority"))
3650 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3657 // Collect transactions into block
3658 map<uint256, CTxIndex> mapTestPool;
3659 uint64 nBlockSize = 1000;
3660 uint64 nBlockTx = 0;
3661 int nBlockSigOps = 100;
3662 while (!mapPriority.empty())
3664 // Take highest priority transaction off priority queue
3665 CTransaction& tx = *(*mapPriority.begin()).second;
3666 mapPriority.erase(mapPriority.begin());
3669 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
3670 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3673 // Legacy limits on sigOps:
3674 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
3675 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3679 if (tx.nTime > GetAdjustedTime())
3682 // ppcoin: simplify transaction fee - allow free = false
3683 int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
3685 // Connecting shouldn't fail due to dependency on other memory pool transactions
3686 // because we're already processing them in order of dependency
3687 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3688 MapPrevTx mapInputs;
3690 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
3693 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
3694 if (nTxFees < nMinFee)
3697 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
3698 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3701 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
3703 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
3704 swap(mapTestPool, mapTestPoolTmp);
3707 pblock->vtx.push_back(tx);
3708 nBlockSize += nTxSize;
3710 nBlockSigOps += nTxSigOps;
3713 // Add transactions that depend on this one to the priority queue
3714 uint256 hash = tx.GetHash();
3715 if (mapDependers.count(hash))
3717 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3719 if (!porphan->setDependsOn.empty())
3721 porphan->setDependsOn.erase(hash);
3722 if (porphan->setDependsOn.empty())
3723 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3729 nLastBlockTx = nBlockTx;
3730 nLastBlockSize = nBlockSize;
3731 printf("CreateNewBlock(): total size %lu\n", nBlockSize);
3734 if (pblock->IsProofOfWork())
3735 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
3738 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3739 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3740 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3741 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
3742 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
3743 pblock->UpdateTime(pindexPrev);
3746 return pblock.release();
3750 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3752 // Update nExtraNonce
3753 static uint256 hashPrevBlock;
3754 if (hashPrevBlock != pblock->hashPrevBlock)
3757 hashPrevBlock = pblock->hashPrevBlock;
3760 pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
3761 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
3763 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3767 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3770 // Prebuild hash buffers
3777 uint256 hashPrevBlock;
3778 uint256 hashMerkleRoot;
3781 unsigned int nNonce;
3784 unsigned char pchPadding0[64];
3786 unsigned char pchPadding1[64];
3789 memset(&tmp, 0, sizeof(tmp));
3791 tmp.block.nVersion = pblock->nVersion;
3792 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3793 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3794 tmp.block.nTime = pblock->nTime;
3795 tmp.block.nBits = pblock->nBits;
3796 tmp.block.nNonce = pblock->nNonce;
3798 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3799 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3801 // Byte swap all the input buffer
3802 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
3803 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3805 // Precalc the first half of the first hash, which stays constant
3806 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3808 memcpy(pdata, &tmp.block, 128);
3809 memcpy(phash1, &tmp.hash1, 64);
3813 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3815 uint256 hash = pblock->GetHash();
3816 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3818 if (hash > hashTarget && pblock->IsProofOfWork())
3819 return error("BitcoinMiner : proof-of-work not meeting target");
3822 printf("BitcoinMiner:\n");
3823 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3825 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3826 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3831 if (pblock->hashPrevBlock != hashBestChain)
3832 return error("BitcoinMiner : generated block is stale");
3834 // Remove key from key pool
3835 reservekey.KeepKey();
3837 // Track how many getdata requests this block gets
3839 LOCK(wallet.cs_wallet);
3840 wallet.mapRequestCount[pblock->GetHash()] = 0;
3843 // Process this block the same as if we had received it from another node
3844 if (!ProcessBlock(NULL, pblock))
3845 return error("BitcoinMiner : ProcessBlock, block not accepted");
3851 void static ThreadBitcoinMiner(void* parg);
3853 static bool fGenerateBitcoins = false;
3854 static bool fLimitProcessors = false;
3855 static int nLimitProcessors = -1;
3857 void static BitcoinMiner(CWallet *pwallet)
3859 printf("BitcoinMiner started\n");
3860 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3862 // Each thread has its own key and counter
3863 CReserveKey reservekey(pwallet);
3864 unsigned int nExtraNonce = 0;
3866 while (fGenerateBitcoins)
3870 while (vNodes.empty() || IsInitialBlockDownload())
3875 if (!fGenerateBitcoins)
3883 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3884 CBlockIndex* pindexPrev = pindexBest;
3886 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet));
3890 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3892 // ppcoin: if proof-of-stake block found then process block
3893 if (pblock->IsProofOfStake())
3895 if (!pblock->SignBlock(*pwalletMain))
3897 error("BitcoinMiner: Unable to sign new proof-of-stake block");
3900 printf("BitcoinMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
3901 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3902 CheckWork(pblock.get(), *pwalletMain, reservekey);
3903 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3907 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3911 // Prebuild hash buffers
3913 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3914 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3915 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3917 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3919 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3920 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3926 int64 nStart = GetTime();
3927 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3929 uint256& hash = *alignup<16>(hashbuf);
3932 unsigned int nHashesDone = 0;
3933 unsigned int nNonceFound;
3936 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3937 (char*)&hash, nHashesDone);
3939 // Check if something found
3940 if (nNonceFound != (unsigned int) -1)
3942 for (unsigned int i = 0; i < sizeof(hash)/4; i++)
3943 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3945 if (hash <= hashTarget)
3948 pblock->nNonce = ByteReverse(nNonceFound);
3949 assert(hash == pblock->GetHash());
3950 if (!pblock->SignBlock(*pwalletMain))
3952 error("BitcoinMiner: Unable to sign new proof-of-work block");
3956 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3957 CheckWork(pblock.get(), *pwalletMain, reservekey);
3958 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3964 static int64 nHashCounter;
3965 if (nHPSTimerStart == 0)
3967 nHPSTimerStart = GetTimeMillis();
3971 nHashCounter += nHashesDone;
3972 if (GetTimeMillis() - nHPSTimerStart > 4000)
3974 static CCriticalSection cs;
3977 if (GetTimeMillis() - nHPSTimerStart > 4000)
3979 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3980 nHPSTimerStart = GetTimeMillis();
3982 static int64 nLogTime;
3983 if (GetTime() - nLogTime > 30 * 60)
3985 nLogTime = GetTime();
3986 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3987 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
3993 // Check for stop or if block needs to be rebuilt
3996 if (!fGenerateBitcoins)
3998 if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
4002 if (nBlockNonce >= 0xffff0000)
4004 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
4006 if (pindexPrev != pindexBest)
4009 // Update nTime every few seconds
4010 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
4011 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
4012 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4013 pblock->UpdateTime(pindexPrev);
4014 nBlockTime = ByteReverse(pblock->nTime);
4015 if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
4016 break; // need to update coinbase timestamp
4021 void static ThreadBitcoinMiner(void* parg)
4023 CWallet* pwallet = (CWallet*)parg;
4026 vnThreadsRunning[THREAD_MINER]++;
4027 BitcoinMiner(pwallet);
4028 vnThreadsRunning[THREAD_MINER]--;
4030 catch (std::exception& e) {
4031 vnThreadsRunning[THREAD_MINER]--;
4032 PrintException(&e, "ThreadBitcoinMiner()");
4034 vnThreadsRunning[THREAD_MINER]--;
4035 PrintException(NULL, "ThreadBitcoinMiner()");
4038 if (vnThreadsRunning[THREAD_MINER] == 0)
4040 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
4044 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
4046 fGenerateBitcoins = fGenerate;
4047 nLimitProcessors = GetArg("-genproclimit", -1);
4048 if (nLimitProcessors == 0)
4049 fGenerateBitcoins = false;
4050 fLimitProcessors = (nLimitProcessors != -1);
4054 int nProcessors = boost::thread::hardware_concurrency();
4055 printf("%d processors\n", nProcessors);
4056 if (nProcessors < 1)
4058 if (fLimitProcessors && nProcessors > nLimitProcessors)
4059 nProcessors = nLimitProcessors;
4060 int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
4061 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
4062 for (int i = 0; i < nAddThreads; i++)
4064 if (!CreateThread(ThreadBitcoinMiner, pwallet))
4065 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");