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 uint256 hashGenesisBlock("0x000000006d52486334316794cc38ffeb7ebf35a7ebd661fd39f5f46b0d001575");
33 static CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
34 const int nInitialBlockThreshold = 120; // Regard blocks up until N-threshold as "initial download"
35 CBlockIndex* pindexGenesisBlock = NULL;
37 uint64 nBestChainTrust = 0;
38 uint64 nBestInvalidTrust = 0;
39 uint256 hashBestChain = 0;
40 CBlockIndex* pindexBest = NULL;
41 int64 nTimeBestReceived = 0;
43 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
45 map<uint256, CBlock*> mapOrphanBlocks;
46 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
48 map<uint256, CDataStream*> mapOrphanTransactions;
49 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
56 int fGenerateBitcoins = false;
57 int64 nTransactionFee = MIN_TX_FEE;
58 int fLimitProcessors = false;
59 int nLimitProcessors = 1;
60 int fMinimizeToTray = true;
61 int fMinimizeOnClose = true;
67 int64 nBalanceReserve = 0;
69 //////////////////////////////////////////////////////////////////////////////
71 // dispatching functions
74 // These functions dispatch to one or all registered wallets
77 void RegisterWallet(CWallet* pwalletIn)
79 CRITICAL_BLOCK(cs_setpwalletRegistered)
81 setpwalletRegistered.insert(pwalletIn);
85 void UnregisterWallet(CWallet* pwalletIn)
87 CRITICAL_BLOCK(cs_setpwalletRegistered)
89 setpwalletRegistered.erase(pwalletIn);
93 // check whether the passed transaction is from us
94 bool static IsFromMe(CTransaction& tx)
96 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
97 if (pwallet->IsFromMe(tx))
102 // get the wallet transaction with the given hash (if it exists)
103 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
105 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
106 if (pwallet->GetTransaction(hashTx,wtx))
111 // erases transaction with the given hash from all wallets
112 void static EraseFromWallets(uint256 hash)
114 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
115 pwallet->EraseFromWallet(hash);
118 // make sure all wallets know about the given transaction, in the given block
119 void static SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true)
123 // ppcoin: wallets need to refund inputs when disconnecting coinstake
124 if (tx.IsCoinStake())
125 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126 if (pwallet->IsFromMe(tx))
127 pwallet->DisableTransaction(tx);
131 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
132 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
135 // notify wallets about a new best chain
136 void static SetBestChain(const CBlockLocator& loc)
138 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
139 pwallet->SetBestChain(loc);
142 // notify wallets about an updated transaction
143 void static UpdatedTransaction(const uint256& hashTx)
145 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
146 pwallet->UpdatedTransaction(hashTx);
150 void static PrintWallets(const CBlock& block)
152 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
153 pwallet->PrintWallet(block);
156 // notify wallets about an incoming inventory (for request counts)
157 void static Inventory(const uint256& hash)
159 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
160 pwallet->Inventory(hash);
163 // ask wallets to resend their transactions
164 void static ResendWalletTransactions()
166 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
167 pwallet->ResendWalletTransactions();
176 //////////////////////////////////////////////////////////////////////////////
178 // mapOrphanTransactions
181 void static AddOrphanTx(const CDataStream& vMsg)
184 CDataStream(vMsg) >> tx;
185 uint256 hash = tx.GetHash();
186 if (mapOrphanTransactions.count(hash))
188 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
189 BOOST_FOREACH(const CTxIn& txin, tx.vin)
190 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
193 void static EraseOrphanTx(uint256 hash)
195 if (!mapOrphanTransactions.count(hash))
197 const CDataStream* pvMsg = mapOrphanTransactions[hash];
199 CDataStream(*pvMsg) >> tx;
200 BOOST_FOREACH(const CTxIn& txin, tx.vin)
202 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
203 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
205 if ((*mi).second == pvMsg)
206 mapOrphanTransactionsByPrev.erase(mi++);
212 mapOrphanTransactions.erase(hash);
222 //////////////////////////////////////////////////////////////////////////////
224 // CTransaction and CTxIndex
227 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
230 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
232 if (!ReadFromDisk(txindexRet.pos))
234 if (prevout.n >= vout.size())
242 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
245 return ReadFromDisk(txdb, prevout, txindex);
248 bool CTransaction::ReadFromDisk(COutPoint prevout)
252 return ReadFromDisk(txdb, prevout, txindex);
257 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
269 // Load the block this tx is in
271 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
273 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
278 // Update the tx's hashBlock
279 hashBlock = pblock->GetHash();
281 // Locate the transaction
282 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
283 if (pblock->vtx[nIndex] == *(CTransaction*)this)
285 if (nIndex == pblock->vtx.size())
287 vMerkleBranch.clear();
289 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
293 // Fill in merkle branch
294 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
297 // Is the tx in a block that's in the main chain
298 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
299 if (mi == mapBlockIndex.end())
301 CBlockIndex* pindex = (*mi).second;
302 if (!pindex || !pindex->IsInMainChain())
305 return pindexBest->nHeight - pindex->nHeight + 1;
314 bool CTransaction::CheckTransaction() const
316 // Basic checks that don't depend on any context
318 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
320 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
322 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
323 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
325 // Check for negative or overflow output values
327 for (int i = (IsCoinStake()? 1 : 0); i < vout.size(); i++)
329 const CTxOut& txout = vout[i];
330 if (txout.nValue < 0)
331 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
332 if (txout.nValue > MAX_MONEY)
333 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
334 nValueOut += txout.nValue;
335 if (!MoneyRange(nValueOut))
336 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
339 // Check for duplicate inputs
340 set<COutPoint> vInOutPoints;
341 BOOST_FOREACH(const CTxIn& txin, vin)
343 if (vInOutPoints.count(txin.prevout))
345 vInOutPoints.insert(txin.prevout);
350 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
351 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
355 BOOST_FOREACH(const CTxIn& txin, vin)
356 if (txin.prevout.IsNull())
357 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
363 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
366 *pfMissingInputs = false;
368 if (!CheckTransaction())
369 return error("AcceptToMemoryPool() : CheckTransaction failed");
371 // Coinbase is only valid in a block, not as a loose transaction
373 return DoS(100, error("AcceptToMemoryPool() : coinbase as individual tx"));
374 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
376 return DoS(100, error("AcceptToMemoryPool() : coinstake as individual tx"));
378 // To help v0.1.5 clients who would see it as a negative number
379 if ((int64)nLockTime > INT_MAX)
380 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
383 unsigned int nSize = ::GetSerializeSize(*this, SER_NETWORK);
384 // Checking ECDSA signatures is a CPU bottleneck, so to avoid denial-of-service
385 // attacks disallow transactions with more than one SigOp per 34 bytes.
386 // 34 bytes because a TxOut is:
387 // 20-byte address + 8 byte bitcoin amount + 5 bytes of ops + 1 byte script length
388 if (GetSigOpCount() > nSize / 34 || nSize < 100)
389 return error("AcceptToMemoryPool() : transaction with out-of-bounds SigOpCount");
391 // Rather not work on nonstandard transactions (unless -testnet)
392 if (!fTestNet && !IsStandard())
393 return error("AcceptToMemoryPool() : nonstandard transaction type");
395 // Do we already have it?
396 uint256 hash = GetHash();
397 CRITICAL_BLOCK(cs_mapTransactions)
398 if (mapTransactions.count(hash))
401 if (txdb.ContainsTx(hash))
404 // Check for conflicts with in-memory transactions
405 CTransaction* ptxOld = NULL;
406 for (int i = 0; i < vin.size(); i++)
408 COutPoint outpoint = vin[i].prevout;
409 if (mapNextTx.count(outpoint))
411 // Disable replacement feature for now
414 // Allow replacing with a newer version of the same transaction
417 ptxOld = mapNextTx[outpoint].ptx;
418 if (ptxOld->IsFinal())
420 if (!IsNewerThan(*ptxOld))
422 for (int i = 0; i < vin.size(); i++)
424 COutPoint outpoint = vin[i].prevout;
425 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
434 // Check against previous transactions
435 map<uint256, CTxIndex> mapUnused;
437 if (!ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
440 *pfMissingInputs = true;
441 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
444 // Don't accept it if it can't get into a block
445 if (nFees < GetMinFee(1000, false, true))
446 return error("AcceptToMemoryPool() : not enough fees");
448 // Continuously rate-limit free transactions
449 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
450 // be annoying or make other's transactions take longer to confirm.
451 if (nFees < MIN_RELAY_TX_FEE)
453 static CCriticalSection cs;
454 static double dFreeCount;
455 static int64 nLastTime;
456 int64 nNow = GetTime();
460 // Use an exponentially decaying ~10-minute window:
461 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
463 // -limitfreerelay unit is thousand-bytes-per-minute
464 // At default rate it would take over a month to fill 1GB
465 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(*this))
466 return error("AcceptToMemoryPool() : free transaction rejected by rate limiter");
468 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
474 // Store transaction in memory
475 CRITICAL_BLOCK(cs_mapTransactions)
479 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
480 ptxOld->RemoveFromMemoryPool();
482 AddToMemoryPoolUnchecked();
485 ///// are we sure this is ok when loading transactions or restoring block txes
486 // If updated, erase old tx from wallet
488 EraseFromWallets(ptxOld->GetHash());
490 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
494 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
497 return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
500 bool CTransaction::AddToMemoryPoolUnchecked()
502 // Add to memory pool without checking anything. Don't call this directly,
503 // call AcceptToMemoryPool to properly check the transaction first.
504 CRITICAL_BLOCK(cs_mapTransactions)
506 uint256 hash = GetHash();
507 mapTransactions[hash] = *this;
508 for (int i = 0; i < vin.size(); i++)
509 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
510 nTransactionsUpdated++;
516 bool CTransaction::RemoveFromMemoryPool()
518 // Remove transaction from memory pool
519 CRITICAL_BLOCK(cs_mapTransactions)
521 BOOST_FOREACH(const CTxIn& txin, vin)
522 mapNextTx.erase(txin.prevout);
523 mapTransactions.erase(GetHash());
524 nTransactionsUpdated++;
534 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
536 if (hashBlock == 0 || nIndex == -1)
539 // Find the block it claims to be in
540 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
541 if (mi == mapBlockIndex.end())
543 CBlockIndex* pindex = (*mi).second;
544 if (!pindex || !pindex->IsInMainChain())
547 // Make sure the merkle branch connects to this block
548 if (!fMerkleVerified)
550 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
552 fMerkleVerified = true;
555 nHeightRet = pindex->nHeight;
556 return pindexBest->nHeight - pindex->nHeight + 1;
560 int CMerkleTx::GetBlocksToMaturity() const
562 if (!(IsCoinBase() || IsCoinStake()))
564 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
568 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
572 if (!IsInMainChain() && !ClientConnectInputs())
574 return CTransaction::AcceptToMemoryPool(txdb, false);
578 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
582 bool CMerkleTx::AcceptToMemoryPool()
585 return AcceptToMemoryPool(txdb);
590 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
592 CRITICAL_BLOCK(cs_mapTransactions)
594 // Add previous supporting transactions first
595 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
597 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
599 uint256 hash = tx.GetHash();
600 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
601 tx.AcceptToMemoryPool(txdb, fCheckInputs);
604 return AcceptToMemoryPool(txdb, fCheckInputs);
609 bool CWalletTx::AcceptWalletTransaction()
612 return AcceptWalletTransaction(txdb);
615 int CTxIndex::GetDepthInMainChain() const
619 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
621 // Find the block in the index
622 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
623 if (mi == mapBlockIndex.end())
625 CBlockIndex* pindex = (*mi).second;
626 if (!pindex || !pindex->IsInMainChain())
628 return 1 + nBestHeight - pindex->nHeight;
640 //////////////////////////////////////////////////////////////////////////////
642 // CBlock and CBlockIndex
645 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
647 if (!fReadTransactions)
649 *this = pindex->GetBlockHeader();
652 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
654 if (GetHash() != pindex->GetBlockHash())
655 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
659 uint256 static GetOrphanRoot(const CBlock* pblock)
661 // Work back to the first block in the orphan chain
662 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
663 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
664 return pblock->GetHash();
667 int64 static GetProofOfWorkReward(unsigned int nBits)
669 CBigNum bnSubsidyLimit = 9999 * COIN; // subsidy amount for difficulty 1
671 bnTarget.SetCompact(nBits);
672 CBigNum bnTargetLimit = bnProofOfWorkLimit;
673 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
675 // ppcoin: subsidy is cut in half every 16x multiply of difficulty
676 // A reasonably continuous curve is used to avoid shock to market
677 // (nSubsidyLimit / nSubsidy) ** 4 == bnProofOfWorkLimit / bnTarget
678 CBigNum bnLowerBound = CENT;
679 CBigNum bnUpperBound = bnSubsidyLimit;
680 while (bnLowerBound + CENT <= bnUpperBound)
682 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
683 if (fDebug && GetBoolArg("-printcreation"))
684 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
685 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
686 bnUpperBound = bnMidValue;
688 bnLowerBound = bnMidValue;
691 int64 nSubsidy = bnUpperBound.getuint64();
692 nSubsidy = (nSubsidy / CENT) * CENT;
693 if (fDebug && GetBoolArg("-printcreation"))
694 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
699 // ppcoin: miner's coin stake is rewarded based on coin age spent (coin-days)
700 int64 GetProofOfStakeReward(int64 nCoinAge)
702 static int64 nRewardCoinYear = CENT; // creation amount per coin-year
703 int64 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
704 if (fDebug && GetBoolArg("-printcreation"))
705 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nCoinAge);
709 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
710 static const int64 nTargetSpacing = 10 * 60;
711 static const int64 nInterval = nTargetTimespan / nTargetSpacing;
712 static const int64 nMaxClockDrift = 2 * 60 * 60; // 2 hours
715 // minimum amount of work that could possibly be required nTime after
716 // minimum work required was nBase
718 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
721 bnResult.SetCompact(nBase);
722 while (nTime > 0 && bnResult < bnProofOfWorkLimit)
724 // Maximum 400% adjustment...
726 // ... in best-case exactly 4-times-normal target time
727 nTime -= nTargetTimespan*4;
729 if (bnResult > bnProofOfWorkLimit)
730 bnResult = bnProofOfWorkLimit;
731 return bnResult.GetCompact();
734 // ppcoin: find last block index up to pindex
735 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
737 while (pindex && (pindex->IsProofOfStake() != fProofOfStake))
738 pindex = pindex->pprev;
742 unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
744 // Genesis block and first block
745 if (pindexLast == NULL || pindexLast->pprev == NULL)
746 return bnProofOfWorkLimit.GetCompact();
748 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
749 if (pindexPrev == NULL)
750 return bnProofOfWorkLimit.GetCompact();
751 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
752 if (pindexPrevPrev == NULL)
753 return bnProofOfWorkLimit.GetCompact();
754 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
756 // ppcoin: target change every block
757 // ppcoin: retarget with exponential moving toward target spacing
759 bnNew.SetCompact(pindexLast->nBits);
760 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
761 bnNew /= ((nInterval + 1) * nTargetSpacing);
763 if (bnNew > bnProofOfWorkLimit)
764 bnNew = bnProofOfWorkLimit;
766 return bnNew.GetCompact();
769 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
772 bnTarget.SetCompact(nBits);
775 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
776 return error("CheckProofOfWork() : nBits below minimum work");
778 // Check proof of work matches claimed amount
779 if (hash > bnTarget.getuint256())
780 return error("CheckProofOfWork() : hash doesn't match nBits");
785 // Return maximum amount of blocks that other nodes claim to have
786 int GetNumBlocksOfPeers()
788 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
791 bool IsInitialBlockDownload()
793 if (pindexBest == NULL || nBestHeight < (Checkpoints::GetTotalBlocksEstimate()-nInitialBlockThreshold))
795 static int64 nLastUpdate;
796 static CBlockIndex* pindexLastBest;
797 if (pindexBest != pindexLastBest)
799 pindexLastBest = pindexBest;
800 nLastUpdate = GetTime();
802 return (GetTime() - nLastUpdate < 10 &&
803 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
806 void static InvalidChainFound(CBlockIndex* pindexNew)
808 if (pindexNew->nChainTrust > nBestInvalidTrust)
810 nBestInvalidTrust = pindexNew->nChainTrust;
811 CTxDB().WriteBestInvalidTrust(nBestInvalidTrust);
814 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());
815 printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
816 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
817 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
830 bool CTransaction::DisconnectInputs(CTxDB& txdb)
832 // Relinquish previous transactions' spent pointers
835 BOOST_FOREACH(const CTxIn& txin, vin)
837 COutPoint prevout = txin.prevout;
839 // Get prev txindex from disk
841 if (!txdb.ReadTxIndex(prevout.hash, txindex))
842 return error("DisconnectInputs() : ReadTxIndex failed");
844 if (prevout.n >= txindex.vSpent.size())
845 return error("DisconnectInputs() : prevout.n out of range");
847 // Mark outpoint as not spent
848 txindex.vSpent[prevout.n].SetNull();
851 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
852 return error("DisconnectInputs() : UpdateTxIndex failed");
856 // Remove transaction from index
857 if (!txdb.EraseTxIndex(*this))
858 return error("DisconnectInputs() : EraseTxPos failed");
864 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
865 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
867 // Take over previous transactions' spent pointers
868 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
869 // fMiner is true when called from the internal bitcoin miner
870 // ... both are false when called from CTransaction::AcceptToMemoryPool
874 for (int i = 0; i < vin.size(); i++)
876 COutPoint prevout = vin[i].prevout;
881 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
883 // Get txindex from current proposed changes
884 txindex = mapTestPool[prevout.hash];
888 // Read txindex from txdb
889 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
891 if (!fFound && (fBlock || fMiner))
892 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());
896 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
898 // Get prev tx from single transactions in memory
899 CRITICAL_BLOCK(cs_mapTransactions)
901 if (!mapTransactions.count(prevout.hash))
902 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
903 txPrev = mapTransactions[prevout.hash];
906 txindex.vSpent.resize(txPrev.vout.size());
910 // Get prev tx from disk
911 if (!txPrev.ReadFromDisk(txindex.pos))
912 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
915 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
916 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()));
918 // If prev is coinbase/coinstake, check that it's matured
919 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
920 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
921 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
922 return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight);
924 // ppcoin: check transaction timestamp
925 if (txPrev.nTime > nTime)
926 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
928 // Skip ECDSA signature verification when connecting blocks (fBlock=true) during initial download
929 // (before the last blockchain checkpoint). This is safe because block merkle hashes are
930 // still computed and checked, and any change will be caught at the next checkpoint.
931 if (!(fBlock && IsInitialBlockDownload()))
933 if (!VerifySignature(txPrev, *this, i))
934 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
936 // Check for conflicts (double-spend)
937 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
938 // for an attacker to attempt to split the network.
939 if (!txindex.vSpent[prevout.n].IsNull())
940 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());
942 // Check for negative or overflow input values
943 nValueIn += txPrev.vout[prevout.n].nValue;
944 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
945 return DoS(100, error("ConnectInputs() : txin values out of range"));
947 // Mark outpoints as spent
948 txindex.vSpent[prevout.n] = posThisTx;
951 if (fBlock || fMiner)
953 mapTestPool[prevout.hash] = txindex;
959 // ppcoin: coin stake tx earns reward instead of paying fee
961 if (!GetCoinAge(txdb, nCoinAge))
962 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
963 int64 nStakeReward = GetValueOut() - nValueIn;
964 if (nStakeReward > GetProofOfStakeReward(nCoinAge))
965 return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
969 if (nValueIn < GetValueOut())
970 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
972 // Tally transaction fees
973 int64 nTxFee = nValueIn - GetValueOut();
975 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
976 // ppcoin: enforce transaction fees for every block
977 if (nTxFee < nMinFee)
978 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;
980 if (!MoneyRange(nFees))
981 return DoS(100, error("ConnectInputs() : nFees out of range"));
987 // Add transaction to changes
988 mapTestPool[GetHash()] = CTxIndex(posThisTx, vout.size());
992 // Add transaction to test pool
993 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1000 bool CTransaction::ClientConnectInputs()
1005 // Take over previous transactions' spent pointers
1006 CRITICAL_BLOCK(cs_mapTransactions)
1009 for (int i = 0; i < vin.size(); i++)
1011 // Get prev tx from single transactions in memory
1012 COutPoint prevout = vin[i].prevout;
1013 if (!mapTransactions.count(prevout.hash))
1015 CTransaction& txPrev = mapTransactions[prevout.hash];
1017 if (prevout.n >= txPrev.vout.size())
1021 if (!VerifySignature(txPrev, *this, i))
1022 return error("ConnectInputs() : VerifySignature failed");
1024 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1025 ///// this has to go away now that posNext is gone
1026 // // Check for conflicts
1027 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1028 // return error("ConnectInputs() : prev tx already used");
1030 // // Flag outpoints as used
1031 // txPrev.vout[prevout.n].posNext = posThisTx;
1033 nValueIn += txPrev.vout[prevout.n].nValue;
1035 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1036 return error("ClientConnectInputs() : txin values out of range");
1038 if (GetValueOut() > nValueIn)
1048 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1050 // Disconnect in reverse order
1051 for (int i = vtx.size()-1; i >= 0; i--)
1052 if (!vtx[i].DisconnectInputs(txdb))
1055 // Update block index on disk without changing it in memory.
1056 // The memory index structure will be changed after the db commits.
1059 CDiskBlockIndex blockindexPrev(pindex->pprev);
1060 blockindexPrev.hashNext = 0;
1061 if (!txdb.WriteBlockIndex(blockindexPrev))
1062 return error("DisconnectBlock() : WriteBlockIndex failed");
1065 // ppcoin: clean up wallet after disconnecting coinstake
1066 BOOST_FOREACH(CTransaction& tx, vtx)
1067 SyncWithWallets(tx, this, false, false);
1072 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1074 // Check it again in case a previous version let a bad block in
1078 // ppcoin: coin stake tx must meet target protocol
1079 if (IsProofOfStake() && !vtx[1].CheckProofOfStake(txdb, nBits))
1080 return error("ConnectBlock() : Block %s unable to meet hash target for coinstake", GetHash().ToString().c_str());
1082 //// issue here: it doesn't know the version
1083 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1085 map<uint256, CTxIndex> mapQueuedChanges;
1087 BOOST_FOREACH(CTransaction& tx, vtx)
1089 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1090 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1092 if (!tx.ConnectInputs(txdb, mapQueuedChanges, posThisTx, pindex, nFees, true, false, tx.GetMinFee()))
1095 // Write queued txindex changes
1096 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1098 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1099 return error("ConnectBlock() : UpdateTxIndex failed");
1102 // ppcoin: fees are not collected by miners as in bitcoin
1103 // ppcoin: fees are destroyed to compensate the entire network
1104 if (vtx[0].GetValueOut() > GetProofOfWorkReward(nBits))
1106 if (fDebug && GetBoolArg("-printcreation"))
1107 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1109 // Update block index on disk without changing it in memory.
1110 // The memory index structure will be changed after the db commits.
1113 CDiskBlockIndex blockindexPrev(pindex->pprev);
1114 blockindexPrev.hashNext = pindex->GetBlockHash();
1115 if (!txdb.WriteBlockIndex(blockindexPrev))
1116 return error("ConnectBlock() : WriteBlockIndex failed");
1119 // Watch for transactions paying to me
1120 BOOST_FOREACH(CTransaction& tx, vtx)
1121 SyncWithWallets(tx, this, true);
1126 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1128 printf("REORGANIZE\n");
1131 CBlockIndex* pfork = pindexBest;
1132 CBlockIndex* plonger = pindexNew;
1133 while (pfork != plonger)
1135 while (plonger->nHeight > pfork->nHeight)
1136 if (!(plonger = plonger->pprev))
1137 return error("Reorganize() : plonger->pprev is null");
1138 if (pfork == plonger)
1140 if (!(pfork = pfork->pprev))
1141 return error("Reorganize() : pfork->pprev is null");
1144 // List of what to disconnect
1145 vector<CBlockIndex*> vDisconnect;
1146 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1147 vDisconnect.push_back(pindex);
1149 // List of what to connect
1150 vector<CBlockIndex*> vConnect;
1151 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1152 vConnect.push_back(pindex);
1153 reverse(vConnect.begin(), vConnect.end());
1155 // Disconnect shorter branch
1156 vector<CTransaction> vResurrect;
1157 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1160 if (!block.ReadFromDisk(pindex))
1161 return error("Reorganize() : ReadFromDisk for disconnect failed");
1162 if (!block.DisconnectBlock(txdb, pindex))
1163 return error("Reorganize() : DisconnectBlock failed");
1165 // Queue memory transactions to resurrect
1166 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1167 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1168 vResurrect.push_back(tx);
1171 // Connect longer branch
1172 vector<CTransaction> vDelete;
1173 for (int i = 0; i < vConnect.size(); i++)
1175 CBlockIndex* pindex = vConnect[i];
1177 if (!block.ReadFromDisk(pindex))
1178 return error("Reorganize() : ReadFromDisk for connect failed");
1179 if (!block.ConnectBlock(txdb, pindex))
1183 return error("Reorganize() : ConnectBlock failed");
1186 // Queue memory transactions to delete
1187 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1188 vDelete.push_back(tx);
1190 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1191 return error("Reorganize() : WriteHashBestChain failed");
1192 if (!txdb.WriteAutoCheckpoint(Checkpoints::GetNextAutoCheckpoint(pindexNew->nCheckpoint)))
1193 return error("Reorganize() : WriteAutoCheckpoint failed");
1195 // Make sure it's successfully written to disk before changing memory structure
1196 if (!txdb.TxnCommit())
1197 return error("Reorganize() : TxnCommit failed");
1199 // Disconnect shorter branch
1200 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1202 pindex->pprev->pnext = NULL;
1204 // Connect longer branch
1205 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1207 pindex->pprev->pnext = pindex;
1209 // Resurrect memory transactions that were in the disconnected branch
1210 BOOST_FOREACH(CTransaction& tx, vResurrect)
1211 tx.AcceptToMemoryPool(txdb, false);
1213 // Delete redundant memory transactions that are in the connected branch
1214 BOOST_FOREACH(CTransaction& tx, vDelete)
1215 tx.RemoveFromMemoryPool();
1221 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1223 uint256 hash = GetHash();
1226 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1228 txdb.WriteHashBestChain(hash);
1229 txdb.WriteAutoCheckpoint(Checkpoints::GetNextAutoCheckpoint(pindexNew->nCheckpoint));
1230 if (!txdb.TxnCommit())
1231 return error("SetBestChain() : TxnCommit failed");
1232 pindexGenesisBlock = pindexNew;
1234 else if (hashPrevBlock == hashBestChain)
1236 // Adding to current best branch
1237 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash) || !txdb.WriteAutoCheckpoint(Checkpoints::GetNextAutoCheckpoint(pindexNew->nCheckpoint)))
1240 InvalidChainFound(pindexNew);
1241 return error("SetBestChain() : ConnectBlock failed");
1243 if (!txdb.TxnCommit())
1244 return error("SetBestChain() : TxnCommit failed");
1246 // Add to current best branch
1247 pindexNew->pprev->pnext = pindexNew;
1249 // Delete redundant memory transactions
1250 BOOST_FOREACH(CTransaction& tx, vtx)
1251 tx.RemoveFromMemoryPool();
1256 if (!Reorganize(txdb, pindexNew))
1259 InvalidChainFound(pindexNew);
1260 return error("SetBestChain() : Reorganize failed");
1264 // Update best block in wallet (so we can detect restored wallets)
1265 if (!IsInitialBlockDownload())
1267 const CBlockLocator locator(pindexNew);
1268 ::SetBestChain(locator);
1272 hashBestChain = hash;
1273 pindexBest = pindexNew;
1274 nBestHeight = pindexBest->nHeight;
1275 nBestChainTrust = pindexNew->nChainTrust;
1276 nTimeBestReceived = GetTime();
1277 nTransactionsUpdated++;
1278 Checkpoints::AdvanceAutoCheckpoint(pindexBest->nCheckpoint);
1279 printf("SetBestChain: new best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str());
1285 // ppcoin: coinstake must meet hash target according to the protocol:
1286 // at least one input must meet the formula
1287 // hash(nBits + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDay
1288 // this ensures that the chance of getting a coinstake is proportional to the
1289 // amount of coin age one owns.
1290 // The reason this hash is chosen is the following:
1291 // nBits: encodes all past block timestamps, making computing hash in advance
1293 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
1294 // generate transaction for future advantage
1295 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
1296 // nodes generating coinstake at the same time
1297 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
1299 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
1300 // generating coinstake at the same time
1301 // block/tx hash should not be used here as they can be generated in vast
1302 // quantities so as to generate blocks faster, degrading the system back into
1303 // a proof-of-work situation.
1305 bool CTransaction::CheckProofOfStake(CTxDB& txdb, unsigned int nBits) const
1307 CBigNum bnTargetPerCoinDay;
1308 bnTargetPerCoinDay.SetCompact(nBits);
1313 BOOST_FOREACH(const CTxIn& txin, vin)
1315 // First try finding the previous transaction in database
1316 CTransaction txPrev;
1318 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1319 continue; // previous transaction not in main chain
1320 if (nTime < txPrev.nTime)
1321 return false; // Transaction timestamp violation
1323 // Read block header
1325 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1326 return false; // unable to read block of previous transaction
1327 if (block.GetBlockTime() + AUTO_CHECKPOINT_TRUST_SPAN > nTime)
1328 continue; // only count coins from at least one week ago
1330 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1331 CBigNum bnCoinDay = CBigNum(nValueIn) * (nTime-txPrev.nTime) / COIN / (24 * 60 * 60);
1333 CDataStream ss(SER_GETHASH, VERSION);
1334 ss << nBits << block.nTime << (txindex.pos.nTxPos - txindex.pos.nBlockPos) << txPrev.nTime << txin.prevout.n << nTime;
1335 if (CBigNum(Hash(ss.begin(), ss.end())) <= bnCoinDay * bnTargetPerCoinDay)
1342 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1343 // Only those coins last spent at least a week ago count. As those
1344 // transactions not in main chain are not currently indexed so we
1345 // might not find out about their coin age. Older transactions are
1346 // guaranteed to be in main chain by auto checkpoint. This rule is
1347 // introduced to help nodes establish a consistent view of the coin
1348 // age (trust score) of competing branches.
1349 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1351 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1357 BOOST_FOREACH(const CTxIn& txin, vin)
1359 // First try finding the previous transaction in database
1360 CTransaction txPrev;
1362 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1363 continue; // previous transaction not in main chain
1364 if (nTime < txPrev.nTime)
1365 return false; // Transaction timestamp violation
1367 // Read block header
1369 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1370 return false; // unable to read block of previous transaction
1371 if (block.GetBlockTime() + AUTO_CHECKPOINT_TRUST_SPAN > nTime)
1372 continue; // only count coins from at least one week ago
1374 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1375 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1377 if (fDebug && GetBoolArg("-printcoinage"))
1378 printf("coin age nValueIn=%-12I64d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1381 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1382 if (fDebug && GetBoolArg("-printcoinage"))
1383 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1384 nCoinAge = bnCoinDay.getuint64();
1388 // ppcoin: total coin age spent in block, in the unit of coin-days.
1389 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1394 BOOST_FOREACH(const CTransaction& tx, vtx)
1397 if (tx.GetCoinAge(txdb, nTxCoinAge))
1398 nCoinAge += nTxCoinAge;
1403 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1405 if (fDebug && GetBoolArg("-printcoinage"))
1406 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1411 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1413 // Check for duplicate
1414 uint256 hash = GetHash();
1415 if (mapBlockIndex.count(hash))
1416 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1418 // Construct new block index object
1419 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1421 return error("AddToBlockIndex() : new CBlockIndex failed");
1422 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1424 pindexNew->phashBlock = &((*mi).first);
1425 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1426 if (miPrev != mapBlockIndex.end())
1428 pindexNew->pprev = (*miPrev).second;
1429 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1431 // ppcoin: compute chain checkpoint
1432 pindexNew->nCheckpoint = Checkpoints::GetNextChainCheckpoint(pindexNew->pprev);
1433 assert (pindexNew->nCheckpoint >= pindexNew->pprev->nCheckpoint);
1436 // ppcoin: compute chain trust score
1438 if (!GetCoinAge(nCoinAge))
1439 return error("AddToBlockIndex() : invalid transaction in block");
1440 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + nCoinAge;
1444 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1445 if (!txdb.TxnCommit())
1449 if (pindexNew->nChainTrust > nBestChainTrust)
1450 if (!SetBestChain(txdb, pindexNew))
1455 if (pindexNew == pindexBest)
1457 // Notify UI to display prev block's coinbase if it was ours
1458 static uint256 hashPrevBestCoinBase;
1459 UpdatedTransaction(hashPrevBestCoinBase);
1460 hashPrevBestCoinBase = vtx[0].GetHash();
1470 bool CBlock::CheckBlock() const
1472 // These are checks that are independent of context
1473 // that can be verified before saving an orphan block.
1476 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1477 return DoS(100, error("CheckBlock() : size limits failed"));
1479 // Check proof of work matches claimed amount
1480 if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1481 return DoS(50, error("CheckBlock() : proof of work failed"));
1484 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
1485 return error("CheckBlock() : block timestamp too far in the future");
1487 // First transaction must be coinbase, the rest must not be
1488 if (vtx.empty() || !vtx[0].IsCoinBase())
1489 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
1490 for (int i = 1; i < vtx.size(); i++)
1491 if (vtx[i].IsCoinBase())
1492 return DoS(100, error("CheckBlock() : more than one coinbase"));
1494 // ppcoin: only the second transaction can be the optional coinstake
1495 for (int i = 2; i < vtx.size(); i++)
1496 if (vtx[i].IsCoinStake())
1497 return DoS(100, error("CheckBlock() : coinstake in wrong position"));
1499 // Check coinbase timestamp
1500 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
1501 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
1503 // Check transactions
1504 BOOST_FOREACH(const CTransaction& tx, vtx)
1506 if (!tx.CheckTransaction())
1507 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
1508 // ppcoin: check transaction timestamp
1509 if (GetBlockTime() < (int64)tx.nTime)
1510 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
1513 // Check that it's not full of nonstandard transactions
1514 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1515 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
1518 if (hashMerkleRoot != BuildMerkleTree())
1519 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
1521 // Coin base vout[0] scriptPubKey must be the same as coin stake vout[1]
1523 if (vtx.size() > 1 && vtx[1].IsCoinStake() &&
1524 vtx[0].vout[0].scriptPubKey != vtx[1].vout[1].scriptPubKey)
1525 return DoS(100, error("CheckBlock() : block key mismatch"));
1528 // Check block signature
1529 if (!CheckBlockSignature())
1530 return DoS(100, error("CheckBlock() : bad block signature"));
1535 bool CBlock::AcceptBlock()
1537 // Check for duplicate
1538 uint256 hash = GetHash();
1539 if (mapBlockIndex.count(hash))
1540 return error("AcceptBlock() : block already in mapBlockIndex");
1542 // Get prev block index
1543 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1544 if (mi == mapBlockIndex.end())
1545 return DoS(10, error("AcceptBlock() : prev block not found"));
1546 CBlockIndex* pindexPrev = (*mi).second;
1547 int nHeight = pindexPrev->nHeight+1;
1549 // ppcoin: check for coinstake duplicate
1550 if (IsProofOfStake())
1551 { // check if coinstake is already connected; that would imply the owner
1552 // of the coinstake sent multiple blocks with the same coinstake
1554 if (CTxDB("r").ReadTxIndex(vtx[1].GetHash(), txindex))
1555 return error("AcceptBlock() : block %s has duplicate coinstake %s", hash.ToString().c_str(), vtx[1].GetHash().ToString().c_str());
1558 // Check proof-of-work or proof-of-stake
1559 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
1560 return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake"));
1562 // Check timestamp against prev
1563 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
1564 return error("AcceptBlock() : block's timestamp is too early");
1566 // Check that all transactions are finalized
1567 BOOST_FOREACH(const CTransaction& tx, vtx)
1568 if (!tx.IsFinal(nHeight, GetBlockTime()))
1569 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
1571 // Check that the block chain matches the known block chain up to a hardened checkpoint
1572 if (!Checkpoints::CheckHardened(nHeight, hash))
1573 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight));
1575 // ppcoin: check that the block satisfies automatic checkpoint
1576 if (!Checkpoints::CheckAuto(pindexPrev))
1577 return DoS(100, error("AcceptBlock() : rejected by automatic checkpoint at %d", Checkpoints::nAutoCheckpoint));
1579 // Write block to history file
1580 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1581 return error("AcceptBlock() : out of disk space");
1582 unsigned int nFile = -1;
1583 unsigned int nBlockPos = 0;
1584 if (!WriteToDisk(nFile, nBlockPos))
1585 return error("AcceptBlock() : WriteToDisk failed");
1586 if (!AddToBlockIndex(nFile, nBlockPos))
1587 return error("AcceptBlock() : AddToBlockIndex failed");
1589 // Relay inventory, but don't relay old inventory during initial block download
1590 if (hashBestChain == hash)
1591 CRITICAL_BLOCK(cs_vNodes)
1592 BOOST_FOREACH(CNode* pnode, vNodes)
1593 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 140700))
1594 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1599 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1601 // Check for duplicate
1602 uint256 hash = pblock->GetHash();
1603 if (mapBlockIndex.count(hash))
1604 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1605 if (mapOrphanBlocks.count(hash))
1606 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1608 // Preliminary checks
1609 if (!pblock->CheckBlock())
1610 return error("ProcessBlock() : CheckBlock FAILED");
1612 CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
1613 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
1615 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
1616 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
1619 pfrom->Misbehaving(100);
1620 return error("ProcessBlock() : block with timestamp before last checkpoint");
1623 bnNewBlock.SetCompact(pblock->nBits);
1625 bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
1626 if (pblock->IsProofOfWork() && bnNewBlock > bnRequired)
1628 pfrom->Misbehaving(100);
1629 return error("ProcessBlock() : block with too little proof-of-work");
1634 // If don't already have its previous block, shunt it off to holding area until we get it
1635 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1637 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1638 CBlock* pblock2 = new CBlock(*pblock);
1639 mapOrphanBlocks.insert(make_pair(hash, pblock2));
1640 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
1642 // Ask this guy to fill in what we're missing
1644 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
1649 if (!pblock->AcceptBlock())
1650 return error("ProcessBlock() : AcceptBlock FAILED");
1652 // Recursively process any orphan blocks that depended on this one
1653 vector<uint256> vWorkQueue;
1654 vWorkQueue.push_back(hash);
1655 for (int i = 0; i < vWorkQueue.size(); i++)
1657 uint256 hashPrev = vWorkQueue[i];
1658 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1659 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1662 CBlock* pblockOrphan = (*mi).second;
1663 if (pblockOrphan->AcceptBlock())
1664 vWorkQueue.push_back(pblockOrphan->GetHash());
1665 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1666 delete pblockOrphan;
1668 mapOrphanBlocksByPrev.erase(hashPrev);
1671 printf("ProcessBlock: ACCEPTED\n");
1682 bool CheckDiskSpace(uint64 nAdditionalBytes)
1684 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1686 // Check for 15MB because database could create another 10MB log file at any time
1687 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1690 string strMessage = _("Warning: Disk space is low ");
1691 strMiscWarning = strMessage;
1692 printf("*** %s\n", strMessage.c_str());
1693 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1694 CreateThread(Shutdown, NULL);
1700 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1704 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1707 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1709 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1718 static unsigned int nCurrentBlockFile = 1;
1720 FILE* AppendBlockFile(unsigned int& nFileRet)
1725 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1728 if (fseek(file, 0, SEEK_END) != 0)
1730 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1731 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1733 nFileRet = nCurrentBlockFile;
1737 nCurrentBlockFile++;
1741 bool LoadBlockIndex(bool fAllowNew)
1745 hashGenesisBlock = uint256("0x00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008");
1746 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1747 pchMessageStart[0] = 0xfa;
1748 pchMessageStart[1] = 0xbf;
1749 pchMessageStart[2] = 0xb5;
1750 pchMessageStart[3] = 0xda;
1757 if (!txdb.LoadBlockIndex())
1762 // Init with genesis block
1764 if (mapBlockIndex.empty())
1770 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1771 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1772 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1773 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1774 // vMerkleTree: 4a5e1e
1777 const char* pszTimestamp = "MarketWatch 07/Nov/2011 Gold tops $1,790 to end at over six-week high";
1779 txNew.nTime = 1325878371;
1780 txNew.vin.resize(1);
1781 txNew.vout.resize(1);
1782 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1783 txNew.vout[0].nValue = GetProofOfWorkReward(bnProofOfWorkLimit.GetCompact());
1784 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1786 block.vtx.push_back(txNew);
1787 block.hashPrevBlock = 0;
1788 block.hashMerkleRoot = block.BuildMerkleTree();
1790 block.nTime = 1325882536;
1791 block.nBits = bnProofOfWorkLimit.GetCompact();
1792 block.nNonce = 2081920190;
1796 block.nTime = 1296688602;
1797 block.nBits = 0x1d07fff8;
1798 block.nNonce = 384568319;
1802 printf("%s\n", block.GetHash().ToString().c_str());
1803 printf("%s\n", hashGenesisBlock.ToString().c_str());
1804 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1805 assert(block.hashMerkleRoot == uint256("0xc7311b56de266580cca65be108ae53d7100b5c3b17da8b1106044103abd7a521"));
1807 assert(block.GetHash() == hashGenesisBlock);
1808 assert(block.CheckBlock());
1810 // Start new block file
1812 unsigned int nBlockPos;
1813 if (!block.WriteToDisk(nFile, nBlockPos))
1814 return error("LoadBlockIndex() : writing genesis block to disk failed");
1815 if (!block.AddToBlockIndex(nFile, nBlockPos))
1816 return error("LoadBlockIndex() : genesis block not accepted");
1824 void PrintBlockTree()
1826 // precompute tree structure
1827 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1828 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1830 CBlockIndex* pindex = (*mi).second;
1831 mapNext[pindex->pprev].push_back(pindex);
1833 //while (rand() % 3 == 0)
1834 // mapNext[pindex->pprev].push_back(pindex);
1837 vector<pair<int, CBlockIndex*> > vStack;
1838 vStack.push_back(make_pair(0, pindexGenesisBlock));
1841 while (!vStack.empty())
1843 int nCol = vStack.back().first;
1844 CBlockIndex* pindex = vStack.back().second;
1847 // print split or gap
1848 if (nCol > nPrevCol)
1850 for (int i = 0; i < nCol-1; i++)
1854 else if (nCol < nPrevCol)
1856 for (int i = 0; i < nCol; i++)
1863 for (int i = 0; i < nCol; i++)
1868 block.ReadFromDisk(pindex);
1869 printf("%d (%u,%u) %s %08lx %s tx %d",
1873 block.GetHash().ToString().substr(0,20).c_str(),
1875 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1878 PrintWallets(block);
1880 // put the main timechain first
1881 vector<CBlockIndex*>& vNext = mapNext[pindex];
1882 for (int i = 0; i < vNext.size(); i++)
1884 if (vNext[i]->pnext)
1886 swap(vNext[0], vNext[i]);
1892 for (int i = 0; i < vNext.size(); i++)
1893 vStack.push_back(make_pair(nCol+i, vNext[i]));
1906 //////////////////////////////////////////////////////////////////////////////
1911 map<uint256, CAlert> mapAlerts;
1912 CCriticalSection cs_mapAlerts;
1914 string GetWarnings(string strFor)
1917 string strStatusBar;
1919 if (GetBoolArg("-testsafemode"))
1922 // Misc warnings like out of disk space and clock is wrong
1923 if (strMiscWarning != "")
1926 strStatusBar = strMiscWarning;
1929 // Longer invalid proof-of-work chain
1930 if (pindexBest && nBestInvalidTrust > nBestChainTrust + pindexBest->GetBlockTrust() * 6)
1933 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1937 CRITICAL_BLOCK(cs_mapAlerts)
1939 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1941 const CAlert& alert = item.second;
1942 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1944 nPriority = alert.nPriority;
1945 strStatusBar = alert.strStatusBar;
1950 if (strFor == "statusbar")
1951 return strStatusBar;
1952 else if (strFor == "rpc")
1954 assert(!"GetWarnings() : invalid parameter");
1958 bool CAlert::ProcessAlert()
1960 if (!CheckSignature())
1965 CRITICAL_BLOCK(cs_mapAlerts)
1967 // Cancel previous alerts
1968 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1970 const CAlert& alert = (*mi).second;
1973 printf("cancelling alert %d\n", alert.nID);
1974 mapAlerts.erase(mi++);
1976 else if (!alert.IsInEffect())
1978 printf("expiring alert %d\n", alert.nID);
1979 mapAlerts.erase(mi++);
1985 // Check if this alert has been cancelled
1986 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1988 const CAlert& alert = item.second;
1989 if (alert.Cancels(*this))
1991 printf("alert already cancelled by %d\n", alert.nID);
1997 mapAlerts.insert(make_pair(GetHash(), *this));
2000 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
2012 //////////////////////////////////////////////////////////////////////////////
2018 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2022 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2023 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2025 // Don't know what it is, just say we already got one
2032 // The message start string is designed to be unlikely to occur in normal data.
2033 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2034 // a large 4-byte int at any alignment.
2035 unsigned char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2038 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2040 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2041 RandAddSeedPerfmon();
2043 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2044 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2046 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2048 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2056 if (strCommand == "version")
2058 // Each connection can only send one version message
2059 if (pfrom->nVersion != 0)
2061 pfrom->Misbehaving(1);
2069 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2070 if (pfrom->nVersion == 10300)
2071 pfrom->nVersion = 300;
2072 if (pfrom->nVersion >= 106 && !vRecv.empty())
2073 vRecv >> addrFrom >> nNonce;
2074 if (pfrom->nVersion >= 106 && !vRecv.empty())
2075 vRecv >> pfrom->strSubVer;
2076 if (pfrom->nVersion >= 209 && !vRecv.empty())
2077 vRecv >> pfrom->nStartingHeight;
2079 if (pfrom->nVersion == 0)
2082 // Disconnect if we connected to ourself
2083 if (nNonce == nLocalHostNonce && nNonce > 1)
2085 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2086 pfrom->fDisconnect = true;
2090 // ppcoin: record my external IP reported by peer
2091 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
2092 addrSeenByPeer = addrMe;
2094 // Be shy and don't send version until we hear
2095 if (pfrom->fInbound)
2096 pfrom->PushVersion();
2098 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2100 AddTimeData(pfrom->addr.ip, nTime);
2103 if (pfrom->nVersion >= 209)
2104 pfrom->PushMessage("verack");
2105 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2106 if (pfrom->nVersion < 209)
2107 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2109 if (!pfrom->fInbound)
2111 // Advertise our address
2112 if (addrLocalHost.IsRoutable() && !fUseProxy)
2114 CAddress addr(addrLocalHost);
2115 addr.nTime = GetAdjustedTime();
2116 pfrom->PushAddress(addr);
2119 // Get recent addresses
2120 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2122 pfrom->PushMessage("getaddr");
2123 pfrom->fGetAddr = true;
2127 // Ask the first connected node for block updates
2128 static int nAskedForBlocks;
2129 if (!pfrom->fClient &&
2130 (pfrom->nVersion < 32000 || pfrom->nVersion >= 32400) &&
2131 (nAskedForBlocks < 1 || vNodes.size() <= 1))
2134 pfrom->PushGetBlocks(pindexBest, uint256(0));
2138 CRITICAL_BLOCK(cs_mapAlerts)
2139 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2140 item.second.RelayTo(pfrom);
2142 pfrom->fSuccessfullyConnected = true;
2144 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2146 cPeerBlockCounts.input(pfrom->nStartingHeight);
2150 else if (pfrom->nVersion == 0)
2152 // Must have a version message before anything else
2153 pfrom->Misbehaving(1);
2158 else if (strCommand == "verack")
2160 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2164 else if (strCommand == "addr")
2166 vector<CAddress> vAddr;
2169 // Don't want addr from older versions unless seeding
2170 if (pfrom->nVersion < 209)
2172 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2174 if (vAddr.size() > 1000)
2176 pfrom->Misbehaving(20);
2177 return error("message addr size() = %d", vAddr.size());
2180 // Store the new addresses
2183 int64 nNow = GetAdjustedTime();
2184 int64 nSince = nNow - 10 * 60;
2185 BOOST_FOREACH(CAddress& addr, vAddr)
2189 // ignore IPv6 for now, since it isn't implemented anyway
2192 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2193 addr.nTime = nNow - 5 * 24 * 60 * 60;
2194 AddAddress(addr, 2 * 60 * 60, &addrDB);
2195 pfrom->AddAddressKnown(addr);
2196 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2198 // Relay to a limited number of other nodes
2199 CRITICAL_BLOCK(cs_vNodes)
2201 // Use deterministic randomness to send to the same nodes for 24 hours
2202 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2203 static uint256 hashSalt;
2205 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2206 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2207 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2208 multimap<uint256, CNode*> mapMix;
2209 BOOST_FOREACH(CNode* pnode, vNodes)
2211 if (pnode->nVersion < 31402)
2213 unsigned int nPointer;
2214 memcpy(&nPointer, &pnode, sizeof(nPointer));
2215 uint256 hashKey = hashRand ^ nPointer;
2216 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2217 mapMix.insert(make_pair(hashKey, pnode));
2219 int nRelayNodes = 2;
2220 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2221 ((*mi).second)->PushAddress(addr);
2225 addrDB.TxnCommit(); // Save addresses (it's ok if this fails)
2226 if (vAddr.size() < 1000)
2227 pfrom->fGetAddr = false;
2231 else if (strCommand == "inv")
2235 if (vInv.size() > 50000)
2237 pfrom->Misbehaving(20);
2238 return error("message inv size() = %d", vInv.size());
2242 BOOST_FOREACH(const CInv& inv, vInv)
2246 pfrom->AddInventoryKnown(inv);
2248 bool fAlreadyHave = AlreadyHave(txdb, inv);
2250 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2254 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2255 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2257 // Track requests for our stuff
2258 Inventory(inv.hash);
2263 else if (strCommand == "getdata")
2267 if (vInv.size() > 50000)
2269 pfrom->Misbehaving(20);
2270 return error("message getdata size() = %d", vInv.size());
2273 BOOST_FOREACH(const CInv& inv, vInv)
2277 printf("received getdata for: %s\n", inv.ToString().c_str());
2279 if (inv.type == MSG_BLOCK)
2281 // Send block from disk
2282 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2283 if (mi != mapBlockIndex.end())
2286 block.ReadFromDisk((*mi).second);
2287 pfrom->PushMessage("block", block);
2289 // Trigger them to send a getblocks request for the next batch of inventory
2290 if (inv.hash == pfrom->hashContinue)
2292 // Bypass PushInventory, this must send even if redundant,
2293 // and we want it right after the last block so they don't
2294 // wait for other stuff first.
2296 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2297 pfrom->PushMessage("inv", vInv);
2298 pfrom->hashContinue = 0;
2302 else if (inv.IsKnownType())
2304 // Send stream from relay memory
2305 CRITICAL_BLOCK(cs_mapRelay)
2307 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2308 if (mi != mapRelay.end())
2309 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2313 // Track requests for our stuff
2314 Inventory(inv.hash);
2319 else if (strCommand == "getblocks")
2321 CBlockLocator locator;
2323 vRecv >> locator >> hashStop;
2325 // Find the last block the caller has in the main chain
2326 CBlockIndex* pindex = locator.GetBlockIndex();
2328 // Send the rest of the chain
2330 pindex = pindex->pnext;
2331 int nLimit = 500 + locator.GetDistanceBack();
2332 unsigned int nBytes = 0;
2333 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2334 for (; pindex; pindex = pindex->pnext)
2336 if (pindex->GetBlockHash() == hashStop)
2338 printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2341 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2343 block.ReadFromDisk(pindex, true);
2344 nBytes += block.GetSerializeSize(SER_NETWORK);
2345 if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
2347 // When this block is requested, we'll send an inv that'll make them
2348 // getblocks the next batch of inventory.
2349 printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
2350 pfrom->hashContinue = pindex->GetBlockHash();
2357 else if (strCommand == "getheaders")
2359 CBlockLocator locator;
2361 vRecv >> locator >> hashStop;
2363 CBlockIndex* pindex = NULL;
2364 if (locator.IsNull())
2366 // If locator is null, return the hashStop block
2367 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
2368 if (mi == mapBlockIndex.end())
2370 pindex = (*mi).second;
2374 // Find the last block the caller has in the main chain
2375 pindex = locator.GetBlockIndex();
2377 pindex = pindex->pnext;
2380 vector<CBlock> vHeaders;
2381 int nLimit = 2000 + locator.GetDistanceBack();
2382 printf("getheaders %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2383 for (; pindex; pindex = pindex->pnext)
2385 vHeaders.push_back(pindex->GetBlockHeader());
2386 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
2389 pfrom->PushMessage("headers", vHeaders);
2393 else if (strCommand == "tx")
2395 vector<uint256> vWorkQueue;
2396 CDataStream vMsg(vRecv);
2400 CInv inv(MSG_TX, tx.GetHash());
2401 pfrom->AddInventoryKnown(inv);
2403 bool fMissingInputs = false;
2404 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2406 SyncWithWallets(tx, NULL, true);
2407 RelayMessage(inv, vMsg);
2408 mapAlreadyAskedFor.erase(inv);
2409 vWorkQueue.push_back(inv.hash);
2411 // Recursively process any orphan transactions that depended on this one
2412 for (int i = 0; i < vWorkQueue.size(); i++)
2414 uint256 hashPrev = vWorkQueue[i];
2415 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2416 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2419 const CDataStream& vMsg = *((*mi).second);
2421 CDataStream(vMsg) >> tx;
2422 CInv inv(MSG_TX, tx.GetHash());
2424 if (tx.AcceptToMemoryPool(true))
2426 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2427 SyncWithWallets(tx, NULL, true);
2428 RelayMessage(inv, vMsg);
2429 mapAlreadyAskedFor.erase(inv);
2430 vWorkQueue.push_back(inv.hash);
2435 BOOST_FOREACH(uint256 hash, vWorkQueue)
2436 EraseOrphanTx(hash);
2438 else if (fMissingInputs)
2440 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2443 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
2447 else if (strCommand == "block")
2452 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
2455 CInv inv(MSG_BLOCK, block.GetHash());
2456 pfrom->AddInventoryKnown(inv);
2458 if (ProcessBlock(pfrom, &block))
2459 mapAlreadyAskedFor.erase(inv);
2460 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
2464 else if (strCommand == "getaddr")
2466 // Nodes rebroadcast an addr every 24 hours
2467 pfrom->vAddrToSend.clear();
2468 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2469 CRITICAL_BLOCK(cs_mapAddresses)
2471 unsigned int nCount = 0;
2472 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2474 const CAddress& addr = item.second;
2475 if (addr.nTime > nSince)
2478 BOOST_FOREACH(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2480 const CAddress& addr = item.second;
2481 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2482 pfrom->PushAddress(addr);
2488 else if (strCommand == "checkorder")
2493 if (!GetBoolArg("-allowreceivebyip"))
2495 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2502 /// we have a chance to check the order here
2504 // Keep giving the same key to the same ip until they use it
2505 if (!mapReuseKey.count(pfrom->addr.ip))
2506 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr.ip], true);
2508 // Send back approval of order and pubkey to use
2509 CScript scriptPubKey;
2510 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2511 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2515 else if (strCommand == "reply")
2520 CRequestTracker tracker;
2521 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2523 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2524 if (mi != pfrom->mapRequests.end())
2526 tracker = (*mi).second;
2527 pfrom->mapRequests.erase(mi);
2530 if (!tracker.IsNull())
2531 tracker.fn(tracker.param1, vRecv);
2535 else if (strCommand == "ping")
2540 else if (strCommand == "alert")
2545 if (alert.ProcessAlert())
2548 pfrom->setKnown.insert(alert.GetHash());
2549 CRITICAL_BLOCK(cs_vNodes)
2550 BOOST_FOREACH(CNode* pnode, vNodes)
2551 alert.RelayTo(pnode);
2558 // Ignore unknown commands for extensibility
2562 // Update the last seen time for this node's address
2563 if (pfrom->fNetworkNode)
2564 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2565 AddressCurrentlyConnected(pfrom->addr);
2571 bool ProcessMessages(CNode* pfrom)
2573 CDataStream& vRecv = pfrom->vRecv;
2577 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2581 // (4) message start
2590 // Scan for message start
2591 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2592 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2593 if (vRecv.end() - pstart < nHeaderSize)
2595 if (vRecv.size() > nHeaderSize)
2597 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2598 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2602 if (pstart - vRecv.begin() > 0)
2603 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2604 vRecv.erase(vRecv.begin(), pstart);
2607 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2612 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2615 string strCommand = hdr.GetCommand();
2618 unsigned int nMessageSize = hdr.nMessageSize;
2619 if (nMessageSize > MAX_SIZE)
2621 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2624 if (nMessageSize > vRecv.size())
2626 // Rewind and wait for rest of message
2627 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2632 if (vRecv.GetVersion() >= 209)
2634 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2635 unsigned int nChecksum = 0;
2636 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2637 if (nChecksum != hdr.nChecksum)
2639 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2640 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2645 // Copy message to its own buffer
2646 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2647 vRecv.ignore(nMessageSize);
2653 CRITICAL_BLOCK(cs_main)
2654 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2658 catch (std::ios_base::failure& e)
2660 if (strstr(e.what(), "end of data"))
2662 // Allow exceptions from underlength message on vRecv
2663 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());
2665 else if (strstr(e.what(), "size too large"))
2667 // Allow exceptions from overlong size
2668 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2672 PrintExceptionContinue(&e, "ProcessMessage()");
2675 catch (std::exception& e) {
2676 PrintExceptionContinue(&e, "ProcessMessage()");
2678 PrintExceptionContinue(NULL, "ProcessMessage()");
2682 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2690 bool SendMessages(CNode* pto, bool fSendTrickle)
2692 CRITICAL_BLOCK(cs_main)
2694 // Don't send anything until we get their version message
2695 if (pto->nVersion == 0)
2699 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2700 pto->PushMessage("ping");
2702 // Resend wallet transactions that haven't gotten in a block yet
2703 ResendWalletTransactions();
2705 // Address refresh broadcast
2706 static int64 nLastRebroadcast;
2707 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2709 nLastRebroadcast = GetTime();
2710 CRITICAL_BLOCK(cs_vNodes)
2712 BOOST_FOREACH(CNode* pnode, vNodes)
2714 // Periodically clear setAddrKnown to allow refresh broadcasts
2715 pnode->setAddrKnown.clear();
2717 // Rebroadcast our address
2718 if (addrLocalHost.IsRoutable() && !fUseProxy)
2720 CAddress addr(addrLocalHost);
2721 addr.nTime = GetAdjustedTime();
2722 pnode->PushAddress(addr);
2728 // Clear out old addresses periodically so it's not too much work at once
2729 static int64 nLastClear;
2730 if (nLastClear == 0)
2731 nLastClear = GetTime();
2732 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2734 nLastClear = GetTime();
2735 CRITICAL_BLOCK(cs_mapAddresses)
2738 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2739 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2740 mi != mapAddresses.end();)
2742 const CAddress& addr = (*mi).second;
2743 if (addr.nTime < nSince)
2745 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2747 addrdb.EraseAddress(addr);
2748 mapAddresses.erase(mi++);
2762 vector<CAddress> vAddr;
2763 vAddr.reserve(pto->vAddrToSend.size());
2764 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
2766 // returns true if wasn't already contained in the set
2767 if (pto->setAddrKnown.insert(addr).second)
2769 vAddr.push_back(addr);
2770 // receiver rejects addr messages larger than 1000
2771 if (vAddr.size() >= 1000)
2773 pto->PushMessage("addr", vAddr);
2778 pto->vAddrToSend.clear();
2780 pto->PushMessage("addr", vAddr);
2785 // Message: inventory
2788 vector<CInv> vInvWait;
2789 CRITICAL_BLOCK(pto->cs_inventory)
2791 vInv.reserve(pto->vInventoryToSend.size());
2792 vInvWait.reserve(pto->vInventoryToSend.size());
2793 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
2795 if (pto->setInventoryKnown.count(inv))
2798 // trickle out tx inv to protect privacy
2799 if (inv.type == MSG_TX && !fSendTrickle)
2801 // 1/4 of tx invs blast to all immediately
2802 static uint256 hashSalt;
2804 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2805 uint256 hashRand = inv.hash ^ hashSalt;
2806 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2807 bool fTrickleWait = ((hashRand & 3) != 0);
2809 // always trickle our own transactions
2813 if (GetTransaction(inv.hash, wtx))
2815 fTrickleWait = true;
2820 vInvWait.push_back(inv);
2825 // returns true if wasn't already contained in the set
2826 if (pto->setInventoryKnown.insert(inv).second)
2828 vInv.push_back(inv);
2829 if (vInv.size() >= 1000)
2831 pto->PushMessage("inv", vInv);
2836 pto->vInventoryToSend = vInvWait;
2839 pto->PushMessage("inv", vInv);
2845 vector<CInv> vGetData;
2846 int64 nNow = GetTime() * 1000000;
2848 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2850 const CInv& inv = (*pto->mapAskFor.begin()).second;
2851 if (!AlreadyHave(txdb, inv))
2853 printf("sending getdata: %s\n", inv.ToString().c_str());
2854 vGetData.push_back(inv);
2855 if (vGetData.size() >= 1000)
2857 pto->PushMessage("getdata", vGetData);
2861 mapAlreadyAskedFor[inv] = nNow;
2862 pto->mapAskFor.erase(pto->mapAskFor.begin());
2864 if (!vGetData.empty())
2865 pto->PushMessage("getdata", vGetData);
2884 //////////////////////////////////////////////////////////////////////////////
2889 int static FormatHashBlocks(void* pbuffer, unsigned int len)
2891 unsigned char* pdata = (unsigned char*)pbuffer;
2892 unsigned int blocks = 1 + ((len + 8) / 64);
2893 unsigned char* pend = pdata + 64 * blocks;
2894 memset(pdata + len, 0, 64 * blocks - len);
2896 unsigned int bits = len * 8;
2897 pend[-1] = (bits >> 0) & 0xff;
2898 pend[-2] = (bits >> 8) & 0xff;
2899 pend[-3] = (bits >> 16) & 0xff;
2900 pend[-4] = (bits >> 24) & 0xff;
2904 static const unsigned int pSHA256InitState[8] =
2905 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2907 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2910 unsigned char data[64];
2914 for (int i = 0; i < 16; i++)
2915 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
2917 for (int i = 0; i < 8; i++)
2918 ctx.h[i] = ((uint32_t*)pinit)[i];
2920 SHA256_Update(&ctx, data, sizeof(data));
2921 for (int i = 0; i < 8; i++)
2922 ((uint32_t*)pstate)[i] = ctx.h[i];
2926 // ScanHash scans nonces looking for a hash with at least some zero bits.
2927 // It operates on big endian data. Caller does the byte reversing.
2928 // All input buffers are 16-byte aligned. nNonce is usually preserved
2929 // between calls, but periodically or if nNonce is 0xffff0000 or above,
2930 // the block is rebuilt and nNonce starts over at zero.
2932 unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
2934 unsigned int& nNonce = *(unsigned int*)(pdata + 12);
2938 // Hash pdata using pmidstate as the starting state into
2939 // preformatted buffer phash1, then hash phash1 into phash
2941 SHA256Transform(phash1, pdata, pmidstate);
2942 SHA256Transform(phash, phash1, pSHA256InitState);
2944 // Return the nonce if the hash has at least some zero bits,
2945 // caller will check if it has enough to reach the target
2946 if (((unsigned short*)phash)[14] == 0)
2949 // If nothing found after trying for a while, return -1
2950 if ((nNonce & 0xffff) == 0)
2952 nHashesDone = 0xffff+1;
2958 // Some explaining would be appreciated
2963 set<uint256> setDependsOn;
2966 COrphan(CTransaction* ptxIn)
2974 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
2975 BOOST_FOREACH(uint256 hash, setDependsOn)
2976 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
2981 CBlock* CreateNewBlock(CWallet* pwallet)
2983 CReserveKey reservekey(pwallet);
2986 auto_ptr<CBlock> pblock(new CBlock());
2990 // Create coinbase tx
2992 txNew.vin.resize(1);
2993 txNew.vin[0].prevout.SetNull();
2994 txNew.vout.resize(1);
2995 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
2997 // Add our coinbase tx as first transaction
2998 pblock->vtx.push_back(txNew);
3000 // ppcoin: if coinstake available add coinstake tx
3001 static unsigned int nLastCoinStakeCheckTime = GetAdjustedTime() - nMaxClockDrift; // only initialized at startup
3002 CBlockIndex* pindexPrev = pindexBest;
3003 while (nLastCoinStakeCheckTime < GetAdjustedTime())
3005 pindexPrev = pindexBest; // get best block again to avoid getting stale
3006 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
3007 static CCriticalSection cs;
3008 CTransaction txCoinStake;
3011 nLastCoinStakeCheckTime++;
3012 txCoinStake.nTime = nLastCoinStakeCheckTime;
3014 if (pwallet->CreateCoinStake(txNew.vout[0].scriptPubKey, pblock->nBits, txCoinStake))
3016 pblock->vtx.push_back(txCoinStake);
3021 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
3023 // Collect memory pool transactions into the block
3025 CRITICAL_BLOCK(cs_main)
3026 CRITICAL_BLOCK(cs_mapTransactions)
3030 // Priority order to process transactions
3031 list<COrphan> vOrphan; // list memory doesn't move
3032 map<uint256, vector<COrphan*> > mapDependers;
3033 multimap<double, CTransaction*> mapPriority;
3034 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3036 CTransaction& tx = (*mi).second;
3037 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
3040 COrphan* porphan = NULL;
3041 double dPriority = 0;
3042 BOOST_FOREACH(const CTxIn& txin, tx.vin)
3044 // Read prev transaction
3045 CTransaction txPrev;
3047 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3049 // Has to wait for dependencies
3052 // Use list for automatic deletion
3053 vOrphan.push_back(COrphan(&tx));
3054 porphan = &vOrphan.back();
3056 mapDependers[txin.prevout.hash].push_back(porphan);
3057 porphan->setDependsOn.insert(txin.prevout.hash);
3060 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3062 // Read block header
3063 int nConf = txindex.GetDepthInMainChain();
3065 dPriority += (double)nValueIn * nConf;
3067 if (fDebug && GetBoolArg("-printpriority"))
3068 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3071 // Priority is sum(valuein * age) / txsize
3072 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3075 porphan->dPriority = dPriority;
3077 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3079 if (fDebug && GetBoolArg("-printpriority"))
3081 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3088 // Collect transactions into block
3089 map<uint256, CTxIndex> mapTestPool;
3090 uint64 nBlockSize = 1000;
3091 int nBlockSigOps = 100;
3092 while (!mapPriority.empty())
3094 // Take highest priority transaction off priority queue
3095 double dPriority = -(*mapPriority.begin()).first;
3096 CTransaction& tx = *(*mapPriority.begin()).second;
3097 mapPriority.erase(mapPriority.begin());
3100 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3101 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3103 int nTxSigOps = tx.GetSigOpCount();
3104 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3108 if (tx.nTime > GetAdjustedTime())
3111 // ppcoin: simplify transaction fee - allow free = false
3112 int64 nMinFee = tx.GetMinFee(nBlockSize, false, true);
3114 // Connecting shouldn't fail due to dependency on other memory pool transactions
3115 // because we're already processing them in order of dependency
3116 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3117 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3119 swap(mapTestPool, mapTestPoolTmp);
3122 pblock->vtx.push_back(tx);
3123 nBlockSize += nTxSize;
3124 nBlockSigOps += nTxSigOps;
3126 // Add transactions that depend on this one to the priority queue
3127 uint256 hash = tx.GetHash();
3128 if (mapDependers.count(hash))
3130 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
3132 if (!porphan->setDependsOn.empty())
3134 porphan->setDependsOn.erase(hash);
3135 if (porphan->setDependsOn.empty())
3136 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3142 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
3145 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3146 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3147 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3148 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
3149 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
3152 return pblock.release();
3156 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
3158 // Update nExtraNonce
3159 static uint256 hashPrevBlock;
3160 if (hashPrevBlock != pblock->hashPrevBlock)
3163 hashPrevBlock = pblock->hashPrevBlock;
3166 pblock->vtx[0].vin[0].scriptSig = CScript() << pblock->nTime << CBigNum(nExtraNonce);
3167 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3171 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
3174 // Prebuild hash buffers
3181 uint256 hashPrevBlock;
3182 uint256 hashMerkleRoot;
3185 unsigned int nNonce;
3188 unsigned char pchPadding0[64];
3190 unsigned char pchPadding1[64];
3193 memset(&tmp, 0, sizeof(tmp));
3195 tmp.block.nVersion = pblock->nVersion;
3196 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
3197 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
3198 tmp.block.nTime = pblock->nTime;
3199 tmp.block.nBits = pblock->nBits;
3200 tmp.block.nNonce = pblock->nNonce;
3202 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3203 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3205 // Byte swap all the input buffer
3206 for (int i = 0; i < sizeof(tmp)/4; i++)
3207 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3209 // Precalc the first half of the first hash, which stays constant
3210 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
3212 memcpy(pdata, &tmp.block, 128);
3213 memcpy(phash1, &tmp.hash1, 64);
3217 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
3219 uint256 hash = pblock->GetHash();
3220 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3222 if (hash > hashTarget && pblock->IsProofOfWork())
3223 return error("BitcoinMiner : proof-of-work not meeting target");
3226 printf("BitcoinMiner:\n");
3227 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3229 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3230 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3233 CRITICAL_BLOCK(cs_main)
3235 if (pblock->hashPrevBlock != hashBestChain)
3236 return error("BitcoinMiner : generated block is stale");
3238 // Remove key from key pool
3239 reservekey.KeepKey();
3241 // Track how many getdata requests this block gets
3242 CRITICAL_BLOCK(wallet.cs_wallet)
3243 wallet.mapRequestCount[pblock->GetHash()] = 0;
3245 // Process this block the same as if we had received it from another node
3246 if (!ProcessBlock(NULL, pblock))
3247 return error("BitcoinMiner : ProcessBlock, block not accepted");
3253 void static ThreadBitcoinMiner(void* parg);
3255 void static BitcoinMiner(CWallet *pwallet)
3257 printf("BitcoinMiner started\n");
3258 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3260 // Each thread has its own key and counter
3261 CReserveKey reservekey(pwallet);
3262 unsigned int nExtraNonce = 0;
3264 while (fGenerateBitcoins)
3266 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3270 while (vNodes.empty() || IsInitialBlockDownload())
3275 if (!fGenerateBitcoins)
3283 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3284 CBlockIndex* pindexPrev = pindexBest;
3286 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet));
3290 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
3292 // ppcoin: if proof-of-stake block found then process block
3293 if (pblock->IsProofOfStake())
3295 // should be able to sign block - assert here for now
3296 assert(pblock->SignBlock(*pwalletMain));
3297 printf("BitcoinMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
3298 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3299 CheckWork(pblock.get(), *pwalletMain, reservekey);
3300 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3304 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3308 // Prebuild hash buffers
3310 char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
3311 char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
3312 char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
3314 FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
3316 unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
3317 unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
3323 int64 nStart = GetTime();
3324 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3326 uint256& hash = *alignup<16>(hashbuf);
3329 unsigned int nHashesDone = 0;
3330 unsigned int nNonceFound;
3333 nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
3334 (char*)&hash, nHashesDone);
3336 // Check if something found
3337 if (nNonceFound != -1)
3339 for (int i = 0; i < sizeof(hash)/4; i++)
3340 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3342 if (hash <= hashTarget)
3345 pblock->nNonce = ByteReverse(nNonceFound);
3346 assert(hash == pblock->GetHash());
3347 // should be able to sign block - assert here for now
3348 assert(pblock->SignBlock(*pwalletMain));
3350 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3351 CheckWork(pblock.get(), *pwalletMain, reservekey);
3352 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3358 static int64 nHashCounter;
3359 if (nHPSTimerStart == 0)
3361 nHPSTimerStart = GetTimeMillis();
3365 nHashCounter += nHashesDone;
3366 if (GetTimeMillis() - nHPSTimerStart > 4000)
3368 static CCriticalSection cs;
3371 if (GetTimeMillis() - nHPSTimerStart > 4000)
3373 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3374 nHPSTimerStart = GetTimeMillis();
3376 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3377 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3378 static int64 nLogTime;
3379 if (GetTime() - nLogTime > 30 * 60)
3381 nLogTime = GetTime();
3382 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3383 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3389 // Check for stop or if block needs to be rebuilt
3392 if (!fGenerateBitcoins)
3394 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3398 if (nBlockNonce >= 0xffff0000)
3400 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3402 if (pindexPrev != pindexBest)
3405 // Update nTime every few seconds
3406 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3407 pblock->nTime = max(pblock->GetBlockTime(), pblock->GetMaxTransactionTime());
3408 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
3409 nBlockTime = ByteReverse(pblock->nTime);
3410 if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
3411 break; // need to update coinbase timestamp
3416 void static ThreadBitcoinMiner(void* parg)
3418 CWallet* pwallet = (CWallet*)parg;
3421 vnThreadsRunning[3]++;
3422 BitcoinMiner(pwallet);
3423 vnThreadsRunning[3]--;
3425 catch (std::exception& e) {
3426 vnThreadsRunning[3]--;
3427 PrintException(&e, "ThreadBitcoinMiner()");
3429 vnThreadsRunning[3]--;
3430 PrintException(NULL, "ThreadBitcoinMiner()");
3432 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
3434 if (vnThreadsRunning[3] == 0)
3436 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
3440 void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
3442 if (fGenerateBitcoins != fGenerate)
3444 fGenerateBitcoins = fGenerate;
3445 WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
3448 if (fGenerateBitcoins)
3450 int nProcessors = boost::thread::hardware_concurrency();
3451 printf("%d processors\n", nProcessors);
3452 if (nProcessors < 1)
3454 if (fLimitProcessors && nProcessors > nLimitProcessors)
3455 nProcessors = nLimitProcessors;
3456 int nAddThreads = nProcessors - vnThreadsRunning[3];
3457 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
3458 for (int i = 0; i < nAddThreads; i++)
3460 if (!CreateThread(ThreadBitcoinMiner, pwallet))
3461 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");