1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2011-2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
15 using namespace boost;
21 CCriticalSection cs_setpwalletRegistered;
22 set<CWallet*> setpwalletRegistered;
24 CCriticalSection cs_main;
26 static map<uint256, CTransaction> mapTransactions;
27 CCriticalSection cs_mapTransactions;
28 unsigned int nTransactionsUpdated = 0;
29 map<COutPoint, CInPoint> mapNextTx;
31 map<uint256, CBlockIndex*> mapBlockIndex;
32 set<COutPoint> setStakeSeen;
33 uint256 hashGenesisBlock("0x000000006d52486334316794cc38ffeb7ebf35a7ebd661fd39f5f46b0d001575");
34 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
35 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
36 CBlockIndex* pindexGenesisBlock = NULL;
38 uint64 nBestChainTrust = 0;
39 uint64 nBestInvalidTrust = 0;
40 uint256 hashBestChain = 0;
41 CBlockIndex* pindexBest = NULL;
42 int64 nTimeBestReceived = 0;
44 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
46 map<uint256, CBlock*> mapOrphanBlocks;
47 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
49 map<uint256, CDataStream*> mapOrphanTransactions;
50 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
57 int fGenerateBitcoins = false;
58 int64 nTransactionFee = MIN_TX_FEE;
59 int fLimitProcessors = false;
60 int nLimitProcessors = 1;
61 int fMinimizeToTray = true;
62 int fMinimizeOnClose = true;
68 int64 nBalanceReserve = 0;
70 //////////////////////////////////////////////////////////////////////////////
72 // dispatching functions
75 // These functions dispatch to one or all registered wallets
78 void RegisterWallet(CWallet* pwalletIn)
80 CRITICAL_BLOCK(cs_setpwalletRegistered)
82 setpwalletRegistered.insert(pwalletIn);
86 void UnregisterWallet(CWallet* pwalletIn)
88 CRITICAL_BLOCK(cs_setpwalletRegistered)
90 setpwalletRegistered.erase(pwalletIn);
94 // check whether the passed transaction is from us
95 bool static IsFromMe(CTransaction& tx)
97 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
98 if (pwallet->IsFromMe(tx))
103 // get the wallet transaction with the given hash (if it exists)
104 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
106 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
107 if (pwallet->GetTransaction(hashTx,wtx))
112 // erases transaction with the given hash from all wallets
113 void static EraseFromWallets(uint256 hash)
115 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
116 pwallet->EraseFromWallet(hash);
119 // make sure all wallets know about the given transaction, in the given block
120 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true)
124 // ppcoin: wallets need to refund inputs when disconnecting coinstake
125 if (tx.IsCoinStake())
126 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
127 if (pwallet->IsFromMe(tx))
128 pwallet->DisableTransaction(tx);
132 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
133 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
136 // notify wallets about a new best chain
137 void static SetBestChain(const CBlockLocator& loc)
139 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
140 pwallet->SetBestChain(loc);
143 // notify wallets about an updated transaction
144 void static UpdatedTransaction(const uint256& hashTx)
146 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
147 pwallet->UpdatedTransaction(hashTx);
151 void static PrintWallets(const CBlock& block)
153 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
154 pwallet->PrintWallet(block);
157 // notify wallets about an incoming inventory (for request counts)
158 void static Inventory(const uint256& hash)
160 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
161 pwallet->Inventory(hash);
164 // ask wallets to resend their transactions
165 void static ResendWalletTransactions()
167 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
168 pwallet->ResendWalletTransactions();
177 //////////////////////////////////////////////////////////////////////////////
179 // mapOrphanTransactions
182 void static AddOrphanTx(const CDataStream& vMsg)
185 CDataStream(vMsg) >> tx;
186 uint256 hash = tx.GetHash();
187 if (mapOrphanTransactions.count(hash))
189 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
190 BOOST_FOREACH(const CTxIn& txin, tx.vin)
191 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
194 void static EraseOrphanTx(uint256 hash)
196 if (!mapOrphanTransactions.count(hash))
198 const CDataStream* pvMsg = mapOrphanTransactions[hash];
200 CDataStream(*pvMsg) >> tx;
201 BOOST_FOREACH(const CTxIn& txin, tx.vin)
203 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
204 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
206 if ((*mi).second == pvMsg)
207 mapOrphanTransactionsByPrev.erase(mi++);
213 mapOrphanTransactions.erase(hash);
223 //////////////////////////////////////////////////////////////////////////////
225 // CTransaction and CTxIndex
228 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
231 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
233 if (!ReadFromDisk(txindexRet.pos))
235 if (prevout.n >= vout.size())
243 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
246 return ReadFromDisk(txdb, prevout, txindex);
249 bool CTransaction::ReadFromDisk(COutPoint prevout)
253 return ReadFromDisk(txdb, prevout, txindex);
258 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
270 // Load the block this tx is in
272 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
274 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
279 // Update the tx's hashBlock
280 hashBlock = pblock->GetHash();
282 // Locate the transaction
283 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
284 if (pblock->vtx[nIndex] == *(CTransaction*)this)
286 if (nIndex == pblock->vtx.size())
288 vMerkleBranch.clear();
290 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
294 // Fill in merkle branch
295 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
298 // Is the tx in a block that's in the main chain
299 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
300 if (mi == mapBlockIndex.end())
302 CBlockIndex* pindex = (*mi).second;
303 if (!pindex || !pindex->IsInMainChain())
306 return pindexBest->nHeight - pindex->nHeight + 1;
315 bool CTransaction::CheckTransaction() const
317 // Basic checks that don't depend on any context
319 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
321 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
323 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
324 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
326 // Check for negative or overflow output values
328 for (int i = 0; i < vout.size(); i++)
330 const CTxOut& txout = vout[i];
331 if (txout.IsEmpty() && (!IsCoinBase()) && (!IsCoinStake()))
332 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
333 if (txout.nValue < 0)
334 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
335 if (txout.nValue > MAX_MONEY)
336 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
337 nValueOut += txout.nValue;
338 if (!MoneyRange(nValueOut))
339 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
342 // Check for duplicate inputs
343 set<COutPoint> vInOutPoints;
344 BOOST_FOREACH(const CTxIn& txin, vin)
346 if (vInOutPoints.count(txin.prevout))
348 vInOutPoints.insert(txin.prevout);
353 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
354 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
358 BOOST_FOREACH(const CTxIn& txin, vin)
359 if (txin.prevout.IsNull())
360 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
366 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
369 *pfMissingInputs = false;
371 if (!CheckTransaction())
372 return error("AcceptToMemoryPool() : CheckTransaction failed");
374 // Coinbase is only valid in a block, not as a loose transaction
376 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
377 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
379 return DoS(100, error("AcceptToMemoryPool() : coinstake as individual tx"));
381 // To help v0.1.5 clients who would see it as a negative number
382 if ((int64)nLockTime > INT_MAX)
383 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
386 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
387 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
388 // attacks disallow transactions with more than one SigOp per 34 bytes.
389 // 34 bytes because a TxOut is:
390 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
391 if (GetSigOpCount() > nSize / 34 || nSize < 100)
392 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
394 // Rather not work on nonstandard transactions (unless -testnet)
395 if (!fTestNet && !IsStandard())
396 return error("AcceptToMemoryPool() : nonstandard transaction type");
398 // Do we already have it?
399 uint256 hash = GetHash();
400 CRITICAL_BLOCK(cs_mapTransactions)
401 if (mapTransactions.count(hash))
404 if (txdb.ContainsTx(hash))
407 // Check for conflicts with in-memory transactions
408 CTransaction* ptxOld = NULL;
409 for (int i = 0; i < vin.size(); i++)
411 COutPoint outpoint = vin[i].prevout;
412 if (mapNextTx.count(outpoint))
414 // Disable replacement feature for now
417 // Allow replacing with a newer version of the same transaction
420 ptxOld = mapNextTx[outpoint].ptx;
421 if (ptxOld->IsFinal())
423 if (!IsNewerThan(*ptxOld))
425 for (int i = 0; i < vin.size(); i++)
427 COutPoint outpoint = vin[i].prevout;
428 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
437 // Check against previous transactions
438 map<uint256, CTxIndex> mapUnused;
440 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
443 *pfMissingInputs = true;
444 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
447 // Don't accept it if it can't get into a block
448 if (nFees < GetMinFee(1000, false, true))
449 return error("AcceptToMemoryPool() : not enough fees");
451 // Continuously rate-limit free transactions
452 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
453 // be annoying or make other's transactions take longer to confirm.
454 if (nFees < MIN_RELAY_TX_FEE)
456 static CCriticalSection cs;
457 static double dFreeCount;
458 static int64 nLastTime;
459 int64 nNow = GetTime();
463 // Use an exponentially decaying ~10-minute window:
464 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
466 // -limitfreerelay unit is thousand-bytes-per-minute
467 // At default rate it would take over a month to fill 1GB
468 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
469 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
471 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
477 // Store transaction in memory
478 CRITICAL_BLOCK(cs_mapTransactions)
482 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
483 ptxOld->RemoveFromMemoryPool();
485 AddToMemoryPoolUnchecked();
488 ///// are we sure this is ok when loading transactions or restoring block txes
489 // If updated, erase old tx from wallet
491 EraseFromWallets(ptxOld->GetHash());
493 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
497 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
500 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
503 bool CTransaction::AddToMemoryPoolUnchecked()
505 // Add to memory pool without checking anything. Don't call this directly,
506 // call AcceptToMemoryPool to properly check the transaction first.
507 CRITICAL_BLOCK(cs_mapTransactions)
509 uint256 hash = GetHash();
510 mapTransactions[hash] = *this;
511 for (int i = 0; i < vin.size(); i++)
512 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
513 nTransactionsUpdated++;
519 bool CTransaction::RemoveFromMemoryPool()
521 // Remove transaction from memory pool
522 CRITICAL_BLOCK(cs_mapTransactions)
524 BOOST_FOREACH(const CTxIn& txin, vin)
525 mapNextTx.erase(txin.prevout);
526 mapTransactions.erase(GetHash());
527 nTransactionsUpdated++;
537 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
539 if (hashBlock == 0 || nIndex == -1)
542 // Find the block it claims to be in
543 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
544 if (mi == mapBlockIndex.end())
546 CBlockIndex* pindex = (*mi).second;
547 if (!pindex || !pindex->IsInMainChain())
550 // Make sure the merkle branch connects to this block
551 if (!fMerkleVerified)
553 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
555 fMerkleVerified = true;
558 nHeightRet = pindex->nHeight;
559 return pindexBest->nHeight - pindex->nHeight + 1;
563 int CMerkleTx::GetBlocksToMaturity() const
565 if (!(IsCoinBase() || IsCoinStake()))
567 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
571 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
575 if (!IsInMainChain() && !ClientConnectInputs())
577 return CTransaction::AcceptToMemoryPool(txdb, false);
581 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
585 bool CMerkleTx::AcceptToMemoryPool()
588 return AcceptToMemoryPool(txdb);
593 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
595 CRITICAL_BLOCK(cs_mapTransactions)
597 // Add previous supporting transactions first
598 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
600 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
602 uint256 hash = tx.GetHash();
603 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
604 tx.AcceptToMemoryPool(txdb, fCheckInputs);
607 return AcceptToMemoryPool(txdb, fCheckInputs);
612 bool CWalletTx::AcceptWalletTransaction()
615 return AcceptWalletTransaction(txdb);
618 int CTxIndex::GetDepthInMainChain() const
622 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
624 // Find the block in the index
625 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
626 if (mi == mapBlockIndex.end())
628 CBlockIndex* pindex = (*mi).second;
629 if (!pindex || !pindex->IsInMainChain())
631 return 1 + nBestHeight - pindex->nHeight;
643 //////////////////////////////////////////////////////////////////////////////
645 // CBlock and CBlockIndex
648 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
650 if (!fReadTransactions)
652 *this = pindex->GetBlockHeader();
655 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
657 if (GetHash() != pindex->GetBlockHash())
658 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
662 uint256 static GetOrphanRoot(const CBlock* pblock)
664 // Work back to the first block in the orphan chain
665 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
666 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
667 return pblock->GetHash();
670 int64 static GetProofOfWorkReward(unsigned int nBits)
672 CBigNum bnSubsidyLimit = 9999 * COIN; // subsidy amount for difficulty 1
674 bnTarget.SetCompact(nBits);
675 CBigNum bnTargetLimit = bnProofOfWorkLimit;
676 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
678 // ppcoin: subsidy is cut in half every 16x multiply of difficulty
679 // A reasonably continuous curve is used to avoid shock to market
680 // (nSubsidyLimit / nSubsidy) ** 4 == bnProofOfWorkLimit / bnTarget
681 CBigNum bnLowerBound = CENT;
682 CBigNum bnUpperBound = bnSubsidyLimit;
683 while (bnLowerBound + CENT <= bnUpperBound)
685 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
686 if (fDebug && GetBoolArg("-printcreation"))
687 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
688 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
689 bnUpperBound = bnMidValue;
691 bnLowerBound = bnMidValue;
694 int64 nSubsidy = bnUpperBound.getuint64();
695 nSubsidy = (nSubsidy / CENT) * CENT;
696 if (fDebug && GetBoolArg("-printcreation"))
697 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
702 // ppcoin: miner's coin stake is rewarded based on coin age spent (coin-days)
703 int64 GetProofOfStakeReward(int64 nCoinAge)
705 static int64 nRewardCoinYear = CENT; // creation amount per coin-year
706 int64 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
707 if (fDebug && GetBoolArg("-printcreation"))
708 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nCoinAge);
712 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
713 static const int64 nTargetSpacing = 10 * 60;
714 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
715 static const int64 nMaxClockDrift = 2 * 60 * 60; // 2 hours
718 // minimum amount of work that could possibly be required nTime after
719 // minimum work required was nBase
721 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
724 bnResult.SetCompact(nBase);
725 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
727 // Maximum 400% adjustment...
729 // ... in best-case exactly 4-times-normal target time
730 nTime -= nTargetTimespan*4;
732 if (bnResult > bnProofOfWorkLimit)
733 bnResult = bnProofOfWorkLimit;
734 return bnResult.GetCompact();
737 // ppcoin: find last block index up to pindex
738 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
740 while (pindex && (pindex->IsProofOfStake() != fProofOfStake))
741 pindex = pindex->pprev;
745 unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
747 // Genesis block and first block
748 if (pindexLast == NULL || pindexLast->pprev == NULL)
749 return bnProofOfWorkLimit.GetCompact();
751 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
752 if (pindexPrev == NULL)
753 return bnProofOfWorkLimit.GetCompact();
754 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
755 if (pindexPrevPrev == NULL)
756 return bnProofOfWorkLimit.GetCompact();
757 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
759 // ppcoin: target change every block
760 // ppcoin: retarget with exponential moving toward target spacing
762 bnNew.SetCompact(pindexPrev->nBits);
763 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
764 bnNew /= ((nInterval + 1) * nTargetSpacing);
766 if (bnNew > bnProofOfWorkLimit)
767 bnNew = bnProofOfWorkLimit;
769 return bnNew.GetCompact();
772 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
775 bnTarget.SetCompact(nBits);
778 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
779 return error("CheckProofOfWork() : nBits below minimum work");
781 // Check proof of work matches claimed amount
782 if (hash > bnTarget.getuint256())
783 return error("CheckProofOfWork() : hash doesn't match nBits");
788 // Return maximum amount of blocks that other nodes claim to have
789 int GetNumBlocksOfPeers()
791 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
794 bool IsInitialBlockDownload()
796 if (pindexBest == NULL || nBestHeight < (Checkpoints::GetTotalBlocksEstimate()-nInitialBlockThreshold))
798 static int64 nLastUpdate;
799 static CBlockIndex* pindexLastBest;
800 if (pindexBest != pindexLastBest)
802 pindexLastBest = pindexBest;
803 nLastUpdate = GetTime();
805 return (GetTime() - nLastUpdate < 10 &&
806 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
809 void static InvalidChainFound(CBlockIndex* pindexNew)
811 if (pindexNew->nChainTrust > nBestInvalidTrust)
813 nBestInvalidTrust = pindexNew->nChainTrust;
814 CTxDB().WriteBestInvalidTrust(nBestInvalidTrust);
817 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());
818 printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
819 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
820 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
833 bool CTransaction::DisconnectInputs(CTxDB& txdb)
835 // Relinquish previous transactions' spent pointers
838 BOOST_FOREACH(const CTxIn& txin, vin)
840 COutPoint prevout = txin.prevout;
842 // Get prev txindex from disk
844 if (!txdb.ReadTxIndex(prevout.hash, txindex))
845 return error("DisconnectInputs() : ReadTxIndex failed");
847 if (prevout.n >= txindex.vSpent.size())
848 return error("DisconnectInputs() : prevout.n out of range");
850 // Mark outpoint as not spent
851 txindex.vSpent[prevout.n].SetNull();
854 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
855 return error("DisconnectInputs() : UpdateTxIndex failed");
859 // Remove transaction from index
860 if (!txdb.EraseTxIndex(*this))
861 return error("DisconnectInputs() : EraseTxPos failed");
867 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
868 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
870 // Take over previous transactions' spent pointers
871 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
872 // fMiner is true when called from the internal bitcoin miner
873 // ... both are false when called from CTransaction::AcceptToMemoryPool
877 for (int i = 0; i < vin.size(); i++)
879 COutPoint prevout = vin[i].prevout;
884 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
886 // Get txindex from current proposed changes
887 txindex = mapTestPool[prevout.hash];
891 // Read txindex from txdb
892 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
894 if (!fFound && (fBlock || fMiner))
895 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
899 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
901 // Get prev tx from single transactions in memory
902 CRITICAL_BLOCK(cs_mapTransactions)
904 if (!mapTransactions.count(prevout.hash))
905 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
906 txPrev = mapTransactions[prevout.hash];
909 txindex.vSpent.resize(txPrev.vout.size());
913 // Get prev tx from disk
914 if (!txPrev.ReadFromDisk(txindex.pos))
915 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
918 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
919 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()));
921 // If prev is coinbase/coinstake, check that it's matured
922 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
923 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
924 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
925 return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight);
927 // ppcoin: check transaction timestamp
928 if (txPrev.nTime > nTime)
929 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
931 // Skip ECDSA signature verification when connecting blocks (fBlock=true) during initial download
932 // (before the last blockchain checkpoint). This is safe because block merkle hashes are
933 // still computed and checked, and any change will be caught at the next checkpoint.
934 if (!(fBlock && IsInitialBlockDownload()))
936 if (!VerifySignature(txPrev, *this, i))
937 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
939 // Check for conflicts (double-spend)
940 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
941 // for an attacker to attempt to split the network.
942 if (!txindex.vSpent[prevout.n].IsNull())
943 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());
945 // Check for negative or overflow input values
946 nValueIn += txPrev.vout[prevout.n].nValue;
947 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
948 return DoS(100, error("ConnectInputs() : txin values out of range"));
950 // Mark outpoints as spent
951 txindex.vSpent[prevout.n] = posThisTx;
954 if (fBlock || fMiner)
956 mapTestPool[prevout.hash] = txindex;
962 // ppcoin: coin stake tx earns reward instead of paying fee
964 if (!GetCoinAge(txdb, nCoinAge))
965 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
966 int64 nStakeReward = GetValueOut() - nValueIn;
967 if (nStakeReward > GetProofOfStakeReward(nCoinAge))
968 return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
972 if (nValueIn < GetValueOut())
973 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
975 // Tally transaction fees
976 int64 nTxFee = nValueIn - GetValueOut();
978 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
979 // ppcoin: enforce transaction fees for every block
980 if (nTxFee < nMinFee)
981 return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(nMinFee).c_str(), FormatMoney(nTxFee).c_str())) : false;
983 if (!MoneyRange(nFees))
984 return DoS(100, error("ConnectInputs() : nFees out of range"));
990 // Add transaction to changes
991 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
995 // Add transaction to test pool
996 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1003 bool CTransaction::ClientConnectInputs()
1008 // Take over previous transactions' spent pointers
1009 CRITICAL_BLOCK(cs_mapTransactions)
1012 for (int i = 0; i < vin.size(); i++)
1014 // Get prev tx from single transactions in memory
1015 COutPoint prevout = vin[i].prevout;
1016 if (!mapTransactions.count(prevout.hash))
1018 CTransaction& txPrev = mapTransactions[prevout.hash];
1020 if (prevout.n >= txPrev.vout.size())
1024 if (!VerifySignature(txPrev, *this, i))
1025 return error("ConnectInputs() : VerifySignature failed");
1027 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1028 ///// this has to go away now that posNext is gone
1029 // // Check for conflicts
1030 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1031 // return error("ConnectInputs() : prev tx already used");
1033 // // Flag outpoints as used
1034 // txPrev.vout[prevout.n].posNext = posThisTx;
1036 nValueIn += txPrev.vout[prevout.n].nValue;
1038 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1039 return error("ClientConnectInputs() : txin values out of range");
1041 if (GetValueOut() > nValueIn)
1051 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1053 // Disconnect in reverse order
1054 for (int i = vtx.size()-1; i >= 0; i--)
1055 if (!vtx[i].DisconnectInputs(txdb))
1058 // Update block index on disk without changing it in memory.
1059 // The memory index structure will be changed after the db commits.
1062 CDiskBlockIndex blockindexPrev(pindex->pprev);
1063 blockindexPrev.hashNext = 0;
1064 if (!txdb.WriteBlockIndex(blockindexPrev))
1065 return error("DisconnectBlock() : WriteBlockIndex failed");
1068 // ppcoin: clean up wallet after disconnecting coinstake
1069 BOOST_FOREACH(CTransaction& tx, vtx)
1070 SyncWithWallets(tx, this, false, false);
1075 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1077 // Check it again in case a previous version let a bad block in
1081 // ppcoin: coin stake tx must meet target protocol
1082 if (IsProofOfStake() && !vtx[1].CheckProofOfStake(txdb, nBits))
1083 return error("ConnectBlock() : Block %s unable to meet hash target for coinstake", GetHash().ToString().c_str());
1085 //// issue here: it doesn't know the version
1086 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1088 map<uint256, CTxIndex> mapQueuedChanges;
1090 BOOST_FOREACH(CTransaction& tx, vtx)
1092 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1093 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1095 if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false, tx.GetMinFee()))
1098 // Write queued txindex changes
1099 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1101 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1102 return error("ConnectBlock() : UpdateTxIndex failed");
1105 // ppcoin: fees are not collected by miners as in bitcoin
1106 // ppcoin: fees are destroyed to compensate the entire network
1107 if (IsProofOfWork() && vtx[0].GetValueOut() > GetProofOfWorkReward(nBits))
1109 if (fDebug && GetBoolArg("-printcreation"))
1110 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1112 // Update block index on disk without changing it in memory.
1113 // The memory index structure will be changed after the db commits.
1116 CDiskBlockIndex blockindexPrev(pindex->pprev);
1117 blockindexPrev.hashNext = pindex->GetBlockHash();
1118 if (!txdb.WriteBlockIndex(blockindexPrev))
1119 return error("ConnectBlock() : WriteBlockIndex failed");
1122 // Watch for transactions paying to me
1123 BOOST_FOREACH(CTransaction& tx, vtx)
1124 SyncWithWallets(tx, this, true);
1129 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1131 printf("REORGANIZE\n");
1134 CBlockIndex* pfork = pindexBest;
1135 CBlockIndex* plonger = pindexNew;
1136 while (pfork != plonger)
1138 while (plonger->nHeight > pfork->nHeight)
1139 if (!(plonger = plonger->pprev))
1140 return error("Reorganize() : plonger->pprev is null");
1141 if (pfork == plonger)
1143 if (!(pfork = pfork->pprev))
1144 return error("Reorganize() : pfork->pprev is null");
1147 // List of what to disconnect
1148 vector<CBlockIndex*> vDisconnect;
1149 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1150 vDisconnect.push_back(pindex);
1152 // List of what to connect
1153 vector<CBlockIndex*> vConnect;
1154 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1155 vConnect.push_back(pindex);
1156 reverse(vConnect.begin(), vConnect.end());
1158 // Disconnect shorter branch
1159 vector<CTransaction> vResurrect;
1160 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1163 if (!block.ReadFromDisk(pindex))
1164 return error("Reorganize() : ReadFromDisk for disconnect failed");
1165 if (!block.DisconnectBlock(txdb, pindex))
1166 return error("Reorganize() : DisconnectBlock failed");
1168 // Queue memory transactions to resurrect
1169 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1170 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1171 vResurrect.push_back(tx);
1174 // Connect longer branch
1175 vector<CTransaction> vDelete;
1176 for (int i = 0; i < vConnect.size(); i++)
1178 CBlockIndex* pindex = vConnect[i];
1180 if (!block.ReadFromDisk(pindex))
1181 return error("Reorganize() : ReadFromDisk for connect failed");
1182 if (!block.ConnectBlock(txdb, pindex))
1186 return error("Reorganize() : ConnectBlock failed");
1189 // Queue memory transactions to delete
1190 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1191 vDelete.push_back(tx);
1193 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1194 return error("Reorganize() : WriteHashBestChain failed");
1195 if (!txdb.WriteAutoCheckpoint(Checkpoints::GetNextAutoCheckpoint(pindexNew->nCheckpoint)))
1196 return error("Reorganize() : WriteAutoCheckpoint failed");
1198 // Make sure it's successfully written to disk before changing memory structure
1199 if (!txdb.TxnCommit())
1200 return error("Reorganize() : TxnCommit failed");
1202 // Disconnect shorter branch
1203 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1205 pindex->pprev->pnext = NULL;
1207 // Connect longer branch
1208 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1210 pindex->pprev->pnext = pindex;
1212 // Resurrect memory transactions that were in the disconnected branch
1213 BOOST_FOREACH(CTransaction& tx, vResurrect)
1214 tx.AcceptToMemoryPool(txdb, false);
1216 // Delete redundant memory transactions that are in the connected branch
1217 BOOST_FOREACH(CTransaction& tx, vDelete)
1218 tx.RemoveFromMemoryPool();
1224 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1226 uint256 hash = GetHash();
1229 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1231 txdb.WriteHashBestChain(hash);
1232 txdb.WriteAutoCheckpoint(Checkpoints::GetNextAutoCheckpoint(pindexNew->nCheckpoint));
1233 if (!txdb.TxnCommit())
1234 return error("SetBestChain() : TxnCommit failed");
1235 pindexGenesisBlock = pindexNew;
1237 else if (hashPrevBlock == hashBestChain)
1239 // Adding to current best branch
1240 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash) || !txdb.WriteAutoCheckpoint(Checkpoints::GetNextAutoCheckpoint(pindexNew->nCheckpoint)))
1243 InvalidChainFound(pindexNew);
1244 return error("SetBestChain() : ConnectBlock failed");
1246 if (!txdb.TxnCommit())
1247 return error("SetBestChain() : TxnCommit failed");
1249 // Add to current best branch
1250 pindexNew->pprev->pnext = pindexNew;
1252 // Delete redundant memory transactions
1253 BOOST_FOREACH(CTransaction& tx, vtx)
1254 tx.RemoveFromMemoryPool();
1259 if (!Reorganize(txdb, pindexNew))
1262 InvalidChainFound(pindexNew);
1263 return error("SetBestChain() : Reorganize failed");
1267 // Update best block in wallet (so we can detect restored wallets)
1268 if (!IsInitialBlockDownload())
1270 const CBlockLocator locator(pindexNew);
1271 ::SetBestChain(locator);
1275 hashBestChain = hash;
1276 pindexBest = pindexNew;
1277 nBestHeight = pindexBest->nHeight;
1278 nBestChainTrust = pindexNew->nChainTrust;
1279 nTimeBestReceived = GetTime();
1280 nTransactionsUpdated++;
1281 Checkpoints::AdvanceAutoCheckpoint(pindexBest->nCheckpoint);
1282 printf("SetBestChain: new best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
1288 // ppcoin: coinstake must meet hash target according to the protocol:
1289 // at least one input must meet the formula
1290 // hash(nBits + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDay
1291 // this ensures that the chance of getting a coinstake is proportional to the
1292 // amount of coin age one owns.
1293 // The reason this hash is chosen is the following:
1294 // nBits: encodes all past block timestamps, making computing hash in advance
1296 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
1297 // generate transaction for future advantage
1298 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
1299 // nodes generating coinstake at the same time
1300 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
1302 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
1303 // generating coinstake at the same time
1304 // block/tx hash should not be used here as they can be generated in vast
1305 // quantities so as to generate blocks faster, degrading the system back into
1306 // a proof-of-work situation.
1308 bool CTransaction::CheckProofOfStake(CTxDB& txdb, unsigned int nBits) const
1310 CBigNum bnTargetPerCoinDay;
1311 bnTargetPerCoinDay.SetCompact(nBits);
1316 // Input 0 must match the stake hash target per coin age (nBits)
1317 const CTxIn& txin = vin[0];
1319 // First try finding the previous transaction in database
1320 CTransaction txPrev;
1322 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1323 return false; // previous transaction not in main chain
1324 if (nTime < txPrev.nTime)
1325 return false; // Transaction timestamp violation
1327 // Read block header
1329 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1330 return false; // unable to read block of previous transaction
1331 if (block.GetBlockTime() + AUTO_CHECKPOINT_TRUST_SPAN > nTime)
1332 return false; // only count coins from at least one week ago
1334 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1335 CBigNum bnCoinDay = CBigNum(nValueIn) * (nTime-txPrev.nTime) / COIN / (24 * 60 * 60);
1337 CDataStream ss(SER_GETHASH, VERSION);
1338 ss << nBits << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << txPrev.nTime << txin.prevout.n << nTime;
1339 if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1345 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1346 // Only those coins last spent at least a week ago count. As those
1347 // transactions not in main chain are not currently indexed so we
1348 // might not find out about their coin age. Older transactions are
1349 // guaranteed to be in main chain by auto checkpoint. This rule is
1350 // introduced to help nodes establish a consistent view of the coin
1351 // age (trust score) of competing branches.
1352 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1354 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1360 BOOST_FOREACH(const CTxIn& txin, vin)
1362 // First try finding the previous transaction in database
1363 CTransaction txPrev;
1365 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1366 continue; // previous transaction not in main chain
1367 if (nTime < txPrev.nTime)
1368 return false; // Transaction timestamp violation
1370 // Read block header
1372 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1373 return false; // unable to read block of previous transaction
1374 if (block.GetBlockTime() + AUTO_CHECKPOINT_TRUST_SPAN > nTime)
1375 continue; // only count coins from at least one week ago
1377 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1378 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1380 if (fDebug && GetBoolArg("-printcoinage"))
1381 printf("coin age nValueIn=%-12I64d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1384 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1385 if (fDebug && GetBoolArg("-printcoinage"))
1386 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1387 nCoinAge = bnCoinDay.getuint64();
1391 // ppcoin: total coin age spent in block, in the unit of coin-days.
1392 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1397 BOOST_FOREACH(const CTransaction& tx, vtx)
1400 if (tx.GetCoinAge(txdb, nTxCoinAge))
1401 nCoinAge += nTxCoinAge;
1406 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1408 if (fDebug && GetBoolArg("-printcoinage"))
1409 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1414 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1416 // Check for duplicate
1417 uint256 hash = GetHash();
1418 if (mapBlockIndex.count(hash))
1419 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1421 // Construct new block index object
1422 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1424 return error("AddToBlockIndex() : new CBlockIndex failed");
1425 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1427 pindexNew->phashBlock = &((*mi).first);
1428 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1429 if (miPrev != mapBlockIndex.end())
1431 pindexNew->pprev = (*miPrev).second;
1432 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1434 // ppcoin: compute chain checkpoint
1435 pindexNew->nCheckpoint = Checkpoints::GetNextChainCheckpoint(pindexNew->pprev);
1436 assert (pindexNew->nCheckpoint >= pindexNew->pprev->nCheckpoint);
1439 // ppcoin: compute chain trust score
1441 if (!GetCoinAge(nCoinAge))
1442 return error("AddToBlockIndex() : invalid transaction in block");
1443 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + nCoinAge;
1447 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1448 if (!txdb.TxnCommit())
1452 if (pindexNew->nChainTrust > nBestChainTrust)
1453 if (!SetBestChain(txdb, pindexNew))
1458 if (pindexNew == pindexBest)
1460 // Notify UI to display prev block's coinbase if it was ours
1461 static uint256 hashPrevBestCoinBase;
1462 UpdatedTransaction(hashPrevBestCoinBase);
1463 hashPrevBestCoinBase = vtx[0].GetHash();
1473 bool CBlock::CheckBlock() const
1475 // These are checks that are independent of context
1476 // that can be verified before saving an orphan block.
1479 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1480 return DoS(100, error("CheckBlock() : size limits failed"));
1482 // Check proof of work matches claimed amount
1483 if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1484 return DoS(50, error("CheckBlock() : proof of work failed"));
1487 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
1488 return error("CheckBlock() : block timestamp too far in the future");
1490 // First transaction must be coinbase, the rest must not be
1491 if (vtx.empty() || !vtx[0].IsCoinBase())
1492 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1493 for (int i = 1; i < vtx.size(); i++)
1494 if (vtx[i].IsCoinBase())
1495 return DoS(100, error("CheckBlock() : more than one coinbase"));
1497 // ppcoin: only the second transaction can be the optional coinstake
1498 for (int i = 2; i < vtx.size(); i++)
1499 if (vtx[i].IsCoinStake())
1500 return DoS(100, error("CheckBlock() : coinstake in wrong position"));
1502 // ppcoin: coinbase output should be empty if proof-of-stake block
1503 if (IsProofOfStake() && !vtx[0].vout[0].IsEmpty())
1504 return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
1506 // Check coinbase timestamp
1507 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
1508 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
1510 // Check transactions
1511 BOOST_FOREACH(const CTransaction& tx, vtx)
1513 if (!tx.CheckTransaction())
1514 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1515 // ppcoin: check transaction timestamp
1516 if (GetBlockTime() < (int64)tx.nTime)
1517 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
1520 // Check that it's not full of nonstandard transactions
1521 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1522 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1525 if (hashMerkleRoot != BuildMerkleTree())
1526 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1528 // Coin base vout[0] scriptPubKey must be the same as coin stake vout[1]
1530 if (vtx.size() > 1 && vtx[1].IsCoinStake() &&
1531 vtx[0].vout[0].scriptPubKey != vtx[1].vout[1].scriptPubKey)
1532 return DoS(100, error("CheckBlock() : block key mismatch"));
1535 // Check block signature
1536 if (!CheckBlockSignature())
1537 return DoS(100, error("CheckBlock() : bad block signature"));
1542 bool CBlock::AcceptBlock()
1544 // Check for duplicate
1545 uint256 hash = GetHash();
1546 if (mapBlockIndex.count(hash))
1547 return error("AcceptBlock() : block already in mapBlockIndex");
1549 // Get prev block index
1550 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1551 if (mi == mapBlockIndex.end())
1552 return DoS(10, error("AcceptBlock() : prev block not found"));
1553 CBlockIndex* pindexPrev = (*mi).second;
1554 int nHeight = pindexPrev->nHeight+1;
1556 // ppcoin: check for coinstake duplicate
1557 if (IsProofOfStake())
1558 { // check if coinstake is already connected; that would imply the owner
1559 // of the coinstake sent multiple blocks with the same coinstake
1561 if (CTxDB("r").ReadTxIndex(vtx[1].GetHash(), txindex))
1562 return error("AcceptBlock() : block %s has duplicate coinstake %s", hash.ToString().c_str(), vtx[1].GetHash().ToString().c_str());
1565 // Check proof-of-work or proof-of-stake
1566 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
1567 return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake"));
1569 // Check timestamp against prev
1570 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
1571 return error("AcceptBlock() : block's timestamp is too early");
1573 // Check that all transactions are finalized
1574 BOOST_FOREACH(const CTransaction& tx, vtx)
1575 if (!tx.IsFinal(nHeight, GetBlockTime()))
1576 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1578 // Check that the block chain matches the known block chain up to a hardened checkpoint
1579 if (!Checkpoints::CheckHardened(nHeight, hash))
1580 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight));
1582 // ppcoin: check that the block satisfies automatic checkpoint
1583 if (!Checkpoints::CheckAuto(pindexPrev))
1584 return DoS(100, error("AcceptBlock() : rejected by automatic checkpoint at %d", Checkpoints::nAutoCheckpoint));
1586 // Write block to history file
1587 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1588 return error("AcceptBlock() : out of disk space");
1589 unsigned int nFile = -1;
1590 unsigned int nBlockPos = 0;
1591 if (!WriteToDisk(nFile, nBlockPos))
1592 return error("AcceptBlock() : WriteToDisk failed");
1593 if (!AddToBlockIndex(nFile, nBlockPos))
1594 return error("AcceptBlock() : AddToBlockIndex failed");
1596 // Relay inventory, but don't relay old inventory during initial block download
1597 if (hashBestChain == hash)
1598 CRITICAL_BLOCK(cs_vNodes)
1599 BOOST_FOREACH(CNode* pnode, vNodes)
1600 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1601 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1606 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1608 // Check for duplicate
1609 uint256 hash = pblock->GetHash();
1610 if (mapBlockIndex.count(hash))
1611 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1612 if (mapOrphanBlocks.count(hash))
1613 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1615 // Preliminary checks
1616 if (!pblock->CheckBlock())
1617 return error("ProcessBlock() : CheckBlock FAILED");
1619 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1620 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1622 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1623 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1626 pfrom->Misbehaving(100);
1627 return error("ProcessBlock() : block with timestamp before last checkpoint");
1630 bnNewBlock.SetCompact(pblock->nBits);
1632 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1633 if (pblock->IsProofOfWork() && bnNewBlock > bnRequired)
1635 pfrom->Misbehaving(100);
1636 return error("ProcessBlock() : block with too little proof-of-work");
1641 // If don't already have its previous block, shunt it off to holding area until we get it
1642 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1644 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1645 CBlock* pblock2 = new CBlock(*pblock);
1646 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1647 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1649 // Ask this guy to fill in what we're missing
1651 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1656 if (!pblock->AcceptBlock())
1657 return error("ProcessBlock() : AcceptBlock FAILED");
1659 // Recursively process any orphan blocks that depended on this one
1660 vector<uint256> vWorkQueue;
1661 vWorkQueue.push_back(hash);
1662 for (int i = 0; i < vWorkQueue.size(); i++)
1664 uint256 hashPrev = vWorkQueue[i];
1665 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1666 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1669 CBlock* pblockOrphan = (*mi).second;
1670 if (pblockOrphan->AcceptBlock())
1671 vWorkQueue.push_back(pblockOrphan->GetHash());
1672 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1673 delete pblockOrphan;
1675 mapOrphanBlocksByPrev.erase(hashPrev);
1678 printf("ProcessBlock: ACCEPTED\n");
1689 bool CheckDiskSpace(uint64 nAdditionalBytes)
1691 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1693 // Check for 15MB because database could create another 10MB log file at any time
1694 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1697 string strMessage = _("Warning: Disk space is low ");
1698 strMiscWarning = strMessage;
1699 printf("*** %s\n", strMessage.c_str());
1700 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1701 CreateThread(Shutdown, NULL);
1707 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1711 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1714 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1716 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1725 static unsigned int nCurrentBlockFile = 1;
1727 FILE* AppendBlockFile(unsigned int& nFileRet)
1732 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1735 if (fseek(file, 0, SEEK_END) != 0)
1737 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1738 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1740 nFileRet = nCurrentBlockFile;
1744 nCurrentBlockFile++;
1748 bool LoadBlockIndex(bool fAllowNew)
1752 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1753 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1754 pchMessageStart[0] = 0xfa;
1755 pchMessageStart[1] = 0xbf;
1756 pchMessageStart[2] = 0xb5;
1757 pchMessageStart[3] = 0xda;
1764 if (!txdb.LoadBlockIndex())
1769 // Init with genesis block
1771 if (mapBlockIndex.empty())
1777 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1778 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1779 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1780 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1781 // vMerkleTree: 4a5e1e
1784 const char* pszTimestamp = "MarketWatch 07/Nov/2011 Gold tops $1,790 to end at over six-week high";
1786 txNew.nTime = 1325878371;
1787 txNew.vin.resize(1);
1788 txNew.vout.resize(1);
1789 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1790 txNew.vout[0].nValue = GetProofOfWorkReward(bnProofOfWorkLimit.GetCompact());
1791 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1793 block.vtx.push_back(txNew);
1794 block.hashPrevBlock = 0;
1795 block.hashMerkleRoot = block.BuildMerkleTree();
1797 block.nTime = 1325882536;
1798 block.nBits = bnProofOfWorkLimit.GetCompact();
1799 block.nNonce = 2081920190;
1803 block.nTime = 1296688602;
1804 block.nBits = 0x1d07fff8;
1805 block.nNonce = 384568319;
1809 printf("%s\n", block.GetHash().ToString().c_str());
1810 printf("%s\n", hashGenesisBlock.ToString().c_str());
1811 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1812 assert(block.hashMerkleRoot == uint256("0xc7311b56de266580cca65be108ae53d7100b5c3b17da8b1106044103abd7a521"));
1814 assert(block.GetHash() == hashGenesisBlock);
1815 assert(block.CheckBlock());
1817 // Start new block file
1819 unsigned int nBlockPos;
1820 if (!block.WriteToDisk(nFile, nBlockPos))
1821 return error("LoadBlockIndex() : writing genesis block to disk failed");
1822 if (!block.AddToBlockIndex(nFile, nBlockPos))
1823 return error("LoadBlockIndex() : genesis block not accepted");
1831 void PrintBlockTree()
1833 // precompute tree structure
1834 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1835 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1837 CBlockIndex* pindex = (*mi).second;
1838 mapNext[pindex->pprev].push_back(pindex);
1840 //while (rand() % 3 == 0)
1841 // mapNext[pindex->pprev].push_back(pindex);
1844 vector<pair<int, CBlockIndex*> > vStack;
1845 vStack.push_back(make_pair(0, pindexGenesisBlock));
1848 while (!vStack.empty())
1850 int nCol = vStack.back().first;
1851 CBlockIndex* pindex = vStack.back().second;
1854 // print split or gap
1855 if (nCol > nPrevCol)
1857 for (int i = 0; i < nCol-1; i++)
1861 else if (nCol < nPrevCol)
1863 for (int i = 0; i < nCol; i++)
1870 for (int i = 0; i < nCol; i++)
1875 block.ReadFromDisk(pindex);
1876 printf("%d (%u,%u) %s %08lx %s tx %d",
1880 block.GetHash().ToString().substr(0,20).c_str(),
1882 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1885 PrintWallets(block);
1887 // put the main timechain first
1888 vector<CBlockIndex*>& vNext = mapNext[pindex];
1889 for (int i = 0; i < vNext.size(); i++)
1891 if (vNext[i]->pnext)
1893 swap(vNext[0], vNext[i]);
1899 for (int i = 0; i < vNext.size(); i++)
1900 vStack.push_back(make_pair(nCol+i, vNext[i]));
1913 //////////////////////////////////////////////////////////////////////////////
1918 map<uint256, CAlert> mapAlerts;
1919 CCriticalSection cs_mapAlerts;
1921 string GetWarnings(string strFor)
1924 string strStatusBar;
1926 if (GetBoolArg("-testsafemode"))
1929 // Misc warnings like out of disk space and clock is wrong
1930 if (strMiscWarning != "")
1933 strStatusBar = strMiscWarning;
1936 // Longer invalid proof-of-work chain
1937 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
1940 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1944 CRITICAL_BLOCK(cs_mapAlerts)
1946 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1948 const CAlert& alert = item.second;
1949 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1951 nPriority = alert.nPriority;
1952 strStatusBar = alert.strStatusBar;
1957 if (strFor == "statusbar")
1958 return strStatusBar;
1959 else if (strFor == "rpc")
1961 assert(!"GetWarnings() : invalid parameter");
1965 bool CAlert::ProcessAlert()
1967 if (!CheckSignature())
1972 CRITICAL_BLOCK(cs_mapAlerts)
1974 // Cancel previous alerts
1975 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1977 const CAlert& alert = (*mi).second;
1980 printf("cancelling alert %d\n", alert.nID);
1981 mapAlerts.erase(mi++);
1983 else if (!alert.IsInEffect())
1985 printf("expiring alert %d\n", alert.nID);
1986 mapAlerts.erase(mi++);
1992 // Check if this alert has been cancelled
1993 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1995 const CAlert& alert = item.second;
1996 if (alert.Cancels(*this))
1998 printf("alert already cancelled by %d\n", alert.nID);
2004 mapAlerts.insert(make_pair(GetHash(), *this));
2007 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2019 //////////////////////////////////////////////////////////////////////////////
2025 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2029 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2030 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2032 // Don't know what it is, just say we already got one
2039 // The message start string is designed to be unlikely to occur in normal data.
2040 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2041 // a large 4-byte int at any alignment.
2042 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2045 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2047 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2048 RandAddSeedPerfmon();
2050 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2051 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2053 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2055 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2063 if (strCommand == "version")
2065 // Each connection can only send one version message
2066 if (pfrom->nVersion != 0)
2068 pfrom->Misbehaving(1);
2076 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2077 if (pfrom->nVersion == 10300)
2078 pfrom->nVersion = 300;
2079 if (pfrom->nVersion >= 106 && !vRecv.empty())
2080 vRecv >> addrFrom >> nNonce;
2081 if (pfrom->nVersion >= 106 && !vRecv.empty())
2082 vRecv >> pfrom->strSubVer;
2083 if (pfrom->nVersion >= 209 && !vRecv.empty())
2084 vRecv >> pfrom->nStartingHeight;
2086 if (pfrom->nVersion == 0)
2089 // Disconnect if we connected to ourself
2090 if (nNonce == nLocalHostNonce && nNonce > 1)
2092 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2093 pfrom->fDisconnect = true;
2097 // ppcoin: record my external IP reported by peer
2098 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
2099 addrSeenByPeer = addrMe;
2101 // Be shy and don't send version until we hear
2102 if (pfrom->fInbound)
2103 pfrom->PushVersion();
2105 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2107 AddTimeData(pfrom->addr.ip, nTime);
2110 if (pfrom->nVersion >= 209)
2111 pfrom->PushMessage("verack");
2112 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2113 if (pfrom->nVersion < 209)
2114 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2116 if (!pfrom->fInbound)
2118 // Advertise our address
2119 if (addrLocalHost.IsRoutable() && !fUseProxy)
2121 CAddress addr(addrLocalHost);
2122 addr.nTime = GetAdjustedTime();
2123 pfrom->PushAddress(addr);
2126 // Get recent addresses
2127 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2129 pfrom->PushMessage("getaddr");
2130 pfrom->fGetAddr = true;
2134 // Ask the first connected node for block updates
2135 static int nAskedForBlocks;
2136 if (!pfrom->fClient &&
2137 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
2138 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2141 pfrom->PushGetBlocks(pindexBest, uint256(0));
2145 CRITICAL_BLOCK(cs_mapAlerts)
2146 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2147 item.second.RelayTo(pfrom);
2149 pfrom->fSuccessfullyConnected = true;
2151 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2153 cPeerBlockCounts.input(pfrom->nStartingHeight);
2157 else if (pfrom->nVersion == 0)
2159 // Must have a version message before anything else
2160 pfrom->Misbehaving(1);
2165 else if (strCommand == "verack")
2167 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2171 else if (strCommand == "addr")
2173 vector<CAddress> vAddr;
2176 // Don't want addr from older versions unless seeding
2177 if (pfrom->nVersion < 209)
2179 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2181 if (vAddr.size() > 1000)
2183 pfrom->Misbehaving(20);
2184 return error("message addr size() = %d", vAddr.size());
2187 // Store the new addresses
2190 int64 nNow = GetAdjustedTime();
2191 int64 nSince = nNow - 10 * 60;
2192 BOOST_FOREACH(CAddress& addr, vAddr)
2196 // ignore IPv6 for now, since it isn't implemented anyway
2199 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2200 addr.nTime = nNow - 5 * 24 * 60 * 60;
2201 AddAddress(addr, 2 * 60 * 60, &addrDB);
2202 pfrom->AddAddressKnown(addr);
2203 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2205 // Relay to a limited number of other nodes
2206 CRITICAL_BLOCK(cs_vNodes)
2208 // Use deterministic randomness to send to the same nodes for 24 hours
2209 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2210 static uint256 hashSalt;
2212 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2213 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2214 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2215 multimap<uint256, CNode*> mapMix;
2216 BOOST_FOREACH(CNode* pnode, vNodes)
2218 if (pnode->nVersion < 31402)
2220 unsigned int nPointer;
2221 memcpy(&nPointer, &pnode, sizeof(nPointer));
2222 uint256 hashKey = hashRand ^ nPointer;
2223 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2224 mapMix.insert(make_pair(hashKey, pnode));
2226 int nRelayNodes = 2;
2227 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2228 ((*mi).second)->PushAddress(addr);
2232 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
2233 if (vAddr.size() < 1000)
2234 pfrom->fGetAddr = false;
2238 else if (strCommand == "inv")
2242 if (vInv.size() > 50000)
2244 pfrom->Misbehaving(20);
2245 return error("message inv size() = %d", vInv.size());
2249 BOOST_FOREACH(const CInv& inv, vInv)
2253 pfrom->AddInventoryKnown(inv);
2255 bool fAlreadyHave = AlreadyHave(txdb, inv);
2257 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2261 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2262 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2264 // Track requests for our stuff
2265 Inventory(inv.hash);
2270 else if (strCommand == "getdata")
2274 if (vInv.size() > 50000)
2276 pfrom->Misbehaving(20);
2277 return error("message getdata size() = %d", vInv.size());
2280 BOOST_FOREACH(const CInv& inv, vInv)
2284 printf("received getdata for: %s\n", inv.ToString().c_str());
2286 if (inv.type == MSG_BLOCK)
2288 // Send block from disk
2289 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2290 if (mi != mapBlockIndex.end())
2293 block.ReadFromDisk((*mi).second);
2294 pfrom->PushMessage("block", block);
2296 // Trigger them to send a getblocks request for the next batch of inventory
2297 if (inv.hash == pfrom->hashContinue)
2299 // Bypass PushInventory, this must send even if redundant,
2300 // and we want it right after the last block so they don't
2301 // wait for other stuff first.
2303 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2304 pfrom->PushMessage("inv", vInv);
2305 pfrom->hashContinue = 0;
2309 else if (inv.IsKnownType())
2311 // Send stream from relay memory
2312 CRITICAL_BLOCK(cs_mapRelay)
2314 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2315 if (mi != mapRelay.end())
2316 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2320 // Track requests for our stuff
2321 Inventory(inv.hash);
2326 else if (strCommand == "getblocks")
2328 CBlockLocator locator;
2330 vRecv >> locator >> hashStop;
2332 // Find the last block the caller has in the main chain
2333 CBlockIndex* pindex = locator.GetBlockIndex();
2335 // Send the rest of the chain
2337 pindex = pindex->pnext;
2338 int nLimit = 500 + locator.GetDistanceBack();
2339 unsigned int nBytes = 0;
2340 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2341 for (; pindex; pindex = pindex->pnext)
2343 if (pindex->GetBlockHash() == hashStop)
2345 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2348 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2350 block.ReadFromDisk(pindex, true);
2351 nBytes += block.GetSerializeSize(SER_NETWORK);
2352 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2354 // When this block is requested, we'll send an inv that'll make them
2355 // getblocks the next batch of inventory.
2356 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2357 pfrom->hashContinue = pindex->GetBlockHash();
2364 else if (strCommand == "getheaders")
2366 CBlockLocator locator;
2368 vRecv >> locator >> hashStop;
2370 CBlockIndex* pindex = NULL;
2371 if (locator.IsNull())
2373 // If locator is null, return the hashStop block
2374 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2375 if (mi == mapBlockIndex.end())
2377 pindex = (*mi).second;
2381 // Find the last block the caller has in the main chain
2382 pindex = locator.GetBlockIndex();
2384 pindex = pindex->pnext;
2387 vector<CBlock> vHeaders;
2388 int nLimit = 2000 + locator.GetDistanceBack();
2389 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2390 for (; pindex; pindex = pindex->pnext)
2392 vHeaders.push_back(pindex->GetBlockHeader());
2393 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2396 pfrom->PushMessage("headers", vHeaders);
2400 else if (strCommand == "tx")
2402 vector<uint256> vWorkQueue;
2403 CDataStream vMsg(vRecv);
2407 CInv inv(MSG_TX, tx.GetHash());
2408 pfrom->AddInventoryKnown(inv);
2410 bool fMissingInputs = false;
2411 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2413 SyncWithWallets(tx, NULL, true);
2414 RelayMessage(inv, vMsg);
2415 mapAlreadyAskedFor.erase(inv);
2416 vWorkQueue.push_back(inv.hash);
2418 // Recursively process any orphan transactions that depended on this one
2419 for (int i = 0; i < vWorkQueue.size(); i++)
2421 uint256 hashPrev = vWorkQueue[i];
2422 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2423 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2426 const CDataStream& vMsg = *((*mi).second);
2428 CDataStream(vMsg) >> tx;
2429 CInv inv(MSG_TX, tx.GetHash());
2431 if (tx.AcceptToMemoryPool(true))
2433 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2434 SyncWithWallets(tx, NULL, true);
2435 RelayMessage(inv, vMsg);
2436 mapAlreadyAskedFor.erase(inv);
2437 vWorkQueue.push_back(inv.hash);
2442 BOOST_FOREACH(uint256 hash, vWorkQueue)
2443 EraseOrphanTx(hash);
2445 else if (fMissingInputs)
2447 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2450 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2454 else if (strCommand == "block")
2459 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2462 CInv inv(MSG_BLOCK, block.GetHash());
2463 pfrom->AddInventoryKnown(inv);
2465 if (ProcessBlock(pfrom, &block))
2466 mapAlreadyAskedFor.erase(inv);
2467 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2471 else if (strCommand == "getaddr")
2473 // Nodes rebroadcast an addr every 24 hours
2474 pfrom->vAddrToSend.clear();
2475 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2476 CRITICAL_BLOCK(cs_mapAddresses)
2478 unsigned int nCount = 0;
2479 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2481 const CAddress& addr = item.second;
2482 if (addr.nTime > nSince)
2485 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2487 const CAddress& addr = item.second;
2488 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2489 pfrom->PushAddress(addr);
2495 else if (strCommand == "checkorder")
2500 if (!GetBoolArg("-allowreceivebyip"))
2502 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2509 /// we have a chance to check the order here
2511 // Keep giving the same key to the same ip until they use it
2512 if (!mapReuseKey.count(pfrom->addr.ip))
2513 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2515 // Send back approval of order and pubkey to use
2516 CScript scriptPubKey;
2517 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2518 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2522 else if (strCommand == "reply")
2527 CRequestTracker tracker;
2528 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2530 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2531 if (mi != pfrom->mapRequests.end())
2533 tracker = (*mi).second;
2534 pfrom->mapRequests.erase(mi);
2537 if (!tracker.IsNull())
2538 tracker.fn(tracker.param1, vRecv);
2542 else if (strCommand == "ping")
2547 else if (strCommand == "alert")
2552 if (alert.ProcessAlert())
2555 pfrom->setKnown.insert(alert.GetHash());
2556 CRITICAL_BLOCK(cs_vNodes)
2557 BOOST_FOREACH(CNode* pnode, vNodes)
2558 alert.RelayTo(pnode);
2565 // Ignore unknown commands for extensibility
2569 // Update the last seen time for this node's address
2570 if (pfrom->fNetworkNode)
2571 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2572 AddressCurrentlyConnected(pfrom->addr);
2578 bool ProcessMessages(CNode* pfrom)
2580 CDataStream& vRecv = pfrom->vRecv;
2584 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2588 // (4) message start
2597 // Scan for message start
2598 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2599 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2600 if (vRecv.end() - pstart < nHeaderSize)
2602 if (vRecv.size() > nHeaderSize)
2604 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2605 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2609 if (pstart - vRecv.begin() > 0)
2610 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2611 vRecv.erase(vRecv.begin(), pstart);
2614 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2619 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2622 string strCommand = hdr.GetCommand();
2625 unsigned int nMessageSize = hdr.nMessageSize;
2626 if (nMessageSize > MAX_SIZE)
2628 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2631 if (nMessageSize > vRecv.size())
2633 // Rewind and wait for rest of message
2634 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2639 if (vRecv.GetVersion() >= 209)
2641 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2642 unsigned int nChecksum = 0;
2643 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2644 if (nChecksum != hdr.nChecksum)
2646 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2647 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2652 // Copy message to its own buffer
2653 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2654 vRecv.ignore(nMessageSize);
2660 CRITICAL_BLOCK(cs_main)
2661 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2665 catch (std::ios_base::failure& e)
2667 if (strstr(e.what(), "end of data"))
2669 // Allow exceptions from underlength message on vRecv
2670 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
2672 else if (strstr(e.what(), "size too large"))
2674 // Allow exceptions from overlong size
2675 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2679 PrintExceptionContinue(&e, "ProcessMessage()");
2682 catch (std::exception& e) {
2683 PrintExceptionContinue(&e, "ProcessMessage()");
2685 PrintExceptionContinue(NULL, "ProcessMessage()");
2689 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2697 bool SendMessages(CNode* pto, bool fSendTrickle)
2699 CRITICAL_BLOCK(cs_main)
2701 // Don't send anything until we get their version message
2702 if (pto->nVersion == 0)
2706 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2707 pto->PushMessage("ping");
2709 // Resend wallet transactions that haven't gotten in a block yet
2710 ResendWalletTransactions();
2712 // Address refresh broadcast
2713 static int64 nLastRebroadcast;
2714 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2716 nLastRebroadcast = GetTime();
2717 CRITICAL_BLOCK(cs_vNodes)
2719 BOOST_FOREACH(CNode* pnode, vNodes)
2721 // Periodically clear setAddrKnown to allow refresh broadcasts
2722 pnode->setAddrKnown.clear();
2724 // Rebroadcast our address
2725 if (addrLocalHost.IsRoutable() && !fUseProxy)
2727 CAddress addr(addrLocalHost);
2728 addr.nTime = GetAdjustedTime();
2729 pnode->PushAddress(addr);
2735 // Clear out old addresses periodically so it's not too much work at once
2736 static int64 nLastClear;
2737 if (nLastClear == 0)
2738 nLastClear = GetTime();
2739 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2741 nLastClear = GetTime();
2742 CRITICAL_BLOCK(cs_mapAddresses)
2745 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2746 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2747 mi != mapAddresses.end();)
2749 const CAddress& addr = (*mi).second;
2750 if (addr.nTime < nSince)
2752 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2754 addrdb.EraseAddress(addr);
2755 mapAddresses.erase(mi++);
2769 vector<CAddress> vAddr;
2770 vAddr.reserve(pto->vAddrToSend.size());
2771 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2773 // returns true if wasn't already contained in the set
2774 if (pto->setAddrKnown.insert(addr).second)
2776 vAddr.push_back(addr);
2777 // receiver rejects addr messages larger than 1000
2778 if (vAddr.size() >= 1000)
2780 pto->PushMessage("addr", vAddr);
2785 pto->vAddrToSend.clear();
2787 pto->PushMessage("addr", vAddr);
2792 // Message: inventory
2795 vector<CInv> vInvWait;
2796 CRITICAL_BLOCK(pto->cs_inventory)
2798 vInv.reserve(pto->vInventoryToSend.size());
2799 vInvWait.reserve(pto->vInventoryToSend.size());
2800 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2802 if (pto->setInventoryKnown.count(inv))
2805 // trickle out tx inv to protect privacy
2806 if (inv.type == MSG_TX && !fSendTrickle)
2808 // 1/4 of tx invs blast to all immediately
2809 static uint256 hashSalt;
2811 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2812 uint256 hashRand = inv.hash ^ hashSalt;
2813 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2814 bool fTrickleWait = ((hashRand & 3) != 0);
2816 // always trickle our own transactions
2820 if (GetTransaction(inv.hash, wtx))
2822 fTrickleWait = true;
2827 vInvWait.push_back(inv);
2832 // returns true if wasn't already contained in the set
2833 if (pto->setInventoryKnown.insert(inv).second)
2835 vInv.push_back(inv);
2836 if (vInv.size() >= 1000)
2838 pto->PushMessage("inv", vInv);
2843 pto->vInventoryToSend = vInvWait;
2846 pto->PushMessage("inv", vInv);
2852 vector<CInv> vGetData;
2853 int64 nNow = GetTime() * 1000000;
2855 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2857 const CInv& inv = (*pto->mapAskFor.begin()).second;
2858 if (!AlreadyHave(txdb, inv))
2860 printf("sending getdata: %s\n", inv.ToString().c_str());
2861 vGetData.push_back(inv);
2862 if (vGetData.size() >= 1000)
2864 pto->PushMessage("getdata", vGetData);
2868 mapAlreadyAskedFor[inv] = nNow;
2869 pto->mapAskFor.erase(pto->mapAskFor.begin());
2871 if (!vGetData.empty())
2872 pto->PushMessage("getdata", vGetData);
2891 //////////////////////////////////////////////////////////////////////////////
2896 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2898 unsigned char* pdata = (unsigned char*)pbuffer;
2899 unsigned int blocks = 1 + ((len + 8) / 64);
2900 unsigned char* pend = pdata + 64 * blocks;
2901 memset(pdata + len, 0, 64 * blocks - len);
2903 unsigned int bits = len * 8;
2904 pend[-1] = (bits >> 0) & 0xff;
2905 pend[-2] = (bits >> 8) & 0xff;
2906 pend[-3] = (bits >> 16) & 0xff;
2907 pend[-4] = (bits >> 24) & 0xff;
2911 static const unsigned int pSHA256InitState[8] =
2912 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2914 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2917 unsigned char data[64];
2921 for (int i = 0; i < 16; i++)
2922 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2924 for (int i = 0; i < 8; i++)
2925 ctx.h[i] = ((uint32_t*)pinit)[i];
2927 SHA256_Update(&ctx, data, sizeof(data));
2928 for (int i = 0; i < 8; i++)
2929 ((uint32_t*)pstate)[i] = ctx.h[i];
2933 // ScanHash scans nonces looking for a hash with at least some zero bits.
2934 // It operates on big endian data. Caller does the byte reversing.
2935 // All input buffers are 16-byte aligned. nNonce is usually preserved
2936 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2937 // the block is rebuilt and nNonce starts over at zero.
2939 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2941 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2945 // Hash pdata using pmidstate as the starting state into
2946 // preformatted buffer phash1, then hash phash1 into phash
2948 SHA256Transform(phash1, pdata, pmidstate);
2949 SHA256Transform(phash, phash1, pSHA256InitState);
2951 // Return the nonce if the hash has at least some zero bits,
2952 // caller will check if it has enough to reach the target
2953 if (((unsigned short*)phash)[14] == 0)
2956 // If nothing found after trying for a while, return -1
2957 if ((nNonce & 0xffff) == 0)
2959 nHashesDone = 0xffff+1;
2965 // Some explaining would be appreciated
2970 set<uint256> setDependsOn;
2973 COrphan(CTransaction* ptxIn)
2981 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2982 BOOST_FOREACH(uint256 hash, setDependsOn)
2983 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2988 CBlock* CreateNewBlock(CWallet* pwallet)
2990 CReserveKey reservekey(pwallet);
2993 auto_ptr<CBlock> pblock(new CBlock());
2997 // Create coinbase tx
2999 txNew.vin.resize(1);
3000 txNew.vin[0].prevout.SetNull();
3001 txNew.vout.resize(1);
3002 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3004 // Add our coinbase tx as first transaction
3005 pblock->vtx.push_back(txNew);
3007 // ppcoin: if coinstake available add coinstake tx
3008 static unsigned int nLastCoinStakeCheckTime = GetAdjustedTime() - nMaxClockDrift; // only initialized at startup
3009 CBlockIndex* pindexPrev = pindexBest;
3010 while (nLastCoinStakeCheckTime < GetAdjustedTime())
3012 pindexPrev = pindexBest; // get best block again to avoid getting stale
3013 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
3014 static CCriticalSection cs;
3015 CTransaction txCoinStake;
3018 nLastCoinStakeCheckTime++;
3019 txCoinStake.nTime = nLastCoinStakeCheckTime;
3021 if (pwallet->CreateCoinStake(pblock->nBits, txCoinStake))
3023 pblock->vtx.push_back(txCoinStake);
3024 pblock->vtx[0].vout[0].SetEmpty();
3029 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
3031 // Collect memory pool transactions into the block
3033 CRITICAL_BLOCK(cs_main)
3034 CRITICAL_BLOCK(cs_mapTransactions)
3038 // Priority order to process transactions
3039 list<COrphan> vOrphan; // list memory doesn't move
3040 map<uint256, vector<COrphan*> > mapDependers;
3041 multimap<double, CTransaction*> mapPriority;
3042 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3044 CTransaction& tx = (*mi).second;
3045 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
3048 COrphan* porphan = NULL;
3049 double dPriority = 0;
3050 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3052 // Read prev transaction
3053 CTransaction txPrev;
3055 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3057 // Has to wait for dependencies
3060 // Use list for automatic deletion
3061 vOrphan.push_back(COrphan(&tx));
3062 porphan = &vOrphan.back();
3064 mapDependers[txin.prevout.hash].push_back(porphan);
3065 porphan->setDependsOn.insert(txin.prevout.hash);
3068 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3070 // Read block header
3071 int nConf = txindex.GetDepthInMainChain();
3073 dPriority += (double)nValueIn * nConf;
3075 if (fDebug && GetBoolArg("-printpriority"))
3076 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3079 // Priority is sum(valuein * age) / txsize
3080 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3083 porphan->dPriority = dPriority;
3085 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3087 if (fDebug && GetBoolArg("-printpriority"))
3089 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3096 // Collect transactions into block
3097 map<uint256, CTxIndex> mapTestPool;
3098 uint64 nBlockSize = 1000;
3099 int nBlockSigOps = 100;
3100 while (!mapPriority.empty())
3102 // Take highest priority transaction off priority queue
3103 double dPriority = -(*mapPriority.begin()).first;
3104 CTransaction& tx = *(*mapPriority.begin()).second;
3105 mapPriority.erase(mapPriority.begin());
3108 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3109 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3111 int nTxSigOps = tx.GetSigOpCount();
3112 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3116 if (tx.nTime > GetAdjustedTime())
3119 // ppcoin: simplify transaction fee - allow free = false
3120 int64 nMinFee = tx.GetMinFee(nBlockSize, false, true);
3122 // Connecting shouldn't fail due to dependency on other memory pool transactions
3123 // because we're already processing them in order of dependency
3124 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3125 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3127 swap(mapTestPool, mapTestPoolTmp);
3130 pblock->vtx.push_back(tx);
3131 nBlockSize += nTxSize;
3132 nBlockSigOps += nTxSigOps;
3134 // Add transactions that depend on this one to the priority queue
3135 uint256 hash = tx.GetHash();
3136 if (mapDependers.count(hash))
3138 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3140 if (!porphan->setDependsOn.empty())
3142 porphan->setDependsOn.erase(hash);
3143 if (porphan->setDependsOn.empty())
3144 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3150 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
3153 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3154 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3155 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3156 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
3157 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
3160 return pblock.release();
3164 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3166 // Update nExtraNonce
3167 static uint256 hashPrevBlock;
3168 if (hashPrevBlock != pblock->hashPrevBlock)
3171 hashPrevBlock = pblock->hashPrevBlock;
3174 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3175 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3179 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3182 // Prebuild hash buffers
3189 uint256 hashPrevBlock;
3190 uint256 hashMerkleRoot;
3193 unsigned int nNonce;
3196 unsigned char pchPadding0[64];
3198 unsigned char pchPadding1[64];
3201 memset(&tmp, 0, sizeof(tmp));
3203 tmp.block.nVersion = pblock->nVersion;
3204 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3205 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3206 tmp.block.nTime = pblock->nTime;
3207 tmp.block.nBits = pblock->nBits;
3208 tmp.block.nNonce = pblock->nNonce;
3210 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3211 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3213 // Byte swap all the input buffer
3214 for (int i = 0; i < sizeof(tmp)/4; i++)
3215 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3217 // Precalc the first half of the first hash, which stays constant
3218 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3220 memcpy(pdata, &tmp.block, 128);
3221 memcpy(phash1, &tmp.hash1, 64);
3225 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3227 uint256 hash = pblock->GetHash();
3228 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3230 if (hash > hashTarget && pblock->IsProofOfWork())
3231 return error("BitcoinMiner : proof-of-work not meeting target");
3234 printf("BitcoinMiner:\n");
3235 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3237 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3238 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3241 CRITICAL_BLOCK(cs_main)
3243 if (pblock->hashPrevBlock != hashBestChain)
3244 return error("BitcoinMiner : generated block is stale");
3246 // Remove key from key pool
3247 reservekey.KeepKey();
3249 // Track how many getdata requests this block gets
3250 CRITICAL_BLOCK(wallet.cs_wallet)
3251 wallet.mapRequestCount[pblock->GetHash()] = 0;
3253 // Process this block the same as if we had received it from another node
3254 if (!ProcessBlock(NULL, pblock))
3255 return error("BitcoinMiner : ProcessBlock, block not accepted");
3261 void static ThreadBitcoinMiner(void* parg);
3263 void static BitcoinMiner(CWallet *pwallet)
3265 printf("BitcoinMiner started\n");
3266 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3268 // Each thread has its own key and counter
3269 CReserveKey reservekey(pwallet);
3270 unsigned int nExtraNonce = 0;
3272 while (fGenerateBitcoins)
3274 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3278 while (vNodes.empty() || IsInitialBlockDownload())
3283 if (!fGenerateBitcoins)
3291 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3292 CBlockIndex* pindexPrev = pindexBest;
3294 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet));
3298 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3300 // ppcoin: if proof-of-stake block found then process block
3301 if (pblock->IsProofOfStake())
3303 // should be able to sign block - assert here for now
3304 assert(pblock->SignBlock(*pwalletMain));
3305 printf("BitcoinMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
3306 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3307 CheckWork(pblock.get(), *pwalletMain, reservekey);
3308 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3312 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3316 // Prebuild hash buffers
3318 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3319 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3320 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3322 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3324 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3325 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3331 int64 nStart = GetTime();
3332 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3334 uint256& hash = *alignup<16>(hashbuf);
3337 unsigned int nHashesDone = 0;
3338 unsigned int nNonceFound;
3341 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3342 (char*)&hash, nHashesDone);
3344 // Check if something found
3345 if (nNonceFound != -1)
3347 for (int i = 0; i < sizeof(hash)/4; i++)
3348 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3350 if (hash <= hashTarget)
3353 pblock->nNonce = ByteReverse(nNonceFound);
3354 assert(hash == pblock->GetHash());
3355 // should be able to sign block - assert here for now
3356 assert(pblock->SignBlock(*pwalletMain));
3358 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3359 CheckWork(pblock.get(), *pwalletMain, reservekey);
3360 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3366 static int64 nHashCounter;
3367 if (nHPSTimerStart == 0)
3369 nHPSTimerStart = GetTimeMillis();
3373 nHashCounter += nHashesDone;
3374 if (GetTimeMillis() - nHPSTimerStart > 4000)
3376 static CCriticalSection cs;
3379 if (GetTimeMillis() - nHPSTimerStart > 4000)
3381 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3382 nHPSTimerStart = GetTimeMillis();
3384 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3385 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3386 static int64 nLogTime;
3387 if (GetTime() - nLogTime > 30 * 60)
3389 nLogTime = GetTime();
3390 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3391 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3397 // Check for stop or if block needs to be rebuilt
3400 if (!fGenerateBitcoins)
3402 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3406 if (nBlockNonce >= 0xffff0000)
3408 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3410 if (pindexPrev != pindexBest)
3413 // Update nTime every few seconds
3414 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3415 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
3416 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
3417 nBlockTime = ByteReverse(pblock->nTime);
3418 if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
3419 break; // need to update coinbase timestamp
3424 void static ThreadBitcoinMiner(void* parg)
3426 CWallet* pwallet = (CWallet*)parg;
3429 vnThreadsRunning[3]++;
3430 BitcoinMiner(pwallet);
3431 vnThreadsRunning[3]--;
3433 catch (std::exception& e) {
3434 vnThreadsRunning[3]--;
3435 PrintException(&e, "ThreadBitcoinMiner()");
3437 vnThreadsRunning[3]--;
3438 PrintException(NULL, "ThreadBitcoinMiner()");
3440 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3442 if (vnThreadsRunning[3] == 0)
3444 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3448 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3450 if (fGenerateBitcoins != fGenerate)
3452 fGenerateBitcoins = fGenerate;
3453 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3456 if (fGenerateBitcoins)
3458 int nProcessors = boost::thread::hardware_concurrency();
3459 printf("%d processors\n", nProcessors);
3460 if (nProcessors < 1)
3462 if (fLimitProcessors && nProcessors > nLimitProcessors)
3463 nProcessors = nLimitProcessors;
3464 int nAddThreads = nProcessors - vnThreadsRunning[3];
3465 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3466 for (int i = 0; i < nAddThreads; i++)
3468 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3469 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");