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<pair<COutPoint, unsigned int> > 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;
48 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
50 map<uint256, CDataStream*> mapOrphanTransactions;
51 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
58 int fGenerateBitcoins = false;
59 int64 nTransactionFee = MIN_TX_FEE;
60 int fLimitProcessors = false;
61 int nLimitProcessors = 1;
62 int fMinimizeToTray = true;
63 int fMinimizeOnClose = true;
69 int64 nBalanceReserve = 0;
71 //////////////////////////////////////////////////////////////////////////////
73 // dispatching functions
76 // These functions dispatch to one or all registered wallets
79 void RegisterWallet(CWallet* pwalletIn)
81 CRITICAL_BLOCK(cs_setpwalletRegistered)
83 setpwalletRegistered.insert(pwalletIn);
87 void UnregisterWallet(CWallet* pwalletIn)
89 CRITICAL_BLOCK(cs_setpwalletRegistered)
91 setpwalletRegistered.erase(pwalletIn);
95 // check whether the passed transaction is from us
96 bool static IsFromMe(CTransaction& tx)
98 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
99 if (pwallet->IsFromMe(tx))
104 // get the wallet transaction with the given hash (if it exists)
105 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
107 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
108 if (pwallet->GetTransaction(hashTx,wtx))
113 // erases transaction with the given hash from all wallets
114 void static EraseFromWallets(uint256 hash)
116 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
117 pwallet->EraseFromWallet(hash);
120 // make sure all wallets know about the given transaction, in the given block
121 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true)
125 // ppcoin: wallets need to refund inputs when disconnecting coinstake
126 if (tx.IsCoinStake())
127 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
128 if (pwallet->IsFromMe(tx))
129 pwallet->DisableTransaction(tx);
133 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
134 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
137 // notify wallets about a new best chain
138 void static SetBestChain(const CBlockLocator& loc)
140 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
141 pwallet->SetBestChain(loc);
144 // notify wallets about an updated transaction
145 void static UpdatedTransaction(const uint256& hashTx)
147 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
148 pwallet->UpdatedTransaction(hashTx);
152 void static PrintWallets(const CBlock& block)
154 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
155 pwallet->PrintWallet(block);
158 // notify wallets about an incoming inventory (for request counts)
159 void static Inventory(const uint256& hash)
161 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
162 pwallet->Inventory(hash);
165 // ask wallets to resend their transactions
166 void static ResendWalletTransactions()
168 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
169 pwallet->ResendWalletTransactions();
178 //////////////////////////////////////////////////////////////////////////////
180 // mapOrphanTransactions
183 void static AddOrphanTx(const CDataStream& vMsg)
186 CDataStream(vMsg) >> tx;
187 uint256 hash = tx.GetHash();
188 if (mapOrphanTransactions.count(hash))
190 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
191 BOOST_FOREACH(const CTxIn& txin, tx.vin)
192 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
195 void static EraseOrphanTx(uint256 hash)
197 if (!mapOrphanTransactions.count(hash))
199 const CDataStream* pvMsg = mapOrphanTransactions[hash];
201 CDataStream(*pvMsg) >> tx;
202 BOOST_FOREACH(const CTxIn& txin, tx.vin)
204 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
205 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
207 if ((*mi).second == pvMsg)
208 mapOrphanTransactionsByPrev.erase(mi++);
214 mapOrphanTransactions.erase(hash);
224 //////////////////////////////////////////////////////////////////////////////
226 // CTransaction and CTxIndex
229 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
232 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
234 if (!ReadFromDisk(txindexRet.pos))
236 if (prevout.n >= vout.size())
244 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
247 return ReadFromDisk(txdb, prevout, txindex);
250 bool CTransaction::ReadFromDisk(COutPoint prevout)
254 return ReadFromDisk(txdb, prevout, txindex);
259 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
271 // Load the block this tx is in
273 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
275 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
280 // Update the tx's hashBlock
281 hashBlock = pblock->GetHash();
283 // Locate the transaction
284 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
285 if (pblock->vtx[nIndex] == *(CTransaction*)this)
287 if (nIndex == pblock->vtx.size())
289 vMerkleBranch.clear();
291 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
295 // Fill in merkle branch
296 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
299 // Is the tx in a block that's in the main chain
300 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
301 if (mi == mapBlockIndex.end())
303 CBlockIndex* pindex = (*mi).second;
304 if (!pindex || !pindex->IsInMainChain())
307 return pindexBest->nHeight - pindex->nHeight + 1;
316 bool CTransaction::CheckTransaction() const
318 // Basic checks that don't depend on any context
320 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
322 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
324 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
325 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
327 // Check for negative or overflow output values
329 for (int i = 0; i < vout.size(); i++)
331 const CTxOut& txout = vout[i];
332 if (txout.IsEmpty() && (!IsCoinBase()) && (!IsCoinStake()))
333 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
334 if (txout.nValue < 0)
335 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
336 if (txout.nValue > MAX_MONEY)
337 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
338 nValueOut += txout.nValue;
339 if (!MoneyRange(nValueOut))
340 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
343 // Check for duplicate inputs
344 set<COutPoint> vInOutPoints;
345 BOOST_FOREACH(const CTxIn& txin, vin)
347 if (vInOutPoints.count(txin.prevout))
349 vInOutPoints.insert(txin.prevout);
354 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
355 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
359 BOOST_FOREACH(const CTxIn& txin, vin)
360 if (txin.prevout.IsNull())
361 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
367 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
370 *pfMissingInputs = false;
372 if (!CheckTransaction())
373 return error("AcceptToMemoryPool() : CheckTransaction failed");
375 // Coinbase is only valid in a block, not as a loose transaction
377 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
378 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
380 return DoS(100, error("AcceptToMemoryPool() : coinstake as individual tx"));
382 // To help v0.1.5 clients who would see it as a negative number
383 if ((int64)nLockTime > INT_MAX)
384 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
387 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
388 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
389 // attacks disallow transactions with more than one SigOp per 34 bytes.
390 // 34 bytes because a TxOut is:
391 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
392 if (GetSigOpCount() > nSize / 34 || nSize < 100)
393 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
395 // Rather not work on nonstandard transactions (unless -testnet)
396 if (!fTestNet && !IsStandard())
397 return error("AcceptToMemoryPool() : nonstandard transaction type");
399 // Do we already have it?
400 uint256 hash = GetHash();
401 CRITICAL_BLOCK(cs_mapTransactions)
402 if (mapTransactions.count(hash))
405 if (txdb.ContainsTx(hash))
408 // Check for conflicts with in-memory transactions
409 CTransaction* ptxOld = NULL;
410 for (int i = 0; i < vin.size(); i++)
412 COutPoint outpoint = vin[i].prevout;
413 if (mapNextTx.count(outpoint))
415 // Disable replacement feature for now
418 // Allow replacing with a newer version of the same transaction
421 ptxOld = mapNextTx[outpoint].ptx;
422 if (ptxOld->IsFinal())
424 if (!IsNewerThan(*ptxOld))
426 for (int i = 0; i < vin.size(); i++)
428 COutPoint outpoint = vin[i].prevout;
429 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
438 // Check against previous transactions
439 map<uint256, CTxIndex> mapUnused;
441 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
444 *pfMissingInputs = true;
445 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
448 // Don't accept it if it can't get into a block
449 if (nFees < GetMinFee(1000, false, true))
450 return error("AcceptToMemoryPool() : not enough fees");
452 // Continuously rate-limit free transactions
453 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
454 // be annoying or make other's transactions take longer to confirm.
455 if (nFees < MIN_RELAY_TX_FEE)
457 static CCriticalSection cs;
458 static double dFreeCount;
459 static int64 nLastTime;
460 int64 nNow = GetTime();
464 // Use an exponentially decaying ~10-minute window:
465 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
467 // -limitfreerelay unit is thousand-bytes-per-minute
468 // At default rate it would take over a month to fill 1GB
469 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
470 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
472 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
478 // Store transaction in memory
479 CRITICAL_BLOCK(cs_mapTransactions)
483 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
484 ptxOld->RemoveFromMemoryPool();
486 AddToMemoryPoolUnchecked();
489 ///// are we sure this is ok when loading transactions or restoring block txes
490 // If updated, erase old tx from wallet
492 EraseFromWallets(ptxOld->GetHash());
494 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
498 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
501 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
504 bool CTransaction::AddToMemoryPoolUnchecked()
506 // Add to memory pool without checking anything. Don't call this directly,
507 // call AcceptToMemoryPool to properly check the transaction first.
508 CRITICAL_BLOCK(cs_mapTransactions)
510 uint256 hash = GetHash();
511 mapTransactions[hash] = *this;
512 for (int i = 0; i < vin.size(); i++)
513 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
514 nTransactionsUpdated++;
520 bool CTransaction::RemoveFromMemoryPool()
522 // Remove transaction from memory pool
523 CRITICAL_BLOCK(cs_mapTransactions)
525 BOOST_FOREACH(const CTxIn& txin, vin)
526 mapNextTx.erase(txin.prevout);
527 mapTransactions.erase(GetHash());
528 nTransactionsUpdated++;
538 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
540 if (hashBlock == 0 || nIndex == -1)
543 // Find the block it claims to be in
544 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
545 if (mi == mapBlockIndex.end())
547 CBlockIndex* pindex = (*mi).second;
548 if (!pindex || !pindex->IsInMainChain())
551 // Make sure the merkle branch connects to this block
552 if (!fMerkleVerified)
554 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
556 fMerkleVerified = true;
559 nHeightRet = pindex->nHeight;
560 return pindexBest->nHeight - pindex->nHeight + 1;
564 int CMerkleTx::GetBlocksToMaturity() const
566 if (!(IsCoinBase() || IsCoinStake()))
568 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
572 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
576 if (!IsInMainChain() && !ClientConnectInputs())
578 return CTransaction::AcceptToMemoryPool(txdb, false);
582 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
586 bool CMerkleTx::AcceptToMemoryPool()
589 return AcceptToMemoryPool(txdb);
594 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
596 CRITICAL_BLOCK(cs_mapTransactions)
598 // Add previous supporting transactions first
599 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
601 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
603 uint256 hash = tx.GetHash();
604 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
605 tx.AcceptToMemoryPool(txdb, fCheckInputs);
608 return AcceptToMemoryPool(txdb, fCheckInputs);
613 bool CWalletTx::AcceptWalletTransaction()
616 return AcceptWalletTransaction(txdb);
619 int CTxIndex::GetDepthInMainChain() const
623 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
625 // Find the block in the index
626 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
627 if (mi == mapBlockIndex.end())
629 CBlockIndex* pindex = (*mi).second;
630 if (!pindex || !pindex->IsInMainChain())
632 return 1 + nBestHeight - pindex->nHeight;
644 //////////////////////////////////////////////////////////////////////////////
646 // CBlock and CBlockIndex
649 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
651 if (!fReadTransactions)
653 *this = pindex->GetBlockHeader();
656 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
658 if (GetHash() != pindex->GetBlockHash())
659 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
663 uint256 static GetOrphanRoot(const CBlock* pblock)
665 // Work back to the first block in the orphan chain
666 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
667 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
668 return pblock->GetHash();
671 int64 static GetProofOfWorkReward(unsigned int nBits)
673 CBigNum bnSubsidyLimit = 9999 * COIN; // subsidy amount for difficulty 1
675 bnTarget.SetCompact(nBits);
676 CBigNum bnTargetLimit = bnProofOfWorkLimit;
677 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
679 // ppcoin: subsidy is cut in half every 16x multiply of difficulty
680 // A reasonably continuous curve is used to avoid shock to market
681 // (nSubsidyLimit / nSubsidy) ** 4 == bnProofOfWorkLimit / bnTarget
682 CBigNum bnLowerBound = CENT;
683 CBigNum bnUpperBound = bnSubsidyLimit;
684 while (bnLowerBound + CENT <= bnUpperBound)
686 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
687 if (fDebug && GetBoolArg("-printcreation"))
688 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
689 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
690 bnUpperBound = bnMidValue;
692 bnLowerBound = bnMidValue;
695 int64 nSubsidy = bnUpperBound.getuint64();
696 nSubsidy = (nSubsidy / CENT) * CENT;
697 if (fDebug && GetBoolArg("-printcreation"))
698 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
703 // ppcoin: miner's coin stake is rewarded based on coin age spent (coin-days)
704 int64 GetProofOfStakeReward(int64 nCoinAge)
706 static int64 nRewardCoinYear = CENT; // creation amount per coin-year
707 int64 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
708 if (fDebug && GetBoolArg("-printcreation"))
709 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nCoinAge);
713 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
714 static const int64 nTargetSpacingStake = 10 * 60; // ten minutes
715 static const int64 nTargetSpacingWorkMax = 2 * 60 * 60; // two hours
716 static const int64 nMaxClockDrift = 2 * 60 * 60; // two hours
719 // minimum amount of work that could possibly be required nTime after
720 // minimum work required was nBase
722 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
725 bnResult.SetCompact(nBase);
726 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
728 // Maximum 400% adjustment...
730 // ... in best-case exactly 4-times-normal target time
731 nTime -= nTargetTimespan*4;
733 if (bnResult > bnProofOfWorkLimit)
734 bnResult = bnProofOfWorkLimit;
735 return bnResult.GetCompact();
738 // ppcoin: find last block index up to pindex
739 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
741 while (pindex && (pindex->IsProofOfStake() != fProofOfStake))
742 pindex = pindex->pprev;
746 unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
748 // Genesis block and first block
749 if (pindexLast == NULL || pindexLast->pprev == NULL)
750 return bnProofOfWorkLimit.GetCompact();
752 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
753 if (pindexPrev == NULL)
754 return bnProofOfWorkLimit.GetCompact();
755 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
756 if (pindexPrevPrev == NULL)
757 return bnProofOfWorkLimit.GetCompact();
758 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
760 // ppcoin: target change every block
761 // ppcoin: retarget with exponential moving toward target spacing
763 bnNew.SetCompact(pindexPrev->nBits);
764 int64 nTargetSpacing = fProofOfStake? nTargetSpacingStake : min(nTargetSpacingWorkMax, nTargetSpacingStake * (1 + pindexLast->nHeight - pindexPrev->nHeight));
765 int64 nInterval = nTargetTimespan / nTargetSpacing;
766 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
767 bnNew /= ((nInterval + 1) * nTargetSpacing);
769 if (bnNew > bnProofOfWorkLimit)
770 bnNew = bnProofOfWorkLimit;
772 return bnNew.GetCompact();
775 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
778 bnTarget.SetCompact(nBits);
781 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
782 return error("CheckProofOfWork() : nBits below minimum work");
784 // Check proof of work matches claimed amount
785 if (hash > bnTarget.getuint256())
786 return error("CheckProofOfWork() : hash doesn't match nBits");
791 // Return maximum amount of blocks that other nodes claim to have
792 int GetNumBlocksOfPeers()
794 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
797 bool IsInitialBlockDownload()
799 if (pindexBest == NULL || nBestHeight < (Checkpoints::GetTotalBlocksEstimate()-nInitialBlockThreshold))
801 static int64 nLastUpdate;
802 static CBlockIndex* pindexLastBest;
803 if (pindexBest != pindexLastBest)
805 pindexLastBest = pindexBest;
806 nLastUpdate = GetTime();
808 return (GetTime() - nLastUpdate < 10 &&
809 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
812 void static InvalidChainFound(CBlockIndex* pindexNew)
814 if (pindexNew->nChainTrust > nBestInvalidTrust)
816 nBestInvalidTrust = pindexNew->nChainTrust;
817 CTxDB().WriteBestInvalidTrust(nBestInvalidTrust);
820 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());
821 printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
822 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
823 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
836 bool CTransaction::DisconnectInputs(CTxDB& txdb)
838 // Relinquish previous transactions' spent pointers
841 BOOST_FOREACH(const CTxIn& txin, vin)
843 COutPoint prevout = txin.prevout;
845 // Get prev txindex from disk
847 if (!txdb.ReadTxIndex(prevout.hash, txindex))
848 return error("DisconnectInputs() : ReadTxIndex failed");
850 if (prevout.n >= txindex.vSpent.size())
851 return error("DisconnectInputs() : prevout.n out of range");
853 // Mark outpoint as not spent
854 txindex.vSpent[prevout.n].SetNull();
857 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
858 return error("DisconnectInputs() : UpdateTxIndex failed");
862 // Remove transaction from index
863 if (!txdb.EraseTxIndex(*this))
864 return error("DisconnectInputs() : EraseTxPos failed");
870 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
871 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
873 // Take over previous transactions' spent pointers
874 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
875 // fMiner is true when called from the internal bitcoin miner
876 // ... both are false when called from CTransaction::AcceptToMemoryPool
880 for (int i = 0; i < vin.size(); i++)
882 COutPoint prevout = vin[i].prevout;
887 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
889 // Get txindex from current proposed changes
890 txindex = mapTestPool[prevout.hash];
894 // Read txindex from txdb
895 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
897 if (!fFound && (fBlock || fMiner))
898 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());
902 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
904 // Get prev tx from single transactions in memory
905 CRITICAL_BLOCK(cs_mapTransactions)
907 if (!mapTransactions.count(prevout.hash))
908 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
909 txPrev = mapTransactions[prevout.hash];
912 txindex.vSpent.resize(txPrev.vout.size());
916 // Get prev tx from disk
917 if (!txPrev.ReadFromDisk(txindex.pos))
918 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
921 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
922 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()));
924 // If prev is coinbase/coinstake, check that it's matured
925 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
926 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
927 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
928 return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight);
930 // ppcoin: check transaction timestamp
931 if (txPrev.nTime > nTime)
932 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
934 // Skip ECDSA signature verification when connecting blocks (fBlock=true) during initial download
935 // (before the last blockchain checkpoint). This is safe because block merkle hashes are
936 // still computed and checked, and any change will be caught at the next checkpoint.
937 if (!(fBlock && IsInitialBlockDownload()))
939 if (!VerifySignature(txPrev, *this, i))
940 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
942 // Check for conflicts (double-spend)
943 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
944 // for an attacker to attempt to split the network.
945 if (!txindex.vSpent[prevout.n].IsNull())
946 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());
948 // Check for negative or overflow input values
949 nValueIn += txPrev.vout[prevout.n].nValue;
950 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
951 return DoS(100, error("ConnectInputs() : txin values out of range"));
953 // Mark outpoints as spent
954 txindex.vSpent[prevout.n] = posThisTx;
957 if (fBlock || fMiner)
959 mapTestPool[prevout.hash] = txindex;
965 // ppcoin: coin stake tx earns reward instead of paying fee
967 if (!GetCoinAge(txdb, nCoinAge))
968 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
969 int64 nStakeReward = GetValueOut() - nValueIn;
970 if (nStakeReward > GetProofOfStakeReward(nCoinAge))
971 return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
975 if (nValueIn < GetValueOut())
976 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
978 // Tally transaction fees
979 int64 nTxFee = nValueIn - GetValueOut();
981 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
982 // ppcoin: enforce transaction fees for every block
983 if (nTxFee < nMinFee)
984 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;
986 if (!MoneyRange(nFees))
987 return DoS(100, error("ConnectInputs() : nFees out of range"));
993 // Add transaction to changes
994 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
998 // Add transaction to test pool
999 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1006 bool CTransaction::ClientConnectInputs()
1011 // Take over previous transactions' spent pointers
1012 CRITICAL_BLOCK(cs_mapTransactions)
1015 for (int i = 0; i < vin.size(); i++)
1017 // Get prev tx from single transactions in memory
1018 COutPoint prevout = vin[i].prevout;
1019 if (!mapTransactions.count(prevout.hash))
1021 CTransaction& txPrev = mapTransactions[prevout.hash];
1023 if (prevout.n >= txPrev.vout.size())
1027 if (!VerifySignature(txPrev, *this, i))
1028 return error("ConnectInputs() : VerifySignature failed");
1030 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1031 ///// this has to go away now that posNext is gone
1032 // // Check for conflicts
1033 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1034 // return error("ConnectInputs() : prev tx already used");
1036 // // Flag outpoints as used
1037 // txPrev.vout[prevout.n].posNext = posThisTx;
1039 nValueIn += txPrev.vout[prevout.n].nValue;
1041 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1042 return error("ClientConnectInputs() : txin values out of range");
1044 if (GetValueOut() > nValueIn)
1054 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1056 // Disconnect in reverse order
1057 for (int i = vtx.size()-1; i >= 0; i--)
1058 if (!vtx[i].DisconnectInputs(txdb))
1061 // Update block index on disk without changing it in memory.
1062 // The memory index structure will be changed after the db commits.
1065 CDiskBlockIndex blockindexPrev(pindex->pprev);
1066 blockindexPrev.hashNext = 0;
1067 if (!txdb.WriteBlockIndex(blockindexPrev))
1068 return error("DisconnectBlock() : WriteBlockIndex failed");
1071 // ppcoin: clean up wallet after disconnecting coinstake
1072 BOOST_FOREACH(CTransaction& tx, vtx)
1073 SyncWithWallets(tx, this, false, false);
1078 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1080 // Check it again in case a previous version let a bad block in
1084 //// issue here: it doesn't know the version
1085 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1087 map<uint256, CTxIndex> mapQueuedChanges;
1089 BOOST_FOREACH(CTransaction& tx, vtx)
1091 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1092 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1094 if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false, tx.GetMinFee()))
1097 // Write queued txindex changes
1098 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1100 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1101 return error("ConnectBlock() : UpdateTxIndex failed");
1104 // ppcoin: fees are not collected by miners as in bitcoin
1105 // ppcoin: fees are destroyed to compensate the entire network
1106 if (IsProofOfWork() && vtx[0].GetValueOut() > GetProofOfWorkReward(nBits))
1108 if (fDebug && GetBoolArg("-printcreation"))
1109 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1111 // Update block index on disk without changing it in memory.
1112 // The memory index structure will be changed after the db commits.
1115 CDiskBlockIndex blockindexPrev(pindex->pprev);
1116 blockindexPrev.hashNext = pindex->GetBlockHash();
1117 if (!txdb.WriteBlockIndex(blockindexPrev))
1118 return error("ConnectBlock() : WriteBlockIndex failed");
1121 // Watch for transactions paying to me
1122 BOOST_FOREACH(CTransaction& tx, vtx)
1123 SyncWithWallets(tx, this, true);
1128 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1130 printf("REORGANIZE\n");
1133 CBlockIndex* pfork = pindexBest;
1134 CBlockIndex* plonger = pindexNew;
1135 while (pfork != plonger)
1137 while (plonger->nHeight > pfork->nHeight)
1138 if (!(plonger = plonger->pprev))
1139 return error("Reorganize() : plonger->pprev is null");
1140 if (pfork == plonger)
1142 if (!(pfork = pfork->pprev))
1143 return error("Reorganize() : pfork->pprev is null");
1146 // List of what to disconnect
1147 vector<CBlockIndex*> vDisconnect;
1148 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1149 vDisconnect.push_back(pindex);
1151 // List of what to connect
1152 vector<CBlockIndex*> vConnect;
1153 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1154 vConnect.push_back(pindex);
1155 reverse(vConnect.begin(), vConnect.end());
1157 // Disconnect shorter branch
1158 vector<CTransaction> vResurrect;
1159 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1162 if (!block.ReadFromDisk(pindex))
1163 return error("Reorganize() : ReadFromDisk for disconnect failed");
1164 if (!block.DisconnectBlock(txdb, pindex))
1165 return error("Reorganize() : DisconnectBlock failed");
1167 // Queue memory transactions to resurrect
1168 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1169 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1170 vResurrect.push_back(tx);
1173 // Connect longer branch
1174 vector<CTransaction> vDelete;
1175 for (int i = 0; i < vConnect.size(); i++)
1177 CBlockIndex* pindex = vConnect[i];
1179 if (!block.ReadFromDisk(pindex))
1180 return error("Reorganize() : ReadFromDisk for connect failed");
1181 if (!block.ConnectBlock(txdb, pindex))
1185 return error("Reorganize() : ConnectBlock failed");
1188 // Queue memory transactions to delete
1189 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1190 vDelete.push_back(tx);
1192 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1193 return error("Reorganize() : WriteHashBestChain failed");
1194 if (!txdb.WriteAutoCheckpoint(Checkpoints::GetNextAutoCheckpoint(pindexNew->nCheckpoint)))
1195 return error("Reorganize() : WriteAutoCheckpoint failed");
1197 // Make sure it's successfully written to disk before changing memory structure
1198 if (!txdb.TxnCommit())
1199 return error("Reorganize() : TxnCommit failed");
1201 // Disconnect shorter branch
1202 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1204 pindex->pprev->pnext = NULL;
1206 // Connect longer branch
1207 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1209 pindex->pprev->pnext = pindex;
1211 // Resurrect memory transactions that were in the disconnected branch
1212 BOOST_FOREACH(CTransaction& tx, vResurrect)
1213 tx.AcceptToMemoryPool(txdb, false);
1215 // Delete redundant memory transactions that are in the connected branch
1216 BOOST_FOREACH(CTransaction& tx, vDelete)
1217 tx.RemoveFromMemoryPool();
1223 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1225 uint256 hash = GetHash();
1228 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1230 txdb.WriteHashBestChain(hash);
1231 txdb.WriteAutoCheckpoint(Checkpoints::GetNextAutoCheckpoint(pindexNew->nCheckpoint));
1232 if (!txdb.TxnCommit())
1233 return error("SetBestChain() : TxnCommit failed");
1234 pindexGenesisBlock = pindexNew;
1236 else if (hashPrevBlock == hashBestChain)
1238 // Adding to current best branch
1239 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash) || !txdb.WriteAutoCheckpoint(Checkpoints::GetNextAutoCheckpoint(pindexNew->nCheckpoint)))
1242 InvalidChainFound(pindexNew);
1243 return error("SetBestChain() : ConnectBlock failed");
1245 if (!txdb.TxnCommit())
1246 return error("SetBestChain() : TxnCommit failed");
1248 // Add to current best branch
1249 pindexNew->pprev->pnext = pindexNew;
1251 // Delete redundant memory transactions
1252 BOOST_FOREACH(CTransaction& tx, vtx)
1253 tx.RemoveFromMemoryPool();
1258 if (!Reorganize(txdb, pindexNew))
1261 InvalidChainFound(pindexNew);
1262 return error("SetBestChain() : Reorganize failed");
1266 // Update best block in wallet (so we can detect restored wallets)
1267 if (!IsInitialBlockDownload())
1269 const CBlockLocator locator(pindexNew);
1270 ::SetBestChain(locator);
1274 hashBestChain = hash;
1275 pindexBest = pindexNew;
1276 nBestHeight = pindexBest->nHeight;
1277 nBestChainTrust = pindexNew->nChainTrust;
1278 nTimeBestReceived = GetTime();
1279 nTransactionsUpdated++;
1280 Checkpoints::AdvanceAutoCheckpoint(pindexBest->nCheckpoint);
1281 printf("SetBestChain: new best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
1287 // ppcoin: coinstake must meet hash target according to the protocol:
1288 // input 0 must meet the formula
1289 // hash(nBits + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDay
1290 // this ensures that the chance of getting a coinstake is proportional to the
1291 // amount of coin age one owns.
1292 // The reason this hash is chosen is the following:
1293 // nBits: encodes all past block timestamps, making computing hash in advance
1295 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
1296 // generate transaction for future advantage
1297 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
1298 // nodes generating coinstake at the same time
1299 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
1301 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
1302 // generating coinstake at the same time
1303 // block/tx hash should not be used here as they can be generated in vast
1304 // quantities so as to generate blocks faster, degrading the system back into
1305 // a proof-of-work situation.
1307 bool CTransaction::CheckProofOfStake(unsigned int nBits) const
1309 CBigNum bnTargetPerCoinDay;
1310 bnTargetPerCoinDay.SetCompact(nBits);
1315 // Input 0 must match the stake hash target per coin age (nBits)
1316 const CTxIn& txin = vin[0];
1318 // 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
1325 if (nTime < txPrev.nTime)
1326 return false; // Transaction timestamp violation
1329 if (!VerifySignature(txPrev, *this, 0))
1330 return DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", GetHash().ToString().c_str()));
1332 // Read block header
1334 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1335 return false; // unable to read block of previous transaction
1336 if (block.GetBlockTime() + AUTO_CHECKPOINT_TRUST_SPAN > nTime)
1337 return false; // only count coins from at least one week ago
1339 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1340 CBigNum bnCoinDay = CBigNum(nValueIn) * (nTime-txPrev.nTime) / COIN / (24 * 60 * 60);
1342 CDataStream ss(SER_GETHASH, VERSION);
1343 ss << nBits << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << txPrev.nTime << txin.prevout.n << nTime;
1344 if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1347 return DoS(100, error("CheckProofOfStake() : check target failed on coinstake %s", GetHash().ToString().c_str()));
1350 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1351 // Only those coins last spent at least a week ago count. As those
1352 // transactions not in main chain are not currently indexed so we
1353 // might not find out about their coin age. Older transactions are
1354 // guaranteed to be in main chain by auto checkpoint. This rule is
1355 // introduced to help nodes establish a consistent view of the coin
1356 // age (trust score) of competing branches.
1357 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1359 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1365 BOOST_FOREACH(const CTxIn& txin, vin)
1367 // First try finding the previous transaction in database
1368 CTransaction txPrev;
1370 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1371 continue; // previous transaction not in main chain
1372 if (nTime < txPrev.nTime)
1373 return false; // Transaction timestamp violation
1375 // Read block header
1377 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1378 return false; // unable to read block of previous transaction
1379 if (block.GetBlockTime() + AUTO_CHECKPOINT_TRUST_SPAN > nTime)
1380 continue; // only count coins from at least one week ago
1382 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1383 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1385 if (fDebug && GetBoolArg("-printcoinage"))
1386 printf("coin age nValueIn=%-12I64d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1389 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1390 if (fDebug && GetBoolArg("-printcoinage"))
1391 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1392 nCoinAge = bnCoinDay.getuint64();
1396 // ppcoin: total coin age spent in block, in the unit of coin-days.
1397 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1402 BOOST_FOREACH(const CTransaction& tx, vtx)
1405 if (tx.GetCoinAge(txdb, nTxCoinAge))
1406 nCoinAge += nTxCoinAge;
1411 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1413 if (fDebug && GetBoolArg("-printcoinage"))
1414 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1419 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1421 // Check for duplicate
1422 uint256 hash = GetHash();
1423 if (mapBlockIndex.count(hash))
1424 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1426 // Construct new block index object
1427 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1429 return error("AddToBlockIndex() : new CBlockIndex failed");
1430 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1431 if (pindexNew->fProofOfStake)
1432 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
1434 pindexNew->phashBlock = &((*mi).first);
1435 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1436 if (miPrev != mapBlockIndex.end())
1438 pindexNew->pprev = (*miPrev).second;
1439 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1441 // ppcoin: compute chain checkpoint
1442 pindexNew->nCheckpoint = Checkpoints::GetNextChainCheckpoint(pindexNew->pprev);
1443 assert (pindexNew->nCheckpoint >= pindexNew->pprev->nCheckpoint);
1446 // ppcoin: compute chain trust score
1448 if (!GetCoinAge(nCoinAge))
1449 return error("AddToBlockIndex() : invalid transaction in block");
1450 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + nCoinAge;
1454 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1455 if (!txdb.TxnCommit())
1459 if (pindexNew->nChainTrust > nBestChainTrust)
1460 if (!SetBestChain(txdb, pindexNew))
1465 if (pindexNew == pindexBest)
1467 // Notify UI to display prev block's coinbase if it was ours
1468 static uint256 hashPrevBestCoinBase;
1469 UpdatedTransaction(hashPrevBestCoinBase);
1470 hashPrevBestCoinBase = vtx[0].GetHash();
1480 bool CBlock::CheckBlock() const
1482 // These are checks that are independent of context
1483 // that can be verified before saving an orphan block.
1486 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1487 return DoS(100, error("CheckBlock() : size limits failed"));
1489 // Check proof of work matches claimed amount
1490 if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1491 return DoS(50, error("CheckBlock() : proof of work failed"));
1494 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
1495 return error("CheckBlock() : block timestamp too far in the future");
1497 // First transaction must be coinbase, the rest must not be
1498 if (vtx.empty() || !vtx[0].IsCoinBase())
1499 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1500 for (int i = 1; i < vtx.size(); i++)
1501 if (vtx[i].IsCoinBase())
1502 return DoS(100, error("CheckBlock() : more than one coinbase"));
1504 // ppcoin: only the second transaction can be the optional coinstake
1505 for (int i = 2; i < vtx.size(); i++)
1506 if (vtx[i].IsCoinStake())
1507 return DoS(100, error("CheckBlock() : coinstake in wrong position"));
1509 // ppcoin: coinbase output should be empty if proof-of-stake block
1510 if (IsProofOfStake() && !vtx[0].vout[0].IsEmpty())
1511 return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
1513 // Check coinbase timestamp
1514 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
1515 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
1517 // Check transactions
1518 BOOST_FOREACH(const CTransaction& tx, vtx)
1520 if (!tx.CheckTransaction())
1521 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1522 // ppcoin: check transaction timestamp
1523 if (GetBlockTime() < (int64)tx.nTime)
1524 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
1527 // Check that it's not full of nonstandard transactions
1528 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1529 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1532 if (hashMerkleRoot != BuildMerkleTree())
1533 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1535 // ppcoin: 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 // Check proof-of-work or proof-of-stake
1557 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
1558 return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake"));
1560 // ppcoin: coinstake tx must meet target protocol
1561 if (IsProofOfStake() && !vtx[1].CheckProofOfStake(nBits))
1562 return error("AcceptBlock() : Block %s unable to meet hash target for coinstake", GetHash().ToString().c_str());
1564 // Check timestamp against prev
1565 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
1566 return error("AcceptBlock() : block's timestamp is too early");
1568 // Check that all transactions are finalized
1569 BOOST_FOREACH(const CTransaction& tx, vtx)
1570 if (!tx.IsFinal(nHeight, GetBlockTime()))
1571 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1573 // Check that the block chain matches the known block chain up to a hardened checkpoint
1574 if (!Checkpoints::CheckHardened(nHeight, hash))
1575 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight));
1577 // ppcoin: check that the block satisfies automatic checkpoint
1578 if (!Checkpoints::CheckAuto(pindexPrev))
1579 return DoS(100, error("AcceptBlock() : rejected by automatic checkpoint at %d", Checkpoints::nAutoCheckpoint));
1581 // Write block to history file
1582 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1583 return error("AcceptBlock() : out of disk space");
1584 unsigned int nFile = -1;
1585 unsigned int nBlockPos = 0;
1586 if (!WriteToDisk(nFile, nBlockPos))
1587 return error("AcceptBlock() : WriteToDisk failed");
1588 if (!AddToBlockIndex(nFile, nBlockPos))
1589 return error("AcceptBlock() : AddToBlockIndex failed");
1591 // Relay inventory, but don't relay old inventory during initial block download
1592 if (hashBestChain == hash)
1593 CRITICAL_BLOCK(cs_vNodes)
1594 BOOST_FOREACH(CNode* pnode, vNodes)
1595 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1596 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1601 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1603 // Check for duplicate
1604 uint256 hash = pblock->GetHash();
1605 if (mapBlockIndex.count(hash))
1606 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1607 if (mapOrphanBlocks.count(hash))
1608 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1610 // ppcoin: check proof-of-stake
1611 // Limited duplicity on stake: prevents block flood attack
1612 // Duplicate stake allowed only when there is orphan child block
1613 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash))
1614 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
1616 // Preliminary checks
1617 if (!pblock->CheckBlock())
1618 return error("ProcessBlock() : CheckBlock FAILED");
1620 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1621 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1623 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1624 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1627 pfrom->Misbehaving(100);
1628 return error("ProcessBlock() : block with timestamp before last checkpoint");
1631 bnNewBlock.SetCompact(pblock->nBits);
1633 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1634 if (pblock->IsProofOfWork() && bnNewBlock > bnRequired)
1636 pfrom->Misbehaving(100);
1637 return error("ProcessBlock() : block with too little proof-of-work");
1642 // If don't already have its previous block, shunt it off to holding area until we get it
1643 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1645 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1646 CBlock* pblock2 = new CBlock(*pblock);
1647 // ppcoin: check proof-of-stake
1648 if (pblock2->IsProofOfStake())
1650 // Limited duplicity on stake: prevents block flood attack
1651 // Duplicate stake allowed only when there is orphan child block
1652 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash))
1653 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock2->GetProofOfStake().first.ToString().c_str(), pblock2->GetProofOfStake().second, hash.ToString().c_str());
1655 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
1657 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1658 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1660 // Ask this guy to fill in what we're missing
1662 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1667 if (!pblock->AcceptBlock())
1668 return error("ProcessBlock() : AcceptBlock FAILED");
1670 // Recursively process any orphan blocks that depended on this one
1671 vector<uint256> vWorkQueue;
1672 vWorkQueue.push_back(hash);
1673 for (int i = 0; i < vWorkQueue.size(); i++)
1675 uint256 hashPrev = vWorkQueue[i];
1676 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1677 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1680 CBlock* pblockOrphan = (*mi).second;
1681 if (pblockOrphan->AcceptBlock())
1682 vWorkQueue.push_back(pblockOrphan->GetHash());
1683 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1684 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
1685 delete pblockOrphan;
1687 mapOrphanBlocksByPrev.erase(hashPrev);
1690 printf("ProcessBlock: ACCEPTED\n");
1701 bool CheckDiskSpace(uint64 nAdditionalBytes)
1703 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1705 // Check for 15MB because database could create another 10MB log file at any time
1706 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1709 string strMessage = _("Warning: Disk space is low ");
1710 strMiscWarning = strMessage;
1711 printf("*** %s\n", strMessage.c_str());
1712 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1713 CreateThread(Shutdown, NULL);
1719 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1723 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1726 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1728 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1737 static unsigned int nCurrentBlockFile = 1;
1739 FILE* AppendBlockFile(unsigned int& nFileRet)
1744 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1747 if (fseek(file, 0, SEEK_END) != 0)
1749 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1750 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1752 nFileRet = nCurrentBlockFile;
1756 nCurrentBlockFile++;
1760 bool LoadBlockIndex(bool fAllowNew)
1764 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1765 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1766 pchMessageStart[0] = 0xfa;
1767 pchMessageStart[1] = 0xbf;
1768 pchMessageStart[2] = 0xb5;
1769 pchMessageStart[3] = 0xda;
1776 if (!txdb.LoadBlockIndex())
1781 // Init with genesis block
1783 if (mapBlockIndex.empty())
1789 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1790 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1791 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1792 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1793 // vMerkleTree: 4a5e1e
1796 const char* pszTimestamp = "MarketWatch 07/Nov/2011 Gold tops $1,790 to end at over six-week high";
1798 txNew.nTime = 1325878371;
1799 txNew.vin.resize(1);
1800 txNew.vout.resize(1);
1801 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1802 txNew.vout[0].nValue = GetProofOfWorkReward(bnProofOfWorkLimit.GetCompact());
1803 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1805 block.vtx.push_back(txNew);
1806 block.hashPrevBlock = 0;
1807 block.hashMerkleRoot = block.BuildMerkleTree();
1809 block.nTime = 1325882536;
1810 block.nBits = bnProofOfWorkLimit.GetCompact();
1811 block.nNonce = 2081920190;
1815 block.nTime = 1296688602;
1816 block.nBits = 0x1d07fff8;
1817 block.nNonce = 384568319;
1821 printf("%s\n", block.GetHash().ToString().c_str());
1822 printf("%s\n", hashGenesisBlock.ToString().c_str());
1823 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1824 assert(block.hashMerkleRoot == uint256("0xc7311b56de266580cca65be108ae53d7100b5c3b17da8b1106044103abd7a521"));
1826 assert(block.GetHash() == hashGenesisBlock);
1827 assert(block.CheckBlock());
1829 // Start new block file
1831 unsigned int nBlockPos;
1832 if (!block.WriteToDisk(nFile, nBlockPos))
1833 return error("LoadBlockIndex() : writing genesis block to disk failed");
1834 if (!block.AddToBlockIndex(nFile, nBlockPos))
1835 return error("LoadBlockIndex() : genesis block not accepted");
1837 // ppcoin: initialize synchronized checkpoint
1839 if (!txdbc.WriteSyncCheckpoint(hashGenesisBlock))
1840 return error("LoadBlockIndex() : failed to init sync checkpoint");
1842 Checkpoints::hashSyncCheckpoint = hashGenesisBlock;
1850 void PrintBlockTree()
1852 // precompute tree structure
1853 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1854 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1856 CBlockIndex* pindex = (*mi).second;
1857 mapNext[pindex->pprev].push_back(pindex);
1859 //while (rand() % 3 == 0)
1860 // mapNext[pindex->pprev].push_back(pindex);
1863 vector<pair<int, CBlockIndex*> > vStack;
1864 vStack.push_back(make_pair(0, pindexGenesisBlock));
1867 while (!vStack.empty())
1869 int nCol = vStack.back().first;
1870 CBlockIndex* pindex = vStack.back().second;
1873 // print split or gap
1874 if (nCol > nPrevCol)
1876 for (int i = 0; i < nCol-1; i++)
1880 else if (nCol < nPrevCol)
1882 for (int i = 0; i < nCol; i++)
1889 for (int i = 0; i < nCol; i++)
1894 block.ReadFromDisk(pindex);
1895 printf("%d (%u,%u) %s %08lx %s tx %d",
1899 block.GetHash().ToString().substr(0,20).c_str(),
1901 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1904 PrintWallets(block);
1906 // put the main timechain first
1907 vector<CBlockIndex*>& vNext = mapNext[pindex];
1908 for (int i = 0; i < vNext.size(); i++)
1910 if (vNext[i]->pnext)
1912 swap(vNext[0], vNext[i]);
1918 for (int i = 0; i < vNext.size(); i++)
1919 vStack.push_back(make_pair(nCol+i, vNext[i]));
1932 //////////////////////////////////////////////////////////////////////////////
1937 map<uint256, CAlert> mapAlerts;
1938 CCriticalSection cs_mapAlerts;
1940 string GetWarnings(string strFor)
1943 string strStatusBar;
1945 if (GetBoolArg("-testsafemode"))
1948 // Misc warnings like out of disk space and clock is wrong
1949 if (strMiscWarning != "")
1952 strStatusBar = strMiscWarning;
1955 // Longer invalid proof-of-work chain
1956 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
1959 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1963 CRITICAL_BLOCK(cs_mapAlerts)
1965 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1967 const CAlert& alert = item.second;
1968 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1970 nPriority = alert.nPriority;
1971 strStatusBar = alert.strStatusBar;
1976 if (strFor == "statusbar")
1977 return strStatusBar;
1978 else if (strFor == "rpc")
1980 assert(!"GetWarnings() : invalid parameter");
1984 bool CAlert::ProcessAlert()
1986 if (!CheckSignature())
1991 CRITICAL_BLOCK(cs_mapAlerts)
1993 // Cancel previous alerts
1994 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1996 const CAlert& alert = (*mi).second;
1999 printf("cancelling alert %d\n", alert.nID);
2000 mapAlerts.erase(mi++);
2002 else if (!alert.IsInEffect())
2004 printf("expiring alert %d\n", alert.nID);
2005 mapAlerts.erase(mi++);
2011 // Check if this alert has been cancelled
2012 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2014 const CAlert& alert = item.second;
2015 if (alert.Cancels(*this))
2017 printf("alert already cancelled by %d\n", alert.nID);
2023 mapAlerts.insert(make_pair(GetHash(), *this));
2026 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2038 //////////////////////////////////////////////////////////////////////////////
2044 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2048 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2049 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2051 // Don't know what it is, just say we already got one
2058 // The message start string is designed to be unlikely to occur in normal data.
2059 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2060 // a large 4-byte int at any alignment.
2061 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2064 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2066 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2067 RandAddSeedPerfmon();
2069 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2070 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2072 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2074 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2082 if (strCommand == "version")
2084 // Each connection can only send one version message
2085 if (pfrom->nVersion != 0)
2087 pfrom->Misbehaving(1);
2095 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2096 if (pfrom->nVersion == 10300)
2097 pfrom->nVersion = 300;
2098 if (pfrom->nVersion >= 106 && !vRecv.empty())
2099 vRecv >> addrFrom >> nNonce;
2100 if (pfrom->nVersion >= 106 && !vRecv.empty())
2101 vRecv >> pfrom->strSubVer;
2102 if (pfrom->nVersion >= 209 && !vRecv.empty())
2103 vRecv >> pfrom->nStartingHeight;
2105 if (pfrom->nVersion == 0)
2108 // Disconnect if we connected to ourself
2109 if (nNonce == nLocalHostNonce && nNonce > 1)
2111 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2112 pfrom->fDisconnect = true;
2116 // ppcoin: record my external IP reported by peer
2117 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
2118 addrSeenByPeer = addrMe;
2120 // Be shy and don't send version until we hear
2121 if (pfrom->fInbound)
2122 pfrom->PushVersion();
2124 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2126 AddTimeData(pfrom->addr.ip, nTime);
2129 if (pfrom->nVersion >= 209)
2130 pfrom->PushMessage("verack");
2131 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2132 if (pfrom->nVersion < 209)
2133 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2135 if (!pfrom->fInbound)
2137 // Advertise our address
2138 if (addrLocalHost.IsRoutable() && !fUseProxy)
2140 CAddress addr(addrLocalHost);
2141 addr.nTime = GetAdjustedTime();
2142 pfrom->PushAddress(addr);
2145 // Get recent addresses
2146 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2148 pfrom->PushMessage("getaddr");
2149 pfrom->fGetAddr = true;
2153 // Ask the first connected node for block updates
2154 static int nAskedForBlocks;
2155 if (!pfrom->fClient &&
2156 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
2157 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2160 pfrom->PushGetBlocks(pindexBest, uint256(0));
2164 CRITICAL_BLOCK(cs_mapAlerts)
2165 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2166 item.second.RelayTo(pfrom);
2168 // ppcoin: relay sync-checkpoint
2169 CRITICAL_BLOCK(Checkpoints::cs_hashSyncCheckpoint)
2170 if (!Checkpoints::checkpointMessage.IsNull())
2171 Checkpoints::checkpointMessage.RelayTo(pfrom);
2173 pfrom->fSuccessfullyConnected = true;
2175 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2177 cPeerBlockCounts.input(pfrom->nStartingHeight);
2181 else if (pfrom->nVersion == 0)
2183 // Must have a version message before anything else
2184 pfrom->Misbehaving(1);
2189 else if (strCommand == "verack")
2191 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2195 else if (strCommand == "addr")
2197 vector<CAddress> vAddr;
2200 // Don't want addr from older versions unless seeding
2201 if (pfrom->nVersion < 209)
2203 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2205 if (vAddr.size() > 1000)
2207 pfrom->Misbehaving(20);
2208 return error("message addr size() = %d", vAddr.size());
2211 // Store the new addresses
2214 int64 nNow = GetAdjustedTime();
2215 int64 nSince = nNow - 10 * 60;
2216 BOOST_FOREACH(CAddress& addr, vAddr)
2220 // ignore IPv6 for now, since it isn't implemented anyway
2223 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2224 addr.nTime = nNow - 5 * 24 * 60 * 60;
2225 AddAddress(addr, 2 * 60 * 60, &addrDB);
2226 pfrom->AddAddressKnown(addr);
2227 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2229 // Relay to a limited number of other nodes
2230 CRITICAL_BLOCK(cs_vNodes)
2232 // Use deterministic randomness to send to the same nodes for 24 hours
2233 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2234 static uint256 hashSalt;
2236 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2237 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2238 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2239 multimap<uint256, CNode*> mapMix;
2240 BOOST_FOREACH(CNode* pnode, vNodes)
2242 if (pnode->nVersion < 31402)
2244 unsigned int nPointer;
2245 memcpy(&nPointer, &pnode, sizeof(nPointer));
2246 uint256 hashKey = hashRand ^ nPointer;
2247 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2248 mapMix.insert(make_pair(hashKey, pnode));
2250 int nRelayNodes = 2;
2251 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2252 ((*mi).second)->PushAddress(addr);
2256 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
2257 if (vAddr.size() < 1000)
2258 pfrom->fGetAddr = false;
2262 else if (strCommand == "inv")
2266 if (vInv.size() > 50000)
2268 pfrom->Misbehaving(20);
2269 return error("message inv size() = %d", vInv.size());
2273 BOOST_FOREACH(const CInv& inv, vInv)
2277 pfrom->AddInventoryKnown(inv);
2279 bool fAlreadyHave = AlreadyHave(txdb, inv);
2281 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2285 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2286 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2288 // Track requests for our stuff
2289 Inventory(inv.hash);
2294 else if (strCommand == "getdata")
2298 if (vInv.size() > 50000)
2300 pfrom->Misbehaving(20);
2301 return error("message getdata size() = %d", vInv.size());
2304 BOOST_FOREACH(const CInv& inv, vInv)
2308 printf("received getdata for: %s\n", inv.ToString().c_str());
2310 if (inv.type == MSG_BLOCK)
2312 // Send block from disk
2313 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2314 if (mi != mapBlockIndex.end())
2317 block.ReadFromDisk((*mi).second);
2318 pfrom->PushMessage("block", block);
2320 // Trigger them to send a getblocks request for the next batch of inventory
2321 if (inv.hash == pfrom->hashContinue)
2323 // Bypass PushInventory, this must send even if redundant,
2324 // and we want it right after the last block so they don't
2325 // wait for other stuff first.
2327 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2328 pfrom->PushMessage("inv", vInv);
2329 pfrom->hashContinue = 0;
2333 else if (inv.IsKnownType())
2335 // Send stream from relay memory
2336 CRITICAL_BLOCK(cs_mapRelay)
2338 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2339 if (mi != mapRelay.end())
2340 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2344 // Track requests for our stuff
2345 Inventory(inv.hash);
2350 else if (strCommand == "getblocks")
2352 CBlockLocator locator;
2354 vRecv >> locator >> hashStop;
2356 // Find the last block the caller has in the main chain
2357 CBlockIndex* pindex = locator.GetBlockIndex();
2359 // Send the rest of the chain
2361 pindex = pindex->pnext;
2362 int nLimit = 500 + locator.GetDistanceBack();
2363 unsigned int nBytes = 0;
2364 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2365 for (; pindex; pindex = pindex->pnext)
2367 if (pindex->GetBlockHash() == hashStop)
2369 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2372 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2374 block.ReadFromDisk(pindex, true);
2375 nBytes += block.GetSerializeSize(SER_NETWORK);
2376 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2378 // When this block is requested, we'll send an inv that'll make them
2379 // getblocks the next batch of inventory.
2380 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2381 pfrom->hashContinue = pindex->GetBlockHash();
2388 else if (strCommand == "getheaders")
2390 CBlockLocator locator;
2392 vRecv >> locator >> hashStop;
2394 CBlockIndex* pindex = NULL;
2395 if (locator.IsNull())
2397 // If locator is null, return the hashStop block
2398 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2399 if (mi == mapBlockIndex.end())
2401 pindex = (*mi).second;
2405 // Find the last block the caller has in the main chain
2406 pindex = locator.GetBlockIndex();
2408 pindex = pindex->pnext;
2411 vector<CBlock> vHeaders;
2412 int nLimit = 2000 + locator.GetDistanceBack();
2413 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2414 for (; pindex; pindex = pindex->pnext)
2416 vHeaders.push_back(pindex->GetBlockHeader());
2417 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2420 pfrom->PushMessage("headers", vHeaders);
2424 else if (strCommand == "tx")
2426 vector<uint256> vWorkQueue;
2427 CDataStream vMsg(vRecv);
2431 CInv inv(MSG_TX, tx.GetHash());
2432 pfrom->AddInventoryKnown(inv);
2434 bool fMissingInputs = false;
2435 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2437 SyncWithWallets(tx, NULL, true);
2438 RelayMessage(inv, vMsg);
2439 mapAlreadyAskedFor.erase(inv);
2440 vWorkQueue.push_back(inv.hash);
2442 // Recursively process any orphan transactions that depended on this one
2443 for (int i = 0; i < vWorkQueue.size(); i++)
2445 uint256 hashPrev = vWorkQueue[i];
2446 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2447 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2450 const CDataStream& vMsg = *((*mi).second);
2452 CDataStream(vMsg) >> tx;
2453 CInv inv(MSG_TX, tx.GetHash());
2455 if (tx.AcceptToMemoryPool(true))
2457 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2458 SyncWithWallets(tx, NULL, true);
2459 RelayMessage(inv, vMsg);
2460 mapAlreadyAskedFor.erase(inv);
2461 vWorkQueue.push_back(inv.hash);
2466 BOOST_FOREACH(uint256 hash, vWorkQueue)
2467 EraseOrphanTx(hash);
2469 else if (fMissingInputs)
2471 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2474 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2478 else if (strCommand == "block")
2483 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2486 CInv inv(MSG_BLOCK, block.GetHash());
2487 pfrom->AddInventoryKnown(inv);
2489 if (ProcessBlock(pfrom, &block))
2490 mapAlreadyAskedFor.erase(inv);
2491 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2495 else if (strCommand == "getaddr")
2497 // Nodes rebroadcast an addr every 24 hours
2498 pfrom->vAddrToSend.clear();
2499 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2500 CRITICAL_BLOCK(cs_mapAddresses)
2502 unsigned int nCount = 0;
2503 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2505 const CAddress& addr = item.second;
2506 if (addr.nTime > nSince)
2509 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2511 const CAddress& addr = item.second;
2512 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2513 pfrom->PushAddress(addr);
2519 else if (strCommand == "checkorder")
2524 if (!GetBoolArg("-allowreceivebyip"))
2526 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2533 /// we have a chance to check the order here
2535 // Keep giving the same key to the same ip until they use it
2536 if (!mapReuseKey.count(pfrom->addr.ip))
2537 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2539 // Send back approval of order and pubkey to use
2540 CScript scriptPubKey;
2541 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2542 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2546 else if (strCommand == "reply")
2551 CRequestTracker tracker;
2552 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2554 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2555 if (mi != pfrom->mapRequests.end())
2557 tracker = (*mi).second;
2558 pfrom->mapRequests.erase(mi);
2561 if (!tracker.IsNull())
2562 tracker.fn(tracker.param1, vRecv);
2566 else if (strCommand == "ping")
2571 else if (strCommand == "alert")
2576 if (alert.ProcessAlert())
2579 pfrom->setKnown.insert(alert.GetHash());
2580 CRITICAL_BLOCK(cs_vNodes)
2581 BOOST_FOREACH(CNode* pnode, vNodes)
2582 alert.RelayTo(pnode);
2586 else if (strCommand == "checkpoint")
2588 Checkpoints::CSyncCheckpoint checkpoint;
2589 vRecv >> checkpoint;
2591 if (checkpoint.ProcessSyncCheckpoint(pfrom))
2594 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
2595 CRITICAL_BLOCK(cs_vNodes)
2596 BOOST_FOREACH(CNode* pnode, vNodes)
2597 checkpoint.RelayTo(pnode);
2603 // Ignore unknown commands for extensibility
2607 // Update the last seen time for this node's address
2608 if (pfrom->fNetworkNode)
2609 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2610 AddressCurrentlyConnected(pfrom->addr);
2616 bool ProcessMessages(CNode* pfrom)
2618 CDataStream& vRecv = pfrom->vRecv;
2622 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2626 // (4) message start
2635 // Scan for message start
2636 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2637 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2638 if (vRecv.end() - pstart < nHeaderSize)
2640 if (vRecv.size() > nHeaderSize)
2642 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2643 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2647 if (pstart - vRecv.begin() > 0)
2648 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2649 vRecv.erase(vRecv.begin(), pstart);
2652 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2657 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2660 string strCommand = hdr.GetCommand();
2663 unsigned int nMessageSize = hdr.nMessageSize;
2664 if (nMessageSize > MAX_SIZE)
2666 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2669 if (nMessageSize > vRecv.size())
2671 // Rewind and wait for rest of message
2672 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2677 if (vRecv.GetVersion() >= 209)
2679 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2680 unsigned int nChecksum = 0;
2681 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2682 if (nChecksum != hdr.nChecksum)
2684 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2685 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2690 // Copy message to its own buffer
2691 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2692 vRecv.ignore(nMessageSize);
2698 CRITICAL_BLOCK(cs_main)
2699 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2703 catch (std::ios_base::failure& e)
2705 if (strstr(e.what(), "end of data"))
2707 // Allow exceptions from underlength message on vRecv
2708 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());
2710 else if (strstr(e.what(), "size too large"))
2712 // Allow exceptions from overlong size
2713 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2717 PrintExceptionContinue(&e, "ProcessMessage()");
2720 catch (std::exception& e) {
2721 PrintExceptionContinue(&e, "ProcessMessage()");
2723 PrintExceptionContinue(NULL, "ProcessMessage()");
2727 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2735 bool SendMessages(CNode* pto, bool fSendTrickle)
2737 CRITICAL_BLOCK(cs_main)
2739 // Don't send anything until we get their version message
2740 if (pto->nVersion == 0)
2744 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2745 pto->PushMessage("ping");
2747 // Resend wallet transactions that haven't gotten in a block yet
2748 ResendWalletTransactions();
2750 // Address refresh broadcast
2751 static int64 nLastRebroadcast;
2752 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2754 nLastRebroadcast = GetTime();
2755 CRITICAL_BLOCK(cs_vNodes)
2757 BOOST_FOREACH(CNode* pnode, vNodes)
2759 // Periodically clear setAddrKnown to allow refresh broadcasts
2760 pnode->setAddrKnown.clear();
2762 // Rebroadcast our address
2763 if (addrLocalHost.IsRoutable() && !fUseProxy)
2765 CAddress addr(addrLocalHost);
2766 addr.nTime = GetAdjustedTime();
2767 pnode->PushAddress(addr);
2773 // Clear out old addresses periodically so it's not too much work at once
2774 static int64 nLastClear;
2775 if (nLastClear == 0)
2776 nLastClear = GetTime();
2777 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2779 nLastClear = GetTime();
2780 CRITICAL_BLOCK(cs_mapAddresses)
2783 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2784 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2785 mi != mapAddresses.end();)
2787 const CAddress& addr = (*mi).second;
2788 if (addr.nTime < nSince)
2790 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2792 addrdb.EraseAddress(addr);
2793 mapAddresses.erase(mi++);
2807 vector<CAddress> vAddr;
2808 vAddr.reserve(pto->vAddrToSend.size());
2809 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2811 // returns true if wasn't already contained in the set
2812 if (pto->setAddrKnown.insert(addr).second)
2814 vAddr.push_back(addr);
2815 // receiver rejects addr messages larger than 1000
2816 if (vAddr.size() >= 1000)
2818 pto->PushMessage("addr", vAddr);
2823 pto->vAddrToSend.clear();
2825 pto->PushMessage("addr", vAddr);
2830 // Message: inventory
2833 vector<CInv> vInvWait;
2834 CRITICAL_BLOCK(pto->cs_inventory)
2836 vInv.reserve(pto->vInventoryToSend.size());
2837 vInvWait.reserve(pto->vInventoryToSend.size());
2838 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2840 if (pto->setInventoryKnown.count(inv))
2843 // trickle out tx inv to protect privacy
2844 if (inv.type == MSG_TX && !fSendTrickle)
2846 // 1/4 of tx invs blast to all immediately
2847 static uint256 hashSalt;
2849 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2850 uint256 hashRand = inv.hash ^ hashSalt;
2851 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2852 bool fTrickleWait = ((hashRand & 3) != 0);
2854 // always trickle our own transactions
2858 if (GetTransaction(inv.hash, wtx))
2860 fTrickleWait = true;
2865 vInvWait.push_back(inv);
2870 // returns true if wasn't already contained in the set
2871 if (pto->setInventoryKnown.insert(inv).second)
2873 vInv.push_back(inv);
2874 if (vInv.size() >= 1000)
2876 pto->PushMessage("inv", vInv);
2881 pto->vInventoryToSend = vInvWait;
2884 pto->PushMessage("inv", vInv);
2890 vector<CInv> vGetData;
2891 int64 nNow = GetTime() * 1000000;
2893 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2895 const CInv& inv = (*pto->mapAskFor.begin()).second;
2896 if (!AlreadyHave(txdb, inv))
2898 printf("sending getdata: %s\n", inv.ToString().c_str());
2899 vGetData.push_back(inv);
2900 if (vGetData.size() >= 1000)
2902 pto->PushMessage("getdata", vGetData);
2906 mapAlreadyAskedFor[inv] = nNow;
2907 pto->mapAskFor.erase(pto->mapAskFor.begin());
2909 if (!vGetData.empty())
2910 pto->PushMessage("getdata", vGetData);
2929 //////////////////////////////////////////////////////////////////////////////
2934 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2936 unsigned char* pdata = (unsigned char*)pbuffer;
2937 unsigned int blocks = 1 + ((len + 8) / 64);
2938 unsigned char* pend = pdata + 64 * blocks;
2939 memset(pdata + len, 0, 64 * blocks - len);
2941 unsigned int bits = len * 8;
2942 pend[-1] = (bits >> 0) & 0xff;
2943 pend[-2] = (bits >> 8) & 0xff;
2944 pend[-3] = (bits >> 16) & 0xff;
2945 pend[-4] = (bits >> 24) & 0xff;
2949 static const unsigned int pSHA256InitState[8] =
2950 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2952 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2955 unsigned char data[64];
2959 for (int i = 0; i < 16; i++)
2960 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2962 for (int i = 0; i < 8; i++)
2963 ctx.h[i] = ((uint32_t*)pinit)[i];
2965 SHA256_Update(&ctx, data, sizeof(data));
2966 for (int i = 0; i < 8; i++)
2967 ((uint32_t*)pstate)[i] = ctx.h[i];
2971 // ScanHash scans nonces looking for a hash with at least some zero bits.
2972 // It operates on big endian data. Caller does the byte reversing.
2973 // All input buffers are 16-byte aligned. nNonce is usually preserved
2974 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2975 // the block is rebuilt and nNonce starts over at zero.
2977 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2979 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2983 // Hash pdata using pmidstate as the starting state into
2984 // preformatted buffer phash1, then hash phash1 into phash
2986 SHA256Transform(phash1, pdata, pmidstate);
2987 SHA256Transform(phash, phash1, pSHA256InitState);
2989 // Return the nonce if the hash has at least some zero bits,
2990 // caller will check if it has enough to reach the target
2991 if (((unsigned short*)phash)[14] == 0)
2994 // If nothing found after trying for a while, return -1
2995 if ((nNonce & 0xffff) == 0)
2997 nHashesDone = 0xffff+1;
3003 // Some explaining would be appreciated
3008 set<uint256> setDependsOn;
3011 COrphan(CTransaction* ptxIn)
3019 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3020 BOOST_FOREACH(uint256 hash, setDependsOn)
3021 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3026 CBlock* CreateNewBlock(CWallet* pwallet)
3028 CReserveKey reservekey(pwallet);
3031 auto_ptr<CBlock> pblock(new CBlock());
3035 // Create coinbase tx
3037 txNew.vin.resize(1);
3038 txNew.vin[0].prevout.SetNull();
3039 txNew.vout.resize(1);
3040 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3042 // Add our coinbase tx as first transaction
3043 pblock->vtx.push_back(txNew);
3045 // ppcoin: if coinstake available add coinstake tx
3046 static unsigned int nLastCoinStakeCheckTime = GetAdjustedTime() - nMaxClockDrift; // only initialized at startup
3047 CBlockIndex* pindexPrev = pindexBest;
3048 while (nLastCoinStakeCheckTime < GetAdjustedTime())
3050 pindexPrev = pindexBest; // get best block again to avoid getting stale
3051 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
3052 static CCriticalSection cs;
3053 CTransaction txCoinStake;
3056 nLastCoinStakeCheckTime++;
3057 txCoinStake.nTime = nLastCoinStakeCheckTime;
3059 if (pwallet->CreateCoinStake(pblock->nBits, txCoinStake))
3061 pblock->vtx.push_back(txCoinStake);
3062 pblock->vtx[0].vout[0].SetEmpty();
3067 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
3069 // Collect memory pool transactions into the block
3071 CRITICAL_BLOCK(cs_main)
3072 CRITICAL_BLOCK(cs_mapTransactions)
3076 // Priority order to process transactions
3077 list<COrphan> vOrphan; // list memory doesn't move
3078 map<uint256, vector<COrphan*> > mapDependers;
3079 multimap<double, CTransaction*> mapPriority;
3080 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3082 CTransaction& tx = (*mi).second;
3083 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
3086 COrphan* porphan = NULL;
3087 double dPriority = 0;
3088 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3090 // Read prev transaction
3091 CTransaction txPrev;
3093 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3095 // Has to wait for dependencies
3098 // Use list for automatic deletion
3099 vOrphan.push_back(COrphan(&tx));
3100 porphan = &vOrphan.back();
3102 mapDependers[txin.prevout.hash].push_back(porphan);
3103 porphan->setDependsOn.insert(txin.prevout.hash);
3106 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3108 // Read block header
3109 int nConf = txindex.GetDepthInMainChain();
3111 dPriority += (double)nValueIn * nConf;
3113 if (fDebug && GetBoolArg("-printpriority"))
3114 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3117 // Priority is sum(valuein * age) / txsize
3118 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3121 porphan->dPriority = dPriority;
3123 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3125 if (fDebug && GetBoolArg("-printpriority"))
3127 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3134 // Collect transactions into block
3135 map<uint256, CTxIndex> mapTestPool;
3136 uint64 nBlockSize = 1000;
3137 int nBlockSigOps = 100;
3138 while (!mapPriority.empty())
3140 // Take highest priority transaction off priority queue
3141 double dPriority = -(*mapPriority.begin()).first;
3142 CTransaction& tx = *(*mapPriority.begin()).second;
3143 mapPriority.erase(mapPriority.begin());
3146 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3147 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3149 int nTxSigOps = tx.GetSigOpCount();
3150 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3154 if (tx.nTime > GetAdjustedTime())
3157 // ppcoin: simplify transaction fee - allow free = false
3158 int64 nMinFee = tx.GetMinFee(nBlockSize, false, true);
3160 // Connecting shouldn't fail due to dependency on other memory pool transactions
3161 // because we're already processing them in order of dependency
3162 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3163 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3165 swap(mapTestPool, mapTestPoolTmp);
3168 pblock->vtx.push_back(tx);
3169 nBlockSize += nTxSize;
3170 nBlockSigOps += nTxSigOps;
3172 // Add transactions that depend on this one to the priority queue
3173 uint256 hash = tx.GetHash();
3174 if (mapDependers.count(hash))
3176 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3178 if (!porphan->setDependsOn.empty())
3180 porphan->setDependsOn.erase(hash);
3181 if (porphan->setDependsOn.empty())
3182 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3188 if (pblock->IsProofOfWork())
3189 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
3192 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3193 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3194 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3195 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
3196 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
3199 return pblock.release();
3203 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3205 // Update nExtraNonce
3206 static uint256 hashPrevBlock;
3207 if (hashPrevBlock != pblock->hashPrevBlock)
3210 hashPrevBlock = pblock->hashPrevBlock;
3213 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3214 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3218 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3221 // Prebuild hash buffers
3228 uint256 hashPrevBlock;
3229 uint256 hashMerkleRoot;
3232 unsigned int nNonce;
3235 unsigned char pchPadding0[64];
3237 unsigned char pchPadding1[64];
3240 memset(&tmp, 0, sizeof(tmp));
3242 tmp.block.nVersion = pblock->nVersion;
3243 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3244 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3245 tmp.block.nTime = pblock->nTime;
3246 tmp.block.nBits = pblock->nBits;
3247 tmp.block.nNonce = pblock->nNonce;
3249 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3250 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3252 // Byte swap all the input buffer
3253 for (int i = 0; i < sizeof(tmp)/4; i++)
3254 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3256 // Precalc the first half of the first hash, which stays constant
3257 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3259 memcpy(pdata, &tmp.block, 128);
3260 memcpy(phash1, &tmp.hash1, 64);
3264 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3266 uint256 hash = pblock->GetHash();
3267 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3269 if (hash > hashTarget && pblock->IsProofOfWork())
3270 return error("BitcoinMiner : proof-of-work not meeting target");
3273 printf("BitcoinMiner:\n");
3274 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3276 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3277 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3280 CRITICAL_BLOCK(cs_main)
3282 if (pblock->hashPrevBlock != hashBestChain)
3283 return error("BitcoinMiner : generated block is stale");
3285 // Remove key from key pool
3286 reservekey.KeepKey();
3288 // Track how many getdata requests this block gets
3289 CRITICAL_BLOCK(wallet.cs_wallet)
3290 wallet.mapRequestCount[pblock->GetHash()] = 0;
3292 // Process this block the same as if we had received it from another node
3293 if (!ProcessBlock(NULL, pblock))
3294 return error("BitcoinMiner : ProcessBlock, block not accepted");
3300 void static ThreadBitcoinMiner(void* parg);
3302 void static BitcoinMiner(CWallet *pwallet)
3304 printf("BitcoinMiner started\n");
3305 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3307 // Each thread has its own key and counter
3308 CReserveKey reservekey(pwallet);
3309 unsigned int nExtraNonce = 0;
3311 while (fGenerateBitcoins)
3313 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3317 while (vNodes.empty() || IsInitialBlockDownload())
3322 if (!fGenerateBitcoins)
3330 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3331 CBlockIndex* pindexPrev = pindexBest;
3333 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet));
3337 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3339 // ppcoin: if proof-of-stake block found then process block
3340 if (pblock->IsProofOfStake())
3342 // should be able to sign block - assert here for now
3343 assert(pblock->SignBlock(*pwalletMain));
3344 printf("BitcoinMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
3345 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3346 CheckWork(pblock.get(), *pwalletMain, reservekey);
3347 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3351 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3355 // Prebuild hash buffers
3357 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3358 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3359 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3361 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3363 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3364 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3370 int64 nStart = GetTime();
3371 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3373 uint256& hash = *alignup<16>(hashbuf);
3376 unsigned int nHashesDone = 0;
3377 unsigned int nNonceFound;
3380 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3381 (char*)&hash, nHashesDone);
3383 // Check if something found
3384 if (nNonceFound != -1)
3386 for (int i = 0; i < sizeof(hash)/4; i++)
3387 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3389 if (hash <= hashTarget)
3392 pblock->nNonce = ByteReverse(nNonceFound);
3393 assert(hash == pblock->GetHash());
3394 // should be able to sign block - assert here for now
3395 assert(pblock->SignBlock(*pwalletMain));
3397 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3398 CheckWork(pblock.get(), *pwalletMain, reservekey);
3399 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3405 static int64 nHashCounter;
3406 if (nHPSTimerStart == 0)
3408 nHPSTimerStart = GetTimeMillis();
3412 nHashCounter += nHashesDone;
3413 if (GetTimeMillis() - nHPSTimerStart > 4000)
3415 static CCriticalSection cs;
3418 if (GetTimeMillis() - nHPSTimerStart > 4000)
3420 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3421 nHPSTimerStart = GetTimeMillis();
3423 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3424 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3425 static int64 nLogTime;
3426 if (GetTime() - nLogTime > 30 * 60)
3428 nLogTime = GetTime();
3429 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3430 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3436 // Check for stop or if block needs to be rebuilt
3439 if (!fGenerateBitcoins)
3441 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3445 if (nBlockNonce >= 0xffff0000)
3447 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3449 if (pindexPrev != pindexBest)
3452 // Update nTime every few seconds
3453 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3454 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
3455 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
3456 nBlockTime = ByteReverse(pblock->nTime);
3457 if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
3458 break; // need to update coinbase timestamp
3463 void static ThreadBitcoinMiner(void* parg)
3465 CWallet* pwallet = (CWallet*)parg;
3468 vnThreadsRunning[3]++;
3469 BitcoinMiner(pwallet);
3470 vnThreadsRunning[3]--;
3472 catch (std::exception& e) {
3473 vnThreadsRunning[3]--;
3474 PrintException(&e, "ThreadBitcoinMiner()");
3476 vnThreadsRunning[3]--;
3477 PrintException(NULL, "ThreadBitcoinMiner()");
3479 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3481 if (vnThreadsRunning[3] == 0)
3483 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3487 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3489 if (fGenerateBitcoins != fGenerate)
3491 fGenerateBitcoins = fGenerate;
3492 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3495 if (fGenerateBitcoins)
3497 int nProcessors = boost::thread::hardware_concurrency();
3498 printf("%d processors\n", nProcessors);
3499 if (nProcessors < 1)
3501 if (fLimitProcessors && nProcessors > nLimitProcessors)
3502 nProcessors = nLimitProcessors;
3503 int nAddThreads = nProcessors - vnThreadsRunning[3];
3504 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3505 for (int i = 0; i < nAddThreads; i++)
3507 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3508 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");