1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
12 #include "ui_interface.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
19 using namespace boost;
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
31 unsigned int nTransactionsUpdated = 0;
33 map<uint256, CBlockIndex*> mapBlockIndex;
34 set<pair<COutPoint, unsigned int> > setStakeSeen;
36 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
37 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
38 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
39 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
40 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
42 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
44 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as minimum age for coin age
45 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as stake age of full weight
46 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
47 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
49 int nCoinbaseMaturity = 500;
50 CBlockIndex* pindexGenesisBlock = NULL;
53 uint256 nBestChainTrust = 0;
54 uint256 nBestInvalidTrust = 0;
56 uint256 hashBestChain = 0;
57 CBlockIndex* pindexBest = NULL;
58 int64 nTimeBestReceived = 0;
60 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
62 map<uint256, CBlock*> mapOrphanBlocks;
63 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
64 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
65 map<uint256, uint256> mapProofOfStake;
67 map<uint256, CDataStream*> mapOrphanTransactions;
68 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
70 // Constant stuff for coinbase transactions we create:
71 CScript COINBASE_FLAGS;
73 const string strMessageMagic = "NovaCoin Signed Message:\n";
76 int64 nTransactionFee = MIN_TX_FEE;
77 bool fStakeUsePooledKeys = false;
78 extern enum Checkpoints::CPMode CheckpointsMode;
80 //////////////////////////////////////////////////////////////////////////////
82 // dispatching functions
85 // These functions dispatch to one or all registered wallets
88 void RegisterWallet(CWallet* pwalletIn)
91 LOCK(cs_setpwalletRegistered);
92 setpwalletRegistered.insert(pwalletIn);
96 void UnregisterWallet(CWallet* pwalletIn)
99 LOCK(cs_setpwalletRegistered);
100 setpwalletRegistered.erase(pwalletIn);
104 // check whether the passed transaction is from us
105 bool static IsFromMe(CTransaction& tx)
107 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
108 if (pwallet->IsFromMe(tx))
113 // get the wallet transaction with the given hash (if it exists)
114 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
116 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
117 if (pwallet->GetTransaction(hashTx,wtx))
122 // erases transaction with the given hash from all wallets
123 void static EraseFromWallets(uint256 hash)
125 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126 pwallet->EraseFromWallet(hash);
129 // make sure all wallets know about the given transaction, in the given block
130 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
134 // ppcoin: wallets need to refund inputs when disconnecting coinstake
135 if (tx.IsCoinStake())
137 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
138 if (pwallet->IsFromMe(tx))
139 pwallet->DisableTransaction(tx);
144 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
145 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
148 // notify wallets about a new best chain
149 void static SetBestChain(const CBlockLocator& loc)
151 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
152 pwallet->SetBestChain(loc);
155 // notify wallets about an updated transaction
156 void static UpdatedTransaction(const uint256& hashTx)
158 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
159 pwallet->UpdatedTransaction(hashTx);
163 void static PrintWallets(const CBlock& block)
165 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
166 pwallet->PrintWallet(block);
169 // notify wallets about an incoming inventory (for request counts)
170 void static Inventory(const uint256& hash)
172 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
173 pwallet->Inventory(hash);
176 // ask wallets to resend their transactions
177 void ResendWalletTransactions()
179 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
180 pwallet->ResendWalletTransactions();
189 //////////////////////////////////////////////////////////////////////////////
191 // mapOrphanTransactions
194 bool AddOrphanTx(const CDataStream& vMsg)
197 CDataStream(vMsg) >> tx;
198 uint256 hash = tx.GetHash();
199 if (mapOrphanTransactions.count(hash))
202 CDataStream* pvMsg = new CDataStream(vMsg);
204 // Ignore big transactions, to avoid a
205 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
206 // large transaction with a missing parent then we assume
207 // it will rebroadcast it later, after the parent transaction(s)
208 // have been mined or received.
209 // 10,000 orphans, each of which is at most 5,000 bytes big is
210 // at most 500 megabytes of orphans:
211 if (pvMsg->size() > 5000)
213 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
218 mapOrphanTransactions[hash] = pvMsg;
219 BOOST_FOREACH(const CTxIn& txin, tx.vin)
220 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
222 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
223 mapOrphanTransactions.size());
227 void static EraseOrphanTx(uint256 hash)
229 if (!mapOrphanTransactions.count(hash))
231 const CDataStream* pvMsg = mapOrphanTransactions[hash];
233 CDataStream(*pvMsg) >> tx;
234 BOOST_FOREACH(const CTxIn& txin, tx.vin)
236 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
237 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
238 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
241 mapOrphanTransactions.erase(hash);
244 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
246 unsigned int nEvicted = 0;
247 while (mapOrphanTransactions.size() > nMaxOrphans)
249 // Evict a random orphan:
250 uint256 randomhash = GetRandHash();
251 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
252 if (it == mapOrphanTransactions.end())
253 it = mapOrphanTransactions.begin();
254 EraseOrphanTx(it->first);
266 //////////////////////////////////////////////////////////////////////////////
268 // CTransaction and CTxIndex
271 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
274 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
276 if (!ReadFromDisk(txindexRet.pos))
278 if (prevout.n >= vout.size())
286 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
289 return ReadFromDisk(txdb, prevout, txindex);
292 bool CTransaction::ReadFromDisk(COutPoint prevout)
296 return ReadFromDisk(txdb, prevout, txindex);
299 bool CTransaction::IsStandard() const
301 if (nVersion > CTransaction::CURRENT_VERSION)
304 BOOST_FOREACH(const CTxIn& txin, vin)
306 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
307 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
308 // ~65-byte public keys, plus a few script ops.
309 if (txin.scriptSig.size() > 500)
311 if (!txin.scriptSig.IsPushOnly())
314 BOOST_FOREACH(const CTxOut& txout, vout) {
315 if (!::IsStandard(txout.scriptPubKey))
317 if (txout.nValue == 0)
324 // Check transaction inputs, and make sure any
325 // pay-to-script-hash transactions are evaluating IsStandard scripts
327 // Why bother? To avoid denial-of-service attacks; an attacker
328 // can submit a standard HASH... OP_EQUAL transaction,
329 // which will get accepted into blocks. The redemption
330 // script can be anything; an attacker could use a very
331 // expensive-to-check-upon-redemption script like:
332 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
334 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
337 return true; // Coinbases don't use vin normally
339 for (unsigned int i = 0; i < vin.size(); i++)
341 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
343 vector<vector<unsigned char> > vSolutions;
344 txnouttype whichType;
345 // get the scriptPubKey corresponding to this input:
346 const CScript& prevScript = prev.scriptPubKey;
347 if (!Solver(prevScript, whichType, vSolutions))
349 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
350 if (nArgsExpected < 0)
353 // Transactions with extra stuff in their scriptSigs are
354 // non-standard. Note that this EvalScript() call will
355 // be quick, because if there are any operations
356 // beside "push data" in the scriptSig the
357 // IsStandard() call returns false
358 vector<vector<unsigned char> > stack;
359 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
362 if (whichType == TX_SCRIPTHASH)
366 CScript subscript(stack.back().begin(), stack.back().end());
367 vector<vector<unsigned char> > vSolutions2;
368 txnouttype whichType2;
369 if (!Solver(subscript, whichType2, vSolutions2))
371 if (whichType2 == TX_SCRIPTHASH)
375 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
378 nArgsExpected += tmpExpected;
381 if (stack.size() != (unsigned int)nArgsExpected)
389 CTransaction::GetLegacySigOpCount() const
391 unsigned int nSigOps = 0;
392 BOOST_FOREACH(const CTxIn& txin, vin)
394 nSigOps += txin.scriptSig.GetSigOpCount(false);
396 BOOST_FOREACH(const CTxOut& txout, vout)
398 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
404 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
416 // Load the block this tx is in
418 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
420 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
425 // Update the tx's hashBlock
426 hashBlock = pblock->GetHash();
428 // Locate the transaction
429 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
430 if (pblock->vtx[nIndex] == *(CTransaction*)this)
432 if (nIndex == (int)pblock->vtx.size())
434 vMerkleBranch.clear();
436 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
440 // Fill in merkle branch
441 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
444 // Is the tx in a block that's in the main chain
445 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
446 if (mi == mapBlockIndex.end())
448 CBlockIndex* pindex = (*mi).second;
449 if (!pindex || !pindex->IsInMainChain())
452 return pindexBest->nHeight - pindex->nHeight + 1;
461 bool CTransaction::CheckTransaction() const
463 // Basic checks that don't depend on any context
465 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
467 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
469 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
470 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
472 // Check for negative or overflow output values
474 for (unsigned int i = 0; i < vout.size(); i++)
476 const CTxOut& txout = vout[i];
477 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
478 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
480 // NovaCoin: enforce minimum output amount for user transactions
481 // (and for all transactions until 20 Sep 2013)
482 if ((!IsCoinBase() || nTime < CHAINCHECKS_SWITCH_TIME)
483 && (!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
484 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
486 if (txout.nValue > MAX_MONEY)
487 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
488 nValueOut += txout.nValue;
489 if (!MoneyRange(nValueOut))
490 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
493 // Check for duplicate inputs
494 set<COutPoint> vInOutPoints;
495 BOOST_FOREACH(const CTxIn& txin, vin)
497 if (vInOutPoints.count(txin.prevout))
499 vInOutPoints.insert(txin.prevout);
504 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
505 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
509 BOOST_FOREACH(const CTxIn& txin, vin)
510 if (txin.prevout.IsNull())
511 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
517 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
518 enum GetMinFee_mode mode) const
520 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
521 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
523 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
524 unsigned int nNewBlockSize = nBlockSize + nBytes;
525 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
527 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
528 if (nMinFee < nBaseFee)
530 BOOST_FOREACH(const CTxOut& txout, vout)
531 if (txout.nValue < CENT)
535 // Raise the price as the block approaches full
536 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
538 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
540 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
543 if (!MoneyRange(nMinFee))
549 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
550 bool* pfMissingInputs)
553 *pfMissingInputs = false;
555 if (!tx.CheckTransaction())
556 return error("CTxMemPool::accept() : CheckTransaction failed");
558 // Coinbase is only valid in a block, not as a loose transaction
560 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
562 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
563 if (tx.IsCoinStake())
564 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
566 // To help v0.1.5 clients who would see it as a negative number
567 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
568 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
570 // Rather not work on nonstandard transactions (unless -testnet)
571 if (!fTestNet && !tx.IsStandard())
572 return error("CTxMemPool::accept() : nonstandard transaction type");
574 // Do we already have it?
575 uint256 hash = tx.GetHash();
578 if (mapTx.count(hash))
582 if (txdb.ContainsTx(hash))
585 // Check for conflicts with in-memory transactions
586 CTransaction* ptxOld = NULL;
587 for (unsigned int i = 0; i < tx.vin.size(); i++)
589 COutPoint outpoint = tx.vin[i].prevout;
590 if (mapNextTx.count(outpoint))
592 // Disable replacement feature for now
595 // Allow replacing with a newer version of the same transaction
598 ptxOld = mapNextTx[outpoint].ptx;
599 if (ptxOld->IsFinal())
601 if (!tx.IsNewerThan(*ptxOld))
603 for (unsigned int i = 0; i < tx.vin.size(); i++)
605 COutPoint outpoint = tx.vin[i].prevout;
606 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
616 map<uint256, CTxIndex> mapUnused;
617 bool fInvalid = false;
618 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
621 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
623 *pfMissingInputs = true;
627 // Check for non-standard pay-to-script-hash in inputs
628 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
629 return error("CTxMemPool::accept() : nonstandard transaction input");
631 // Note: if you modify this code to accept non-standard transactions, then
632 // you should add code here to check that the transaction does a
633 // reasonable number of ECDSA signature verifications.
635 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
636 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
638 // Don't accept it if it can't get into a block
639 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY);
640 if (nFees < txMinFee)
641 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
642 hash.ToString().c_str(),
645 // Continuously rate-limit free transactions
646 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
647 // be annoying or make others' transactions take longer to confirm.
648 if (nFees < MIN_RELAY_TX_FEE)
650 static CCriticalSection cs;
651 static double dFreeCount;
652 static int64 nLastTime;
653 int64 nNow = GetTime();
657 // Use an exponentially decaying ~10-minute window:
658 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
660 // -limitfreerelay unit is thousand-bytes-per-minute
661 // At default rate it would take over a month to fill 1GB
662 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
663 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
665 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
670 // Check against previous transactions
671 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
672 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
674 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
678 // Store transaction in memory
683 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
686 addUnchecked(hash, tx);
689 ///// are we sure this is ok when loading transactions or restoring block txes
690 // If updated, erase old tx from wallet
692 EraseFromWallets(ptxOld->GetHash());
694 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
695 hash.ToString().substr(0,10).c_str(),
700 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
702 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
705 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
707 // Add to memory pool without checking anything. Don't call this directly,
708 // call CTxMemPool::accept to properly check the transaction first.
711 for (unsigned int i = 0; i < tx.vin.size(); i++)
712 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
713 nTransactionsUpdated++;
719 bool CTxMemPool::remove(CTransaction &tx)
721 // Remove transaction from memory pool
724 uint256 hash = tx.GetHash();
725 if (mapTx.count(hash))
727 BOOST_FOREACH(const CTxIn& txin, tx.vin)
728 mapNextTx.erase(txin.prevout);
730 nTransactionsUpdated++;
736 void CTxMemPool::clear()
741 ++nTransactionsUpdated;
744 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
749 vtxid.reserve(mapTx.size());
750 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
751 vtxid.push_back((*mi).first);
757 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
759 if (hashBlock == 0 || nIndex == -1)
762 // Find the block it claims to be in
763 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
764 if (mi == mapBlockIndex.end())
766 CBlockIndex* pindex = (*mi).second;
767 if (!pindex || !pindex->IsInMainChain())
770 // Make sure the merkle branch connects to this block
771 if (!fMerkleVerified)
773 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
775 fMerkleVerified = true;
779 return pindexBest->nHeight - pindex->nHeight + 1;
783 int CMerkleTx::GetBlocksToMaturity() const
785 if (!(IsCoinBase() || IsCoinStake()))
787 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
791 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
795 if (!IsInMainChain() && !ClientConnectInputs())
797 return CTransaction::AcceptToMemoryPool(txdb, false);
801 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
805 bool CMerkleTx::AcceptToMemoryPool()
808 return AcceptToMemoryPool(txdb);
813 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
818 // Add previous supporting transactions first
819 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
821 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
823 uint256 hash = tx.GetHash();
824 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
825 tx.AcceptToMemoryPool(txdb, fCheckInputs);
828 return AcceptToMemoryPool(txdb, fCheckInputs);
833 bool CWalletTx::AcceptWalletTransaction()
836 return AcceptWalletTransaction(txdb);
839 int CTxIndex::GetDepthInMainChain() const
843 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
845 // Find the block in the index
846 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
847 if (mi == mapBlockIndex.end())
849 CBlockIndex* pindex = (*mi).second;
850 if (!pindex || !pindex->IsInMainChain())
852 return 1 + nBestHeight - pindex->nHeight;
855 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
856 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
862 if (mempool.exists(hash))
864 tx = mempool.lookup(hash);
870 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
873 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
874 hashBlock = block.GetHash();
888 //////////////////////////////////////////////////////////////////////////////
890 // CBlock and CBlockIndex
893 static CBlockIndex* pblockindexFBBHLast;
894 CBlockIndex* FindBlockByHeight(int nHeight)
896 CBlockIndex *pblockindex;
897 if (nHeight < nBestHeight / 2)
898 pblockindex = pindexGenesisBlock;
900 pblockindex = pindexBest;
901 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
902 pblockindex = pblockindexFBBHLast;
903 while (pblockindex->nHeight > nHeight)
904 pblockindex = pblockindex->pprev;
905 while (pblockindex->nHeight < nHeight)
906 pblockindex = pblockindex->pnext;
907 pblockindexFBBHLast = pblockindex;
911 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
913 if (!fReadTransactions)
915 *this = pindex->GetBlockHeader();
918 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
920 if (GetHash() != pindex->GetBlockHash())
921 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
925 uint256 static GetOrphanRoot(const CBlock* pblock)
927 // Work back to the first block in the orphan chain
928 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
929 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
930 return pblock->GetHash();
933 // ppcoin: find block wanted by given orphan block
934 uint256 WantedByOrphan(const CBlock* pblockOrphan)
936 // Work back to the first block in the orphan chain
937 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
938 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
939 return pblockOrphan->hashPrevBlock;
942 // select stake target limit according to hard-coded conditions
943 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
945 if(fTestNet) // separate proof of stake target limit for testnet
946 return bnProofOfStakeLimit;
947 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
948 return bnProofOfStakeLimit;
949 if(nHeight + 1 > 15000) // 24 bits since block 15000
950 return bnProofOfStakeLegacyLimit;
951 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
952 return bnProofOfStakeHardLimit;
954 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
957 // miner's coin base reward based on nBits
958 int64 GetProofOfWorkReward(unsigned int nBits)
960 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
963 bnTarget.SetCompact(nBits);
964 CBigNum bnTargetLimit = bnProofOfWorkLimit;
965 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
967 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
968 // A reasonably continuous curve is used to avoid shock to market
969 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
971 // Human readable form:
973 // nSubsidy = 100 / (diff ^ 1/6)
974 CBigNum bnLowerBound = CENT;
975 CBigNum bnUpperBound = bnSubsidyLimit;
976 while (bnLowerBound + CENT <= bnUpperBound)
978 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
979 if (fDebug && GetBoolArg("-printcreation"))
980 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
981 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
982 bnUpperBound = bnMidValue;
984 bnLowerBound = bnMidValue;
987 int64 nSubsidy = bnUpperBound.getuint64();
989 nSubsidy = (nSubsidy / CENT) * CENT;
990 if (fDebug && GetBoolArg("-printcreation"))
991 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
993 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
996 // miner's coin stake reward based on nBits and coin age spent (coin-days)
997 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
999 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1001 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1003 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1005 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1007 bnTarget.SetCompact(nBits);
1008 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1009 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1011 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1013 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1014 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1015 bnMidPart, bnRewardPart;
1017 while (bnLowerBound + CENT <= bnUpperBound)
1019 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1020 if (fDebug && GetBoolArg("-printcreation"))
1021 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1023 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1026 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1028 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1030 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1033 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1034 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1039 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1041 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1043 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1046 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1047 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1050 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1051 bnUpperBound = bnMidValue;
1053 bnLowerBound = bnMidValue;
1056 nRewardCoinYear = bnUpperBound.getuint64();
1057 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1061 // Old creation amount per coin-year, 5% fixed stake mint rate
1062 nRewardCoinYear = 5 * CENT;
1066 return nRewardCoinYear;
1068 // Fix problem with proof-of-stake rewards calculation since 20 Sep 2013
1069 if(nTime < CHAINCHECKS_SWITCH_TIME)
1070 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
1072 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1074 // Set reasonable reward limit for large inputs since 20 Oct 2013
1076 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1077 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1079 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1080 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1082 nSubsidy = min(nSubsidy, nSubsidyLimit);
1085 if (fDebug && GetBoolArg("-printcreation"))
1086 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1090 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1092 // get proof of work blocks max spacing according to hard-coded conditions
1093 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1095 if(nTime > TARGETS_SWITCH_TIME)
1096 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1099 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1101 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1105 // maximum nBits value could possible be required nTime after
1107 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1110 bnResult.SetCompact(nBase);
1112 while (nTime > 0 && bnResult < bnTargetLimit)
1114 // Maximum 200% adjustment per day...
1116 nTime -= 24 * 60 * 60;
1118 if (bnResult > bnTargetLimit)
1119 bnResult = bnTargetLimit;
1120 return bnResult.GetCompact();
1124 // minimum amount of work that could possibly be required nTime after
1125 // minimum proof-of-work required was nBase
1127 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1129 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1133 // minimum amount of stake that could possibly be required nTime after
1134 // minimum proof-of-stake required was nBase
1136 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1138 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1142 // ppcoin: find last block index up to pindex
1143 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1145 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1146 pindex = pindex->pprev;
1150 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1152 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1154 if (pindexLast == NULL)
1155 return bnTargetLimit.GetCompact(); // genesis block
1157 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1158 if (pindexPrev->pprev == NULL)
1159 return bnTargetLimit.GetCompact(); // first block
1160 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1161 if (pindexPrevPrev->pprev == NULL)
1162 return bnTargetLimit.GetCompact(); // second block
1164 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1166 // ppcoin: target change every block
1167 // ppcoin: retarget with exponential moving toward target spacing
1169 bnNew.SetCompact(pindexPrev->nBits);
1170 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1171 int64 nInterval = nTargetTimespan / nTargetSpacing;
1172 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1173 bnNew /= ((nInterval + 1) * nTargetSpacing);
1175 if (bnNew > bnTargetLimit)
1176 bnNew = bnTargetLimit;
1178 return bnNew.GetCompact();
1181 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1184 bnTarget.SetCompact(nBits);
1187 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1188 return error("CheckProofOfWork() : nBits below minimum work");
1190 // Check proof of work matches claimed amount
1191 if (hash > bnTarget.getuint256())
1192 return error("CheckProofOfWork() : hash doesn't match nBits");
1197 // Return maximum amount of blocks that other nodes claim to have
1198 int GetNumBlocksOfPeers()
1200 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1203 bool IsInitialBlockDownload()
1205 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1207 static int64 nLastUpdate;
1208 static CBlockIndex* pindexLastBest;
1209 if (pindexBest != pindexLastBest)
1211 pindexLastBest = pindexBest;
1212 nLastUpdate = GetTime();
1214 return (GetTime() - nLastUpdate < 10 &&
1215 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1218 void static InvalidChainFound(CBlockIndex* pindexNew)
1220 if (pindexNew->nChainTrust > nBestInvalidTrust)
1222 nBestInvalidTrust = pindexNew->nChainTrust;
1223 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1224 uiInterface.NotifyBlocksChanged();
1227 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1228 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1230 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1231 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1232 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1233 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1234 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1235 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1236 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1237 nBestBlockTrust.Get64(),
1238 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1242 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1244 nTime = max(GetBlockTime(), GetAdjustedTime());
1257 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1259 // Relinquish previous transactions' spent pointers
1262 BOOST_FOREACH(const CTxIn& txin, vin)
1264 COutPoint prevout = txin.prevout;
1266 // Get prev txindex from disk
1268 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1269 return error("DisconnectInputs() : ReadTxIndex failed");
1271 if (prevout.n >= txindex.vSpent.size())
1272 return error("DisconnectInputs() : prevout.n out of range");
1274 // Mark outpoint as not spent
1275 txindex.vSpent[prevout.n].SetNull();
1278 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1279 return error("DisconnectInputs() : UpdateTxIndex failed");
1283 // Remove transaction from index
1284 // This can fail if a duplicate of this transaction was in a chain that got
1285 // reorganized away. This is only possible if this transaction was completely
1286 // spent, so erasing it would be a no-op anyway.
1287 txdb.EraseTxIndex(*this);
1293 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1294 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1296 // FetchInputs can return false either because we just haven't seen some inputs
1297 // (in which case the transaction should be stored as an orphan)
1298 // or because the transaction is malformed (in which case the transaction should
1299 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1303 return true; // Coinbase transactions have no inputs to fetch.
1305 for (unsigned int i = 0; i < vin.size(); i++)
1307 COutPoint prevout = vin[i].prevout;
1308 if (inputsRet.count(prevout.hash))
1309 continue; // Got it already
1312 CTxIndex& txindex = inputsRet[prevout.hash].first;
1314 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1316 // Get txindex from current proposed changes
1317 txindex = mapTestPool.find(prevout.hash)->second;
1321 // Read txindex from txdb
1322 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1324 if (!fFound && (fBlock || fMiner))
1325 return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1328 CTransaction& txPrev = inputsRet[prevout.hash].second;
1329 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1331 // Get prev tx from single transactions in memory
1334 if (!mempool.exists(prevout.hash))
1335 return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1336 txPrev = mempool.lookup(prevout.hash);
1339 txindex.vSpent.resize(txPrev.vout.size());
1343 // Get prev tx from disk
1344 if (!txPrev.ReadFromDisk(txindex.pos))
1345 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1349 // Make sure all prevout.n indexes are valid:
1350 for (unsigned int i = 0; i < vin.size(); i++)
1352 const COutPoint prevout = vin[i].prevout;
1353 assert(inputsRet.count(prevout.hash) != 0);
1354 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1355 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1356 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1358 // Revisit this if/when transaction replacement is implemented and allows
1361 return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" 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()));
1368 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1370 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1371 if (mi == inputs.end())
1372 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1374 const CTransaction& txPrev = (mi->second).second;
1375 if (input.prevout.n >= txPrev.vout.size())
1376 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1378 return txPrev.vout[input.prevout.n];
1381 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1387 for (unsigned int i = 0; i < vin.size(); i++)
1389 nResult += GetOutputFor(vin[i], inputs).nValue;
1395 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1400 unsigned int nSigOps = 0;
1401 for (unsigned int i = 0; i < vin.size(); i++)
1403 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1404 if (prevout.scriptPubKey.IsPayToScriptHash())
1405 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1410 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1411 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1412 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1414 // Take over previous transactions' spent pointers
1415 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1416 // fMiner is true when called from the internal bitcoin miner
1417 // ... both are false when called from CTransaction::AcceptToMemoryPool
1422 for (unsigned int i = 0; i < vin.size(); i++)
1424 COutPoint prevout = vin[i].prevout;
1425 assert(inputs.count(prevout.hash) > 0);
1426 CTxIndex& txindex = inputs[prevout.hash].first;
1427 CTransaction& txPrev = inputs[prevout.hash].second;
1429 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1430 return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" 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()));
1432 // If prev is coinbase or coinstake, check that it's matured
1433 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1434 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1435 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1436 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1438 // ppcoin: check transaction timestamp
1439 if (txPrev.nTime > nTime)
1440 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1442 // Check for negative or overflow input values
1443 nValueIn += txPrev.vout[prevout.n].nValue;
1444 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1445 return DoS(100, error("ConnectInputs() : txin values out of range"));
1448 // The first loop above does all the inexpensive checks.
1449 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1450 // Helps prevent CPU exhaustion attacks.
1451 for (unsigned int i = 0; i < vin.size(); i++)
1453 COutPoint prevout = vin[i].prevout;
1454 assert(inputs.count(prevout.hash) > 0);
1455 CTxIndex& txindex = inputs[prevout.hash].first;
1456 CTransaction& txPrev = inputs[prevout.hash].second;
1458 // Check for conflicts (double-spend)
1459 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1460 // for an attacker to attempt to split the network.
1461 if (!txindex.vSpent[prevout.n].IsNull())
1462 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());
1464 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1465 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1466 // still computed and checked, and any change will be caught at the next checkpoint.
1467 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1470 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1472 // only during transition phase for P2SH: do not invoke anti-DoS code for
1473 // potentially old clients relaying bad P2SH transactions
1474 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1475 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1477 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1481 // Mark outpoints as spent
1482 txindex.vSpent[prevout.n] = posThisTx;
1485 if (fBlock || fMiner)
1487 mapTestPool[prevout.hash] = txindex;
1493 // ppcoin: coin stake tx earns reward instead of paying fee
1495 if (!GetCoinAge(txdb, nCoinAge))
1496 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1498 int64 nStakeReward = GetValueOut() - nValueIn;
1499 int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1501 if (nStakeReward > nCalculatedStakeReward)
1502 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1506 if (nValueIn < GetValueOut())
1507 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1509 // Tally transaction fees
1510 int64 nTxFee = nValueIn - GetValueOut();
1512 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1513 // ppcoin: enforce transaction fees for every block
1514 if (nTxFee < GetMinFee())
1515 return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false;
1518 if (!MoneyRange(nFees))
1519 return DoS(100, error("ConnectInputs() : nFees out of range"));
1527 bool CTransaction::ClientConnectInputs()
1532 // Take over previous transactions' spent pointers
1536 for (unsigned int i = 0; i < vin.size(); i++)
1538 // Get prev tx from single transactions in memory
1539 COutPoint prevout = vin[i].prevout;
1540 if (!mempool.exists(prevout.hash))
1542 CTransaction& txPrev = mempool.lookup(prevout.hash);
1544 if (prevout.n >= txPrev.vout.size())
1548 if (!VerifySignature(txPrev, *this, i, true, 0))
1549 return error("ConnectInputs() : VerifySignature failed");
1551 ///// this is redundant with the mempool.mapNextTx stuff,
1552 ///// not sure which I want to get rid of
1553 ///// this has to go away now that posNext is gone
1554 // // Check for conflicts
1555 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1556 // return error("ConnectInputs() : prev tx already used");
1558 // // Flag outpoints as used
1559 // txPrev.vout[prevout.n].posNext = posThisTx;
1561 nValueIn += txPrev.vout[prevout.n].nValue;
1563 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1564 return error("ClientConnectInputs() : txin values out of range");
1566 if (GetValueOut() > nValueIn)
1576 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1578 // Disconnect in reverse order
1579 for (int i = vtx.size()-1; i >= 0; i--)
1580 if (!vtx[i].DisconnectInputs(txdb))
1583 // Update block index on disk without changing it in memory.
1584 // The memory index structure will be changed after the db commits.
1587 CDiskBlockIndex blockindexPrev(pindex->pprev);
1588 blockindexPrev.hashNext = 0;
1589 if (!txdb.WriteBlockIndex(blockindexPrev))
1590 return error("DisconnectBlock() : WriteBlockIndex failed");
1593 // ppcoin: clean up wallet after disconnecting coinstake
1594 BOOST_FOREACH(CTransaction& tx, vtx)
1595 SyncWithWallets(tx, this, false, false);
1600 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1602 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1603 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1606 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1607 // unless those are already completely spent.
1608 // If such overwrites are allowed, coinbases and transactions depending upon those
1609 // can be duplicated to remove the ability to spend the first instance -- even after
1610 // being sent to another address.
1611 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1612 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1613 // already refuses previously-known transaction ids entirely.
1614 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1615 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1616 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1617 // initial block download.
1618 bool fEnforceBIP30 = true; // Always active in NovaCoin
1619 bool fStrictPayToScriptHash = true; // Always active in NovaCoin
1621 //// issue here: it doesn't know the version
1622 unsigned int nTxPos;
1624 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1625 // Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from
1628 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1630 map<uint256, CTxIndex> mapQueuedChanges;
1633 int64 nValueOut = 0;
1634 unsigned int nSigOps = 0;
1635 BOOST_FOREACH(CTransaction& tx, vtx)
1637 uint256 hashTx = tx.GetHash();
1639 if (fEnforceBIP30) {
1640 CTxIndex txindexOld;
1641 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1642 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1648 nSigOps += tx.GetLegacySigOpCount();
1649 if (nSigOps > MAX_BLOCK_SIGOPS)
1650 return DoS(100, error("ConnectBlock() : too many sigops"));
1652 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1654 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1656 MapPrevTx mapInputs;
1657 if (tx.IsCoinBase())
1658 nValueOut += tx.GetValueOut();
1662 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1665 if (fStrictPayToScriptHash)
1667 // Add in sigops done by pay-to-script-hash inputs;
1668 // this is to prevent a "rogue miner" from creating
1669 // an incredibly-expensive-to-validate block.
1670 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1671 if (nSigOps > MAX_BLOCK_SIGOPS)
1672 return DoS(100, error("ConnectBlock() : too many sigops"));
1675 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1676 int64 nTxValueOut = tx.GetValueOut();
1677 nValueIn += nTxValueIn;
1678 nValueOut += nTxValueOut;
1679 if (!tx.IsCoinStake())
1680 nFees += nTxValueIn - nTxValueOut;
1682 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1686 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1689 // ppcoin: track money supply and mint amount info
1690 pindex->nMint = nValueOut - nValueIn + nFees;
1691 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1692 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1693 return error("Connect() : WriteBlockIndex for pindex failed");
1695 // ppcoin: fees are not collected by miners as in bitcoin
1696 // ppcoin: fees are destroyed to compensate the entire network
1697 if (fDebug && GetBoolArg("-printcreation"))
1698 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1703 // Write queued txindex changes
1704 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1706 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1707 return error("ConnectBlock() : UpdateTxIndex failed");
1710 // Update block index on disk without changing it in memory.
1711 // The memory index structure will be changed after the db commits.
1714 CDiskBlockIndex blockindexPrev(pindex->pprev);
1715 blockindexPrev.hashNext = pindex->GetBlockHash();
1716 if (!txdb.WriteBlockIndex(blockindexPrev))
1717 return error("ConnectBlock() : WriteBlockIndex failed");
1720 // Watch for transactions paying to me
1721 BOOST_FOREACH(CTransaction& tx, vtx)
1722 SyncWithWallets(tx, this, true);
1727 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1729 printf("REORGANIZE\n");
1732 CBlockIndex* pfork = pindexBest;
1733 CBlockIndex* plonger = pindexNew;
1734 while (pfork != plonger)
1736 while (plonger->nHeight > pfork->nHeight)
1737 if (!(plonger = plonger->pprev))
1738 return error("Reorganize() : plonger->pprev is null");
1739 if (pfork == plonger)
1741 if (!(pfork = pfork->pprev))
1742 return error("Reorganize() : pfork->pprev is null");
1745 // List of what to disconnect
1746 vector<CBlockIndex*> vDisconnect;
1747 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1748 vDisconnect.push_back(pindex);
1750 // List of what to connect
1751 vector<CBlockIndex*> vConnect;
1752 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1753 vConnect.push_back(pindex);
1754 reverse(vConnect.begin(), vConnect.end());
1756 printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
1757 printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
1759 // Disconnect shorter branch
1760 vector<CTransaction> vResurrect;
1761 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1764 if (!block.ReadFromDisk(pindex))
1765 return error("Reorganize() : ReadFromDisk for disconnect failed");
1766 if (!block.DisconnectBlock(txdb, pindex))
1767 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1769 // Queue memory transactions to resurrect
1770 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1771 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1772 vResurrect.push_back(tx);
1775 // Connect longer branch
1776 vector<CTransaction> vDelete;
1777 for (unsigned int i = 0; i < vConnect.size(); i++)
1779 CBlockIndex* pindex = vConnect[i];
1781 if (!block.ReadFromDisk(pindex))
1782 return error("Reorganize() : ReadFromDisk for connect failed");
1783 if (!block.ConnectBlock(txdb, pindex))
1786 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1789 // Queue memory transactions to delete
1790 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1791 vDelete.push_back(tx);
1793 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1794 return error("Reorganize() : WriteHashBestChain failed");
1796 // Make sure it's successfully written to disk before changing memory structure
1797 if (!txdb.TxnCommit())
1798 return error("Reorganize() : TxnCommit failed");
1800 // Disconnect shorter branch
1801 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1803 pindex->pprev->pnext = NULL;
1805 // Connect longer branch
1806 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1808 pindex->pprev->pnext = pindex;
1810 // Resurrect memory transactions that were in the disconnected branch
1811 BOOST_FOREACH(CTransaction& tx, vResurrect)
1812 tx.AcceptToMemoryPool(txdb, false);
1814 // Delete redundant memory transactions that are in the connected branch
1815 BOOST_FOREACH(CTransaction& tx, vDelete)
1818 printf("REORGANIZE: done\n");
1824 // Called from inside SetBestChain: attaches a block to the new best chain being built
1825 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1827 uint256 hash = GetHash();
1829 // Adding to current best branch
1830 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1833 InvalidChainFound(pindexNew);
1836 if (!txdb.TxnCommit())
1837 return error("SetBestChain() : TxnCommit failed");
1839 // Add to current best branch
1840 pindexNew->pprev->pnext = pindexNew;
1842 // Delete redundant memory transactions
1843 BOOST_FOREACH(CTransaction& tx, vtx)
1849 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1851 uint256 hash = GetHash();
1853 if (!txdb.TxnBegin())
1854 return error("SetBestChain() : TxnBegin failed");
1856 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1858 txdb.WriteHashBestChain(hash);
1859 if (!txdb.TxnCommit())
1860 return error("SetBestChain() : TxnCommit failed");
1861 pindexGenesisBlock = pindexNew;
1863 else if (hashPrevBlock == hashBestChain)
1865 if (!SetBestChainInner(txdb, pindexNew))
1866 return error("SetBestChain() : SetBestChainInner failed");
1870 // the first block in the new chain that will cause it to become the new best chain
1871 CBlockIndex *pindexIntermediate = pindexNew;
1873 // list of blocks that need to be connected afterwards
1874 std::vector<CBlockIndex*> vpindexSecondary;
1876 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1877 // Try to limit how much needs to be done inside
1878 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1880 vpindexSecondary.push_back(pindexIntermediate);
1881 pindexIntermediate = pindexIntermediate->pprev;
1884 if (!vpindexSecondary.empty())
1885 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1887 // Switch to new best branch
1888 if (!Reorganize(txdb, pindexIntermediate))
1891 InvalidChainFound(pindexNew);
1892 return error("SetBestChain() : Reorganize failed");
1895 // Connect further blocks
1896 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1899 if (!block.ReadFromDisk(pindex))
1901 printf("SetBestChain() : ReadFromDisk failed\n");
1904 if (!txdb.TxnBegin()) {
1905 printf("SetBestChain() : TxnBegin 2 failed\n");
1908 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1909 if (!block.SetBestChainInner(txdb, pindex))
1914 // Update best block in wallet (so we can detect restored wallets)
1915 bool fIsInitialDownload = IsInitialBlockDownload();
1916 if (!fIsInitialDownload)
1918 const CBlockLocator locator(pindexNew);
1919 ::SetBestChain(locator);
1923 hashBestChain = hash;
1924 pindexBest = pindexNew;
1925 pblockindexFBBHLast = NULL;
1926 nBestHeight = pindexBest->nHeight;
1927 nBestChainTrust = pindexNew->nChainTrust;
1928 nTimeBestReceived = GetTime();
1929 nTransactionsUpdated++;
1931 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1933 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1934 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1935 CBigNum(nBestChainTrust).ToString().c_str(),
1936 nBestBlockTrust.Get64(),
1937 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1939 // Check the version of the last 100 blocks to see if we need to upgrade:
1940 if (!fIsInitialDownload)
1943 const CBlockIndex* pindex = pindexBest;
1944 for (int i = 0; i < 100 && pindex != NULL; i++)
1946 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1948 pindex = pindex->pprev;
1951 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1952 if (nUpgraded > 100/2)
1953 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1954 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1957 std::string strCmd = GetArg("-blocknotify", "");
1959 if (!fIsInitialDownload && !strCmd.empty())
1961 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1962 boost::thread t(runCommand, strCmd); // thread runs free
1968 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1969 // Only those coins meeting minimum age requirement counts. As those
1970 // transactions not in main chain are not currently indexed so we
1971 // might not find out about their coin age. Older transactions are
1972 // guaranteed to be in main chain by sync-checkpoint. This rule is
1973 // introduced to help nodes establish a consistent view of the coin
1974 // age (trust score) of competing branches.
1975 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1977 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1983 BOOST_FOREACH(const CTxIn& txin, vin)
1985 // First try finding the previous transaction in database
1986 CTransaction txPrev;
1988 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1989 continue; // previous transaction not in main chain
1990 if (nTime < txPrev.nTime)
1991 return false; // Transaction timestamp violation
1993 // Read block header
1995 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1996 return false; // unable to read block of previous transaction
1997 if (block.GetBlockTime() + nStakeMinAge > nTime)
1998 continue; // only count coins meeting min age requirement
2000 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2001 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2003 if (fDebug && GetBoolArg("-printcoinage"))
2004 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2007 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
2008 if (fDebug && GetBoolArg("-printcoinage"))
2009 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2010 nCoinAge = bnCoinDay.getuint64();
2014 // ppcoin: total coin age spent in block, in the unit of coin-days.
2015 bool CBlock::GetCoinAge(uint64& nCoinAge) const
2020 BOOST_FOREACH(const CTransaction& tx, vtx)
2023 if (tx.GetCoinAge(txdb, nTxCoinAge))
2024 nCoinAge += nTxCoinAge;
2029 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2031 if (fDebug && GetBoolArg("-printcoinage"))
2032 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
2036 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2038 // Check for duplicate
2039 uint256 hash = GetHash();
2040 if (mapBlockIndex.count(hash))
2041 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2043 // Construct new block index object
2044 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
2046 return error("AddToBlockIndex() : new CBlockIndex failed");
2047 pindexNew->phashBlock = &hash;
2048 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2049 if (miPrev != mapBlockIndex.end())
2051 pindexNew->pprev = (*miPrev).second;
2052 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2055 // ppcoin: compute chain trust score
2056 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2058 // ppcoin: compute stake entropy bit for stake modifier
2059 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2060 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2062 // ppcoin: record proof-of-stake hash value
2063 if (pindexNew->IsProofOfStake())
2065 if (!mapProofOfStake.count(hash))
2066 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2067 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2070 // ppcoin: compute stake modifier
2071 uint64 nStakeModifier = 0;
2072 bool fGeneratedStakeModifier = false;
2073 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2074 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2075 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2076 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2077 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2078 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2080 // Add to mapBlockIndex
2081 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2082 if (pindexNew->IsProofOfStake())
2083 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2084 pindexNew->phashBlock = &((*mi).first);
2086 // Write to disk block index
2088 if (!txdb.TxnBegin())
2090 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2091 if (!txdb.TxnCommit())
2095 if (pindexNew->nChainTrust > nBestChainTrust)
2096 if (!SetBestChain(txdb, pindexNew))
2099 if (pindexNew == pindexBest)
2101 // Notify UI to display prev block's coinbase if it was ours
2102 static uint256 hashPrevBestCoinBase;
2103 UpdatedTransaction(hashPrevBestCoinBase);
2104 hashPrevBestCoinBase = vtx[0].GetHash();
2107 uiInterface.NotifyBlocksChanged();
2114 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2116 // These are checks that are independent of context
2117 // that can be verified before saving an orphan block.
2120 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2121 return DoS(100, error("CheckBlock() : size limits failed"));
2123 // Check proof of work matches claimed amount
2124 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2125 return DoS(50, error("CheckBlock() : proof of work failed"));
2128 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
2129 return error("CheckBlock() : block timestamp too far in the future");
2131 // First transaction must be coinbase, the rest must not be
2132 if (vtx.empty() || !vtx[0].IsCoinBase())
2133 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2134 for (unsigned int i = 1; i < vtx.size(); i++)
2135 if (vtx[i].IsCoinBase())
2136 return DoS(100, error("CheckBlock() : more than one coinbase"));
2138 // Check coinbase timestamp
2139 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
2140 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2142 if (IsProofOfStake())
2144 // Coinbase output should be empty if proof-of-stake block
2145 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2146 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2148 // Second transaction must be coinstake, the rest must not be
2149 if (vtx.empty() || !vtx[1].IsCoinStake())
2150 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2151 for (unsigned int i = 2; i < vtx.size(); i++)
2152 if (vtx[i].IsCoinStake())
2153 return DoS(100, error("CheckBlock() : more than one coinstake"));
2155 // Check coinstake timestamp
2156 if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2157 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2159 // NovaCoin: check proof-of-stake block signature
2160 if (fCheckSig && !CheckBlockSignature(true))
2161 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2165 // Coinbase fee paid until 20 Sep 2013
2166 int64 nFee = GetBlockTime() < CHAINCHECKS_SWITCH_TIME ? vtx[0].GetMinFee() - MIN_TX_FEE : 0;
2168 // Check coinbase reward
2169 if (vtx[0].GetValueOut() > (GetProofOfWorkReward(nBits) - nFee))
2170 return DoS(50, error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
2171 vtx[0].GetValueOut(),
2172 GetProofOfWorkReward(nBits) - nFee));
2174 // Should we check proof-of-work block signature or not?
2176 // * Always skip on TestNet
2177 // * Perform checking for the first 9689 blocks
2178 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2180 if(!fTestNet && fCheckSig)
2182 bool isAfterCheckpoint = (GetBlockTime() > Checkpoints::GetLastCheckpointTime());
2183 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2184 bool checkPoWSig = (isAfterCheckpoint && GetBlockTime() < CHAINCHECKS_SWITCH_TIME);
2186 // NovaCoin: check proof-of-work block signature
2187 if ((checkEntropySig || checkPoWSig) && !CheckBlockSignature(false))
2188 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2192 // Check transactions
2193 BOOST_FOREACH(const CTransaction& tx, vtx)
2195 if (!tx.CheckTransaction())
2196 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2198 // ppcoin: check transaction timestamp
2199 if (GetBlockTime() < (int64)tx.nTime)
2200 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2203 // Check for duplicate txids. This is caught by ConnectInputs(),
2204 // but catching it earlier avoids a potential DoS attack:
2205 set<uint256> uniqueTx;
2206 BOOST_FOREACH(const CTransaction& tx, vtx)
2208 uniqueTx.insert(tx.GetHash());
2210 if (uniqueTx.size() != vtx.size())
2211 return DoS(100, error("CheckBlock() : duplicate transaction"));
2213 unsigned int nSigOps = 0;
2214 BOOST_FOREACH(const CTransaction& tx, vtx)
2216 nSigOps += tx.GetLegacySigOpCount();
2218 if (nSigOps > MAX_BLOCK_SIGOPS)
2219 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2221 // Check merkle root
2222 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2223 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2229 bool CBlock::AcceptBlock()
2231 // Check for duplicate
2232 uint256 hash = GetHash();
2233 if (mapBlockIndex.count(hash))
2234 return error("AcceptBlock() : block already in mapBlockIndex");
2236 // Get prev block index
2237 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2238 if (mi == mapBlockIndex.end())
2239 return DoS(10, error("AcceptBlock() : prev block not found"));
2240 CBlockIndex* pindexPrev = (*mi).second;
2241 int nHeight = pindexPrev->nHeight+1;
2243 // Check proof-of-work or proof-of-stake
2244 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2245 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2247 // Check timestamp against prev
2248 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
2249 return error("AcceptBlock() : block's timestamp is too early");
2251 // Check that all transactions are finalized
2252 BOOST_FOREACH(const CTransaction& tx, vtx)
2253 if (!tx.IsFinal(nHeight, GetBlockTime()))
2254 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2256 // Check that the block chain matches the known block chain up to a checkpoint
2257 if (!Checkpoints::CheckHardened(nHeight, hash))
2258 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2260 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2262 // Check that the block satisfies synchronized checkpoint
2263 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2264 return error("AcceptBlock() : rejected by synchronized checkpoint");
2266 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2267 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2269 // Enforce rule that the coinbase starts with serialized block height
2270 CScript expect = CScript() << nHeight;
2271 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2272 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2273 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2275 // Write block to history file
2276 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2277 return error("AcceptBlock() : out of disk space");
2278 unsigned int nFile = -1;
2279 unsigned int nBlockPos = 0;
2280 if (!WriteToDisk(nFile, nBlockPos))
2281 return error("AcceptBlock() : WriteToDisk failed");
2282 if (!AddToBlockIndex(nFile, nBlockPos))
2283 return error("AcceptBlock() : AddToBlockIndex failed");
2285 // Relay inventory, but don't relay old inventory during initial block download
2286 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2287 if (hashBestChain == hash)
2290 BOOST_FOREACH(CNode* pnode, vNodes)
2291 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2292 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2295 // ppcoin: check pending sync-checkpoint
2296 Checkpoints::AcceptPendingSyncCheckpoint();
2301 uint256 CBlockIndex::GetBlockTrust() const
2304 bnTarget.SetCompact(nBits);
2309 /* Old protocol, will be removed later */
2310 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2311 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2315 // Calculate work amount for block
2316 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2318 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2319 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2321 // Return nPoWTrust for the first 12 blocks
2322 if (pprev == NULL || pprev->nHeight < 12)
2325 const CBlockIndex* currentIndex = pprev;
2327 if(IsProofOfStake())
2329 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2331 // Return 1/3 of score if parent block is not the PoW block
2332 if (!pprev->IsProofOfWork())
2333 return (bnNewTrust / 3).getuint256();
2337 // Check last 12 blocks type
2338 while (pprev->nHeight - currentIndex->nHeight < 12)
2340 if (currentIndex->IsProofOfWork())
2342 currentIndex = currentIndex->pprev;
2345 // Return 1/3 of score if less than 3 PoW blocks found
2347 return (bnNewTrust / 3).getuint256();
2349 return bnNewTrust.getuint256();
2353 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2355 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2356 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2357 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2361 // Check last 12 blocks type
2362 while (pprev->nHeight - currentIndex->nHeight < 12)
2364 if (currentIndex->IsProofOfStake())
2366 currentIndex = currentIndex->pprev;
2369 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2371 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2373 bnTarget.SetCompact(pprev->nBits);
2378 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2380 // Return nPoWTrust + full trust score for previous block nBits
2381 return nPoWTrust + bnNewTrust.getuint256();
2385 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2387 unsigned int nFound = 0;
2388 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2390 if (pstart->nVersion >= minVersion)
2392 pstart = pstart->pprev;
2394 return (nFound >= nRequired);
2397 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2399 // Check for duplicate
2400 uint256 hash = pblock->GetHash();
2401 if (mapBlockIndex.count(hash))
2402 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2403 if (mapOrphanBlocks.count(hash))
2404 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2406 // ppcoin: check proof-of-stake
2407 // Limited duplicity on stake: prevents block flood attack
2408 // Duplicate stake allowed only when there is orphan child block
2409 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2410 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
2412 // Preliminary checks
2413 if (!pblock->CheckBlock())
2414 return error("ProcessBlock() : CheckBlock FAILED");
2416 // ppcoin: verify hash target and signature of coinstake tx
2417 if (pblock->IsProofOfStake())
2419 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2420 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2422 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2423 return false; // do not error here as we expect this during initial block download
2425 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2426 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2429 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2430 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2432 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2433 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2435 bnNewBlock.SetCompact(pblock->nBits);
2438 if (pblock->IsProofOfStake())
2439 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2441 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2443 if (bnNewBlock > bnRequired)
2446 pfrom->Misbehaving(100);
2447 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2451 // ppcoin: ask for pending sync-checkpoint if any
2452 if (!IsInitialBlockDownload())
2453 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2455 // If don't already have its previous block, shunt it off to holding area until we get it
2456 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2458 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2459 CBlock* pblock2 = new CBlock(*pblock);
2460 // ppcoin: check proof-of-stake
2461 if (pblock2->IsProofOfStake())
2463 // Limited duplicity on stake: prevents block flood attack
2464 // Duplicate stake allowed only when there is orphan child block
2465 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2466 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock2->GetProofOfStake().first.ToString().c_str(), pblock2->GetProofOfStake().second, hash.ToString().c_str());
2468 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2470 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2471 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2473 // Ask this guy to fill in what we're missing
2476 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2477 // ppcoin: getblocks may not obtain the ancestor block rejected
2478 // earlier by duplicate-stake check so we ask for it again directly
2479 if (!IsInitialBlockDownload())
2480 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2486 if (!pblock->AcceptBlock())
2487 return error("ProcessBlock() : AcceptBlock FAILED");
2489 // Recursively process any orphan blocks that depended on this one
2490 vector<uint256> vWorkQueue;
2491 vWorkQueue.push_back(hash);
2492 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2494 uint256 hashPrev = vWorkQueue[i];
2495 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2496 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2499 CBlock* pblockOrphan = (*mi).second;
2500 if (pblockOrphan->AcceptBlock())
2501 vWorkQueue.push_back(pblockOrphan->GetHash());
2502 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2503 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2504 delete pblockOrphan;
2506 mapOrphanBlocksByPrev.erase(hashPrev);
2509 printf("ProcessBlock: ACCEPTED\n");
2511 // ppcoin: if responsible for sync-checkpoint send it
2512 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2513 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2518 // ppcoin: sign block
2519 bool CBlock::SignBlock(const CKeyStore& keystore)
2521 vector<valtype> vSolutions;
2522 txnouttype whichType;
2524 if(!IsProofOfStake())
2526 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2528 const CTxOut& txout = vtx[0].vout[i];
2530 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2533 if (whichType == TX_PUBKEY)
2536 valtype& vchPubKey = vSolutions[0];
2539 if (!keystore.GetKey(Hash160(vchPubKey), key))
2541 if (key.GetPubKey() != vchPubKey)
2543 if(!key.Sign(GetHash(), vchBlockSig))
2552 const CTxOut& txout = vtx[1].vout[1];
2554 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2557 if (whichType == TX_PUBKEY)
2560 valtype& vchPubKey = vSolutions[0];
2563 if (!keystore.GetKey(Hash160(vchPubKey), key))
2565 if (key.GetPubKey() != vchPubKey)
2568 return key.Sign(GetHash(), vchBlockSig);
2572 printf("Sign failed\n");
2576 // ppcoin: check block signature
2577 bool CBlock::CheckBlockSignature(bool fProofOfStake) const
2579 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2580 return vchBlockSig.empty();
2582 vector<valtype> vSolutions;
2583 txnouttype whichType;
2587 const CTxOut& txout = vtx[1].vout[1];
2589 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2591 if (whichType == TX_PUBKEY)
2593 valtype& vchPubKey = vSolutions[0];
2595 if (!key.SetPubKey(vchPubKey))
2597 if (vchBlockSig.empty())
2599 return key.Verify(GetHash(), vchBlockSig);
2604 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2606 const CTxOut& txout = vtx[0].vout[i];
2608 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2611 if (whichType == TX_PUBKEY)
2614 valtype& vchPubKey = vSolutions[0];
2616 if (!key.SetPubKey(vchPubKey))
2618 if (vchBlockSig.empty())
2620 if(!key.Verify(GetHash(), vchBlockSig))
2630 bool CheckDiskSpace(uint64 nAdditionalBytes)
2632 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2634 // Check for nMinDiskSpace bytes (currently 50MB)
2635 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2638 string strMessage = _("Warning: Disk space is low!");
2639 strMiscWarning = strMessage;
2640 printf("*** %s\n", strMessage.c_str());
2641 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2648 static filesystem::path BlockFilePath(unsigned int nFile)
2650 string strBlockFn = strprintf("blk%04u.dat", nFile);
2651 return GetDataDir() / strBlockFn;
2654 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2656 if ((nFile < 1) || (nFile == (unsigned int) -1))
2658 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2661 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2663 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2672 static unsigned int nCurrentBlockFile = 1;
2674 FILE* AppendBlockFile(unsigned int& nFileRet)
2679 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2682 if (fseek(file, 0, SEEK_END) != 0)
2684 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2685 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2687 nFileRet = nCurrentBlockFile;
2691 nCurrentBlockFile++;
2695 bool LoadBlockIndex(bool fAllowNew)
2699 pchMessageStart[0] = 0xcd;
2700 pchMessageStart[1] = 0xf2;
2701 pchMessageStart[2] = 0xc0;
2702 pchMessageStart[3] = 0xef;
2704 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2705 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2706 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2707 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2708 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2715 if (!txdb.LoadBlockIndex())
2720 // Init with genesis block
2722 if (mapBlockIndex.empty())
2731 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2732 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2733 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2735 // vMerkleTree: 4cb33b3b6a
2739 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2740 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2741 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2743 // vMerkleTree: 4cb33b3b6a
2745 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2747 txNew.nTime = 1360105017;
2748 txNew.vin.resize(1);
2749 txNew.vout.resize(1);
2750 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2751 txNew.vout[0].SetEmpty();
2753 block.vtx.push_back(txNew);
2754 block.hashPrevBlock = 0;
2755 block.hashMerkleRoot = block.BuildMerkleTree();
2757 block.nTime = 1360105017;
2758 block.nBits = bnProofOfWorkLimit.GetCompact();
2759 block.nNonce = !fTestNet ? 1575379 : 46534;
2762 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2764 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2765 assert(block.CheckBlock());
2767 // Start new block file
2769 unsigned int nBlockPos;
2770 if (!block.WriteToDisk(nFile, nBlockPos))
2771 return error("LoadBlockIndex() : writing genesis block to disk failed");
2772 if (!block.AddToBlockIndex(nFile, nBlockPos))
2773 return error("LoadBlockIndex() : genesis block not accepted");
2775 // ppcoin: initialize synchronized checkpoint
2776 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2777 return error("LoadBlockIndex() : failed to init sync checkpoint");
2780 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2783 string strPubKey = "";
2784 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2786 // write checkpoint master key to db
2788 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2789 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2790 if (!txdb.TxnCommit())
2791 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2792 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2793 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2806 void PrintBlockTree()
2808 // pre-compute tree structure
2809 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2810 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2812 CBlockIndex* pindex = (*mi).second;
2813 mapNext[pindex->pprev].push_back(pindex);
2815 //while (rand() % 3 == 0)
2816 // mapNext[pindex->pprev].push_back(pindex);
2819 vector<pair<int, CBlockIndex*> > vStack;
2820 vStack.push_back(make_pair(0, pindexGenesisBlock));
2823 while (!vStack.empty())
2825 int nCol = vStack.back().first;
2826 CBlockIndex* pindex = vStack.back().second;
2829 // print split or gap
2830 if (nCol > nPrevCol)
2832 for (int i = 0; i < nCol-1; i++)
2836 else if (nCol < nPrevCol)
2838 for (int i = 0; i < nCol; i++)
2845 for (int i = 0; i < nCol; i++)
2850 block.ReadFromDisk(pindex);
2851 printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
2855 block.GetHash().ToString().c_str(),
2857 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2858 FormatMoney(pindex->nMint).c_str(),
2861 PrintWallets(block);
2863 // put the main time-chain first
2864 vector<CBlockIndex*>& vNext = mapNext[pindex];
2865 for (unsigned int i = 0; i < vNext.size(); i++)
2867 if (vNext[i]->pnext)
2869 swap(vNext[0], vNext[i]);
2875 for (unsigned int i = 0; i < vNext.size(); i++)
2876 vStack.push_back(make_pair(nCol+i, vNext[i]));
2880 bool LoadExternalBlockFile(FILE* fileIn)
2882 int64 nStart = GetTimeMillis();
2888 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2889 unsigned int nPos = 0;
2890 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2892 unsigned char pchData[65536];
2894 fseek(blkdat, nPos, SEEK_SET);
2895 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2898 nPos = (unsigned int)-1;
2901 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2904 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2906 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2909 nPos += ((unsigned char*)nFind - pchData) + 1;
2912 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2913 } while(!fRequestShutdown);
2914 if (nPos == (unsigned int)-1)
2916 fseek(blkdat, nPos, SEEK_SET);
2919 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2923 if (ProcessBlock(NULL,&block))
2931 catch (std::exception &e) {
2932 printf("%s() : Deserialize or I/O error caught during load\n",
2933 __PRETTY_FUNCTION__);
2936 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2940 //////////////////////////////////////////////////////////////////////////////
2945 extern map<uint256, CAlert> mapAlerts;
2946 extern CCriticalSection cs_mapAlerts;
2948 extern string strMintMessage;
2949 extern string strMintWarning;
2951 string GetWarnings(string strFor)
2954 string strStatusBar;
2957 if (GetBoolArg("-testsafemode"))
2960 // ppcoin: wallet lock warning for minting
2961 if (strMintWarning != "")
2964 strStatusBar = strMintWarning;
2967 // Misc warnings like out of disk space and clock is wrong
2968 if (strMiscWarning != "")
2971 strStatusBar = strMiscWarning;
2974 // * Should not enter safe mode for longer invalid chain
2975 // * If sync-checkpoint is too old do not enter safe mode
2976 // * Display warning only in the STRICT mode
2977 if (CheckpointsMode == Checkpoints::STRICT && Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) &&
2978 !fTestNet && !IsInitialBlockDownload())
2981 strStatusBar = _("WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.");
2984 // ppcoin: if detected invalid checkpoint enter safe mode
2985 if (Checkpoints::hashInvalidCheckpoint != 0)
2988 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
2994 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2996 const CAlert& alert = item.second;
2997 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2999 nPriority = alert.nPriority;
3000 strStatusBar = alert.strStatusBar;
3001 if (nPriority > 1000)
3002 strRPC = strStatusBar;
3007 if (strFor == "statusbar")
3008 return strStatusBar;
3009 else if (strFor == "rpc")
3011 assert(!"GetWarnings() : invalid parameter");
3022 //////////////////////////////////////////////////////////////////////////////
3028 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3034 bool txInMap = false;
3037 txInMap = (mempool.exists(inv.hash));
3040 mapOrphanTransactions.count(inv.hash) ||
3041 txdb.ContainsTx(inv.hash);
3045 return mapBlockIndex.count(inv.hash) ||
3046 mapOrphanBlocks.count(inv.hash);
3048 // Don't know what it is, just say we already got one
3055 // The message start string is designed to be unlikely to occur in normal data.
3056 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3057 // a large 4-byte int at any alignment.
3058 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3060 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3062 static map<CService, CPubKey> mapReuseKey;
3063 RandAddSeedPerfmon();
3065 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3066 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3068 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3076 if (strCommand == "version")
3078 // Each connection can only send one version message
3079 if (pfrom->nVersion != 0)
3081 pfrom->Misbehaving(1);
3089 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3090 if (pfrom->nVersion < MIN_PROTO_VERSION)
3092 // Since February 20, 2012, the protocol is initiated at version 209,
3093 // and earlier versions are no longer supported
3094 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3095 pfrom->fDisconnect = true;
3099 if (pfrom->nVersion == 10300)
3100 pfrom->nVersion = 300;
3102 vRecv >> addrFrom >> nNonce;
3104 vRecv >> pfrom->strSubVer;
3106 vRecv >> pfrom->nStartingHeight;
3108 if (pfrom->fInbound && addrMe.IsRoutable())
3110 pfrom->addrLocal = addrMe;
3114 // Disconnect if we connected to ourself
3115 if (nNonce == nLocalHostNonce && nNonce > 1)
3117 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3118 pfrom->fDisconnect = true;
3122 // ppcoin: record my external IP reported by peer
3123 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3124 addrSeenByPeer = addrMe;
3126 // Be shy and don't send version until we hear
3127 if (pfrom->fInbound)
3128 pfrom->PushVersion();
3130 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3132 AddTimeData(pfrom->addr, nTime);
3135 pfrom->PushMessage("verack");
3136 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3138 if (!pfrom->fInbound)
3140 // Advertise our address
3141 if (!fNoListen && !IsInitialBlockDownload())
3143 CAddress addr = GetLocalAddress(&pfrom->addr);
3144 if (addr.IsRoutable())
3145 pfrom->PushAddress(addr);
3148 // Get recent addresses
3149 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3151 pfrom->PushMessage("getaddr");
3152 pfrom->fGetAddr = true;
3154 addrman.Good(pfrom->addr);
3156 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3158 addrman.Add(addrFrom, addrFrom);
3159 addrman.Good(addrFrom);
3163 // Ask the first connected node for block updates
3164 static int nAskedForBlocks = 0;
3165 if (!pfrom->fClient && !pfrom->fOneShot &&
3166 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3167 (pfrom->nVersion < NOBLKS_VERSION_START ||
3168 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3169 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3172 pfrom->PushGetBlocks(pindexBest, uint256(0));
3178 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3179 item.second.RelayTo(pfrom);
3182 // ppcoin: relay sync-checkpoint
3184 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3185 if (!Checkpoints::checkpointMessage.IsNull())
3186 Checkpoints::checkpointMessage.RelayTo(pfrom);
3189 pfrom->fSuccessfullyConnected = true;
3191 printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
3193 cPeerBlockCounts.input(pfrom->nStartingHeight);
3195 // ppcoin: ask for pending sync-checkpoint if any
3196 if (!IsInitialBlockDownload())
3197 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3201 else if (pfrom->nVersion == 0)
3203 // Must have a version message before anything else
3204 pfrom->Misbehaving(1);
3209 else if (strCommand == "verack")
3211 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3215 else if (strCommand == "addr")
3217 vector<CAddress> vAddr;
3220 // Don't want addr from older versions unless seeding
3221 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3223 if (vAddr.size() > 1000)
3225 pfrom->Misbehaving(20);
3226 return error("message addr size() = %"PRIszu"", vAddr.size());
3229 // Store the new addresses
3230 vector<CAddress> vAddrOk;
3231 int64 nNow = GetAdjustedTime();
3232 int64 nSince = nNow - 10 * 60;
3233 BOOST_FOREACH(CAddress& addr, vAddr)
3237 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3238 addr.nTime = nNow - 5 * 24 * 60 * 60;
3239 pfrom->AddAddressKnown(addr);
3240 bool fReachable = IsReachable(addr);
3241 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3243 // Relay to a limited number of other nodes
3246 // Use deterministic randomness to send to the same nodes for 24 hours
3247 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3248 static uint256 hashSalt;
3250 hashSalt = GetRandHash();
3251 uint64 hashAddr = addr.GetHash();
3252 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3253 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3254 multimap<uint256, CNode*> mapMix;
3255 BOOST_FOREACH(CNode* pnode, vNodes)
3257 if (pnode->nVersion < CADDR_TIME_VERSION)
3259 unsigned int nPointer;
3260 memcpy(&nPointer, &pnode, sizeof(nPointer));
3261 uint256 hashKey = hashRand ^ nPointer;
3262 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3263 mapMix.insert(make_pair(hashKey, pnode));
3265 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3266 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3267 ((*mi).second)->PushAddress(addr);
3270 // Do not store addresses outside our network
3272 vAddrOk.push_back(addr);
3274 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3275 if (vAddr.size() < 1000)
3276 pfrom->fGetAddr = false;
3277 if (pfrom->fOneShot)
3278 pfrom->fDisconnect = true;
3282 else if (strCommand == "inv")
3286 if (vInv.size() > MAX_INV_SZ)
3288 pfrom->Misbehaving(20);
3289 return error("message inv size() = %"PRIszu"", vInv.size());
3292 // find last block in inv vector
3293 unsigned int nLastBlock = (unsigned int)(-1);
3294 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3295 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3296 nLastBlock = vInv.size() - 1 - nInv;
3301 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3303 const CInv &inv = vInv[nInv];
3307 pfrom->AddInventoryKnown(inv);
3309 bool fAlreadyHave = AlreadyHave(txdb, inv);
3311 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3315 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3316 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3317 } else if (nInv == nLastBlock) {
3318 // In case we are on a very long side-chain, it is possible that we already have
3319 // the last block in an inv bundle sent in response to getblocks. Try to detect
3320 // this situation and push another getblocks to continue.
3321 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3323 printf("force request: %s\n", inv.ToString().c_str());
3326 // Track requests for our stuff
3327 Inventory(inv.hash);
3332 else if (strCommand == "getdata")
3336 if (vInv.size() > MAX_INV_SZ)
3338 pfrom->Misbehaving(20);
3339 return error("message getdata size() = %"PRIszu"", vInv.size());
3342 if (fDebugNet || (vInv.size() != 1))
3343 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3345 BOOST_FOREACH(const CInv& inv, vInv)
3349 if (fDebugNet || (vInv.size() == 1))
3350 printf("received getdata for: %s\n", inv.ToString().c_str());
3352 if (inv.type == MSG_BLOCK)
3354 // Send block from disk
3355 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3356 if (mi != mapBlockIndex.end())
3359 block.ReadFromDisk((*mi).second);
3360 pfrom->PushMessage("block", block);
3362 // Trigger them to send a getblocks request for the next batch of inventory
3363 if (inv.hash == pfrom->hashContinue)
3365 // ppcoin: send latest proof-of-work block to allow the
3366 // download node to accept as orphan (proof-of-stake
3367 // block might be rejected by stake connection check)
3369 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3370 pfrom->PushMessage("inv", vInv);
3371 pfrom->hashContinue = 0;
3375 else if (inv.IsKnownType())
3377 // Send stream from relay memory
3378 bool pushed = false;
3381 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3382 if (mi != mapRelay.end()) {
3383 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3387 if (!pushed && inv.type == MSG_TX) {
3389 if (mempool.exists(inv.hash)) {
3390 CTransaction tx = mempool.lookup(inv.hash);
3391 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3394 pfrom->PushMessage("tx", ss);
3399 // Track requests for our stuff
3400 Inventory(inv.hash);
3405 else if (strCommand == "getblocks")
3407 CBlockLocator locator;
3409 vRecv >> locator >> hashStop;
3411 // Find the last block the caller has in the main chain
3412 CBlockIndex* pindex = locator.GetBlockIndex();
3414 // Send the rest of the chain
3416 pindex = pindex->pnext;
3418 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3419 for (; pindex; pindex = pindex->pnext)
3421 if (pindex->GetBlockHash() == hashStop)
3423 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3424 // ppcoin: tell downloading node about the latest block if it's
3425 // without risk being rejected due to stake connection check
3426 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3427 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3430 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3433 // When this block is requested, we'll send an inv that'll make them
3434 // getblocks the next batch of inventory.
3435 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3436 pfrom->hashContinue = pindex->GetBlockHash();
3441 else if (strCommand == "checkpoint")
3443 CSyncCheckpoint checkpoint;
3444 vRecv >> checkpoint;
3446 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3449 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3451 BOOST_FOREACH(CNode* pnode, vNodes)
3452 checkpoint.RelayTo(pnode);
3456 else if (strCommand == "getheaders")
3458 CBlockLocator locator;
3460 vRecv >> locator >> hashStop;
3462 CBlockIndex* pindex = NULL;
3463 if (locator.IsNull())
3465 // If locator is null, return the hashStop block
3466 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3467 if (mi == mapBlockIndex.end())
3469 pindex = (*mi).second;
3473 // Find the last block the caller has in the main chain
3474 pindex = locator.GetBlockIndex();
3476 pindex = pindex->pnext;
3479 vector<CBlock> vHeaders;
3481 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3482 for (; pindex; pindex = pindex->pnext)
3484 vHeaders.push_back(pindex->GetBlockHeader());
3485 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3488 pfrom->PushMessage("headers", vHeaders);
3492 else if (strCommand == "tx")
3494 vector<uint256> vWorkQueue;
3495 vector<uint256> vEraseQueue;
3496 CDataStream vMsg(vRecv);
3501 CInv inv(MSG_TX, tx.GetHash());
3502 pfrom->AddInventoryKnown(inv);
3504 // Truncate messages to the size of the tx in them
3505 unsigned int nSize = ::GetSerializeSize(tx,SER_NETWORK, PROTOCOL_VERSION);
3506 if (nSize < vMsg.size()){
3510 bool fMissingInputs = false;
3511 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3513 SyncWithWallets(tx, NULL, true);
3514 RelayMessage(inv, vMsg);
3515 mapAlreadyAskedFor.erase(inv);
3516 vWorkQueue.push_back(inv.hash);
3517 vEraseQueue.push_back(inv.hash);
3519 // Recursively process any orphan transactions that depended on this one
3520 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3522 uint256 hashPrev = vWorkQueue[i];
3523 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3524 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3527 const CDataStream& vMsg = *((*mi).second);
3529 CDataStream(vMsg) >> tx;
3530 CInv inv(MSG_TX, tx.GetHash());
3531 bool fMissingInputs2 = false;
3533 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3535 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3536 SyncWithWallets(tx, NULL, true);
3537 RelayMessage(inv, vMsg);
3538 mapAlreadyAskedFor.erase(inv);
3539 vWorkQueue.push_back(inv.hash);
3540 vEraseQueue.push_back(inv.hash);
3542 else if (!fMissingInputs2)
3545 vEraseQueue.push_back(inv.hash);
3546 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3551 BOOST_FOREACH(uint256 hash, vEraseQueue)
3552 EraseOrphanTx(hash);
3554 else if (fMissingInputs)
3558 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3559 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3561 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3563 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3567 else if (strCommand == "block")
3571 uint256 hashBlock = block.GetHash();
3573 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3576 CInv inv(MSG_BLOCK, hashBlock);
3577 pfrom->AddInventoryKnown(inv);
3579 if (ProcessBlock(pfrom, &block))
3580 mapAlreadyAskedFor.erase(inv);
3581 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3585 else if (strCommand == "getaddr")
3587 // Don't return addresses older than nCutOff timestamp
3588 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3589 pfrom->vAddrToSend.clear();
3590 vector<CAddress> vAddr = addrman.GetAddr();
3591 BOOST_FOREACH(const CAddress &addr, vAddr)
3592 if(addr.nTime > nCutOff)
3593 pfrom->PushAddress(addr);
3597 else if (strCommand == "mempool")
3599 std::vector<uint256> vtxid;
3600 mempool.queryHashes(vtxid);
3602 for (unsigned int i = 0; i < vtxid.size(); i++) {
3603 CInv inv(MSG_TX, vtxid[i]);
3604 vInv.push_back(inv);
3605 if (i == (MAX_INV_SZ - 1))
3608 if (vInv.size() > 0)
3609 pfrom->PushMessage("inv", vInv);
3613 else if (strCommand == "checkorder")
3618 if (!GetBoolArg("-allowreceivebyip"))
3620 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3627 /// we have a chance to check the order here
3629 // Keep giving the same key to the same ip until they use it
3630 if (!mapReuseKey.count(pfrom->addr))
3631 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3633 // Send back approval of order and pubkey to use
3634 CScript scriptPubKey;
3635 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3636 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3640 else if (strCommand == "reply")
3645 CRequestTracker tracker;
3647 LOCK(pfrom->cs_mapRequests);
3648 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3649 if (mi != pfrom->mapRequests.end())
3651 tracker = (*mi).second;
3652 pfrom->mapRequests.erase(mi);
3655 if (!tracker.IsNull())
3656 tracker.fn(tracker.param1, vRecv);
3660 else if (strCommand == "ping")
3662 if (pfrom->nVersion > BIP0031_VERSION)
3666 // Echo the message back with the nonce. This allows for two useful features:
3668 // 1) A remote node can quickly check if the connection is operational
3669 // 2) Remote nodes can measure the latency of the network thread. If this node
3670 // is overloaded it won't respond to pings quickly and the remote node can
3671 // avoid sending us more work, like chain download requests.
3673 // The nonce stops the remote getting confused between different pings: without
3674 // it, if the remote node sends a ping once per second and this node takes 5
3675 // seconds to respond to each, the 5th ping the remote sends would appear to
3676 // return very quickly.
3677 pfrom->PushMessage("pong", nonce);
3682 else if (strCommand == "alert")
3687 uint256 alertHash = alert.GetHash();
3688 if (pfrom->setKnown.count(alertHash) == 0)
3690 if (alert.ProcessAlert())
3693 pfrom->setKnown.insert(alertHash);
3696 BOOST_FOREACH(CNode* pnode, vNodes)
3697 alert.RelayTo(pnode);
3701 // Small DoS penalty so peers that send us lots of
3702 // duplicate/expired/invalid-signature/whatever alerts
3703 // eventually get banned.
3704 // This isn't a Misbehaving(100) (immediate ban) because the
3705 // peer might be an older or different implementation with
3706 // a different signature key, etc.
3707 pfrom->Misbehaving(10);
3715 // Ignore unknown commands for extensibility
3719 // Update the last seen time for this node's address
3720 if (pfrom->fNetworkNode)
3721 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3722 AddressCurrentlyConnected(pfrom->addr);
3728 bool ProcessMessages(CNode* pfrom)
3730 CDataStream& vRecv = pfrom->vRecv;
3734 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3738 // (4) message start
3747 // Don't bother if send buffer is too full to respond anyway
3748 if (pfrom->vSend.size() >= SendBufferSize())
3751 // Scan for message start
3752 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3753 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3754 if (vRecv.end() - pstart < nHeaderSize)
3756 if ((int)vRecv.size() > nHeaderSize)
3758 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3759 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3763 if (pstart - vRecv.begin() > 0)
3764 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3765 vRecv.erase(vRecv.begin(), pstart);
3768 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3773 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3776 string strCommand = hdr.GetCommand();
3779 unsigned int nMessageSize = hdr.nMessageSize;
3780 if (nMessageSize > MAX_SIZE)
3782 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3785 if (nMessageSize > vRecv.size())
3787 // Rewind and wait for rest of message
3788 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3793 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3794 unsigned int nChecksum = 0;
3795 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3796 if (nChecksum != hdr.nChecksum)
3798 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3799 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3803 // Copy message to its own buffer
3804 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3805 vRecv.ignore(nMessageSize);
3813 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3818 catch (std::ios_base::failure& e)
3820 if (strstr(e.what(), "end of data"))
3822 // Allow exceptions from under-length message on vRecv
3823 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
3825 else if (strstr(e.what(), "size too large"))
3827 // Allow exceptions from over-long size
3828 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3832 PrintExceptionContinue(&e, "ProcessMessages()");
3835 catch (std::exception& e) {
3836 PrintExceptionContinue(&e, "ProcessMessages()");
3838 PrintExceptionContinue(NULL, "ProcessMessages()");
3842 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3850 bool SendMessages(CNode* pto, bool fSendTrickle)
3852 TRY_LOCK(cs_main, lockMain);
3854 // Don't send anything until we get their version message
3855 if (pto->nVersion == 0)
3858 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3860 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3862 if (pto->nVersion > BIP0031_VERSION)
3863 pto->PushMessage("ping", nonce);
3865 pto->PushMessage("ping");
3868 // Resend wallet transactions that haven't gotten in a block yet
3869 ResendWalletTransactions();
3871 // Address refresh broadcast
3872 static int64 nLastRebroadcast;
3873 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3877 BOOST_FOREACH(CNode* pnode, vNodes)
3879 // Periodically clear setAddrKnown to allow refresh broadcasts
3880 if (nLastRebroadcast)
3881 pnode->setAddrKnown.clear();
3883 // Rebroadcast our address
3886 CAddress addr = GetLocalAddress(&pnode->addr);
3887 if (addr.IsRoutable())
3888 pnode->PushAddress(addr);
3892 nLastRebroadcast = GetTime();
3900 vector<CAddress> vAddr;
3901 vAddr.reserve(pto->vAddrToSend.size());
3902 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3904 // returns true if wasn't already contained in the set
3905 if (pto->setAddrKnown.insert(addr).second)
3907 vAddr.push_back(addr);
3908 // receiver rejects addr messages larger than 1000
3909 if (vAddr.size() >= 1000)
3911 pto->PushMessage("addr", vAddr);
3916 pto->vAddrToSend.clear();
3918 pto->PushMessage("addr", vAddr);
3923 // Message: inventory
3926 vector<CInv> vInvWait;
3928 LOCK(pto->cs_inventory);
3929 vInv.reserve(pto->vInventoryToSend.size());
3930 vInvWait.reserve(pto->vInventoryToSend.size());
3931 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3933 if (pto->setInventoryKnown.count(inv))
3936 // trickle out tx inv to protect privacy
3937 if (inv.type == MSG_TX && !fSendTrickle)
3939 // 1/4 of tx invs blast to all immediately
3940 static uint256 hashSalt;
3942 hashSalt = GetRandHash();
3943 uint256 hashRand = inv.hash ^ hashSalt;
3944 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3945 bool fTrickleWait = ((hashRand & 3) != 0);
3947 // always trickle our own transactions
3951 if (GetTransaction(inv.hash, wtx))
3953 fTrickleWait = true;
3958 vInvWait.push_back(inv);
3963 // returns true if wasn't already contained in the set
3964 if (pto->setInventoryKnown.insert(inv).second)
3966 vInv.push_back(inv);
3967 if (vInv.size() >= 1000)
3969 pto->PushMessage("inv", vInv);
3974 pto->vInventoryToSend = vInvWait;
3977 pto->PushMessage("inv", vInv);
3983 vector<CInv> vGetData;
3984 int64 nNow = GetTime() * 1000000;
3986 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3988 const CInv& inv = (*pto->mapAskFor.begin()).second;
3989 if (!AlreadyHave(txdb, inv))
3992 printf("sending getdata: %s\n", inv.ToString().c_str());
3993 vGetData.push_back(inv);
3994 if (vGetData.size() >= 1000)
3996 pto->PushMessage("getdata", vGetData);
3999 mapAlreadyAskedFor[inv] = nNow;
4001 pto->mapAskFor.erase(pto->mapAskFor.begin());
4003 if (!vGetData.empty())
4004 pto->PushMessage("getdata", vGetData);