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"
11 #include "ui_interface.h"
13 #include <boost/algorithm/string/replace.hpp>
14 #include <boost/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
18 using namespace boost;
24 CCriticalSection cs_setpwalletRegistered;
25 set<CWallet*> setpwalletRegistered;
27 CCriticalSection cs_main;
30 unsigned int nTransactionsUpdated = 0;
32 map<uint256, CBlockIndex*> mapBlockIndex;
33 set<pair<COutPoint, unsigned int> > setStakeSeen;
35 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
36 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
37 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
38 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
39 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
41 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
43 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as minimum age for coin age
44 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as stake age of full weight
45 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
46 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
48 int nCoinbaseMaturity = 500;
49 CBlockIndex* pindexGenesisBlock = NULL;
52 uint256 nBestChainTrust = 0;
53 uint256 nBestInvalidTrust = 0;
55 uint256 hashBestChain = 0;
56 CBlockIndex* pindexBest = NULL;
57 int64 nTimeBestReceived = 0;
59 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
61 map<uint256, CBlock*> mapOrphanBlocks;
62 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
63 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
64 map<uint256, uint256> mapProofOfStake;
66 map<uint256, CDataStream*> mapOrphanTransactions;
67 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
69 // Constant stuff for coinbase transactions we create:
70 CScript COINBASE_FLAGS;
72 const string strMessageMagic = "NovaCoin Signed Message:\n";
75 int64 nTransactionFee = MIN_TX_FEE;
76 bool fStakeUsePooledKeys = false;
78 //////////////////////////////////////////////////////////////////////////////
80 // dispatching functions
83 // These functions dispatch to one or all registered wallets
86 void RegisterWallet(CWallet* pwalletIn)
89 LOCK(cs_setpwalletRegistered);
90 setpwalletRegistered.insert(pwalletIn);
94 void UnregisterWallet(CWallet* pwalletIn)
97 LOCK(cs_setpwalletRegistered);
98 setpwalletRegistered.erase(pwalletIn);
102 // check whether the passed transaction is from us
103 bool static IsFromMe(CTransaction& tx)
105 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
106 if (pwallet->IsFromMe(tx))
111 // get the wallet transaction with the given hash (if it exists)
112 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
114 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
115 if (pwallet->GetTransaction(hashTx,wtx))
120 // erases transaction with the given hash from all wallets
121 void static EraseFromWallets(uint256 hash)
123 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
124 pwallet->EraseFromWallet(hash);
127 // make sure all wallets know about the given transaction, in the given block
128 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
132 // ppcoin: wallets need to refund inputs when disconnecting coinstake
133 if (tx.IsCoinStake())
135 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
136 if (pwallet->IsFromMe(tx))
137 pwallet->DisableTransaction(tx);
142 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
143 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
146 // notify wallets about a new best chain
147 void static SetBestChain(const CBlockLocator& loc)
149 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
150 pwallet->SetBestChain(loc);
153 // notify wallets about an updated transaction
154 void static UpdatedTransaction(const uint256& hashTx)
156 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
157 pwallet->UpdatedTransaction(hashTx);
161 void static PrintWallets(const CBlock& block)
163 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
164 pwallet->PrintWallet(block);
167 // notify wallets about an incoming inventory (for request counts)
168 void static Inventory(const uint256& hash)
170 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
171 pwallet->Inventory(hash);
174 // ask wallets to resend their transactions
175 void ResendWalletTransactions()
177 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
178 pwallet->ResendWalletTransactions();
187 //////////////////////////////////////////////////////////////////////////////
189 // mapOrphanTransactions
192 bool AddOrphanTx(const CDataStream& vMsg)
195 CDataStream(vMsg) >> tx;
196 uint256 hash = tx.GetHash();
197 if (mapOrphanTransactions.count(hash))
200 CDataStream* pvMsg = new CDataStream(vMsg);
202 // Ignore big transactions, to avoid a
203 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
204 // large transaction with a missing parent then we assume
205 // it will rebroadcast it later, after the parent transaction(s)
206 // have been mined or received.
207 // 10,000 orphans, each of which is at most 5,000 bytes big is
208 // at most 500 megabytes of orphans:
209 if (pvMsg->size() > 5000)
211 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
216 mapOrphanTransactions[hash] = pvMsg;
217 BOOST_FOREACH(const CTxIn& txin, tx.vin)
218 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
220 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
221 mapOrphanTransactions.size());
225 void static EraseOrphanTx(uint256 hash)
227 if (!mapOrphanTransactions.count(hash))
229 const CDataStream* pvMsg = mapOrphanTransactions[hash];
231 CDataStream(*pvMsg) >> tx;
232 BOOST_FOREACH(const CTxIn& txin, tx.vin)
234 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
235 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
236 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
239 mapOrphanTransactions.erase(hash);
242 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
244 unsigned int nEvicted = 0;
245 while (mapOrphanTransactions.size() > nMaxOrphans)
247 // Evict a random orphan:
248 uint256 randomhash = GetRandHash();
249 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
250 if (it == mapOrphanTransactions.end())
251 it = mapOrphanTransactions.begin();
252 EraseOrphanTx(it->first);
264 //////////////////////////////////////////////////////////////////////////////
266 // CTransaction and CTxIndex
269 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
272 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
274 if (!ReadFromDisk(txindexRet.pos))
276 if (prevout.n >= vout.size())
284 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
287 return ReadFromDisk(txdb, prevout, txindex);
290 bool CTransaction::ReadFromDisk(COutPoint prevout)
294 return ReadFromDisk(txdb, prevout, txindex);
297 bool CTransaction::IsStandard() const
299 if (nVersion > CTransaction::CURRENT_VERSION)
302 BOOST_FOREACH(const CTxIn& txin, vin)
304 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
305 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
306 // ~65-byte public keys, plus a few script ops.
307 if (txin.scriptSig.size() > 500)
309 if (!txin.scriptSig.IsPushOnly())
312 BOOST_FOREACH(const CTxOut& txout, vout) {
313 if (!::IsStandard(txout.scriptPubKey))
315 if (txout.nValue == 0)
322 // Check transaction inputs, and make sure any
323 // pay-to-script-hash transactions are evaluating IsStandard scripts
325 // Why bother? To avoid denial-of-service attacks; an attacker
326 // can submit a standard HASH... OP_EQUAL transaction,
327 // which will get accepted into blocks. The redemption
328 // script can be anything; an attacker could use a very
329 // expensive-to-check-upon-redemption script like:
330 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
332 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
335 return true; // Coinbases don't use vin normally
337 for (unsigned int i = 0; i < vin.size(); i++)
339 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
341 vector<vector<unsigned char> > vSolutions;
342 txnouttype whichType;
343 // get the scriptPubKey corresponding to this input:
344 const CScript& prevScript = prev.scriptPubKey;
345 if (!Solver(prevScript, whichType, vSolutions))
347 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
348 if (nArgsExpected < 0)
351 // Transactions with extra stuff in their scriptSigs are
352 // non-standard. Note that this EvalScript() call will
353 // be quick, because if there are any operations
354 // beside "push data" in the scriptSig the
355 // IsStandard() call returns false
356 vector<vector<unsigned char> > stack;
357 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
360 if (whichType == TX_SCRIPTHASH)
364 CScript subscript(stack.back().begin(), stack.back().end());
365 vector<vector<unsigned char> > vSolutions2;
366 txnouttype whichType2;
367 if (!Solver(subscript, whichType2, vSolutions2))
369 if (whichType2 == TX_SCRIPTHASH)
373 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
376 nArgsExpected += tmpExpected;
379 if (stack.size() != (unsigned int)nArgsExpected)
387 CTransaction::GetLegacySigOpCount() const
389 unsigned int nSigOps = 0;
390 BOOST_FOREACH(const CTxIn& txin, vin)
392 nSigOps += txin.scriptSig.GetSigOpCount(false);
394 BOOST_FOREACH(const CTxOut& txout, vout)
396 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
402 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
414 // Load the block this tx is in
416 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
418 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
423 // Update the tx's hashBlock
424 hashBlock = pblock->GetHash();
426 // Locate the transaction
427 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
428 if (pblock->vtx[nIndex] == *(CTransaction*)this)
430 if (nIndex == (int)pblock->vtx.size())
432 vMerkleBranch.clear();
434 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
438 // Fill in merkle branch
439 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
442 // Is the tx in a block that's in the main chain
443 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
444 if (mi == mapBlockIndex.end())
446 CBlockIndex* pindex = (*mi).second;
447 if (!pindex || !pindex->IsInMainChain())
450 return pindexBest->nHeight - pindex->nHeight + 1;
459 bool CTransaction::CheckTransaction() const
461 // Basic checks that don't depend on any context
463 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
465 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
467 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
468 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
470 // Check for negative or overflow output values
472 for (unsigned int i = 0; i < vout.size(); i++)
474 const CTxOut& txout = vout[i];
475 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
476 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
478 // NovaCoin: enforce minimum output amount for user transactions
479 // (and for all transactions until 20 Sep 2013)
480 if ((!IsCoinBase() || nTime < CHAINCHECKS_SWITCH_TIME)
481 && (!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
482 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
484 if (txout.nValue > MAX_MONEY)
485 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
486 nValueOut += txout.nValue;
487 if (!MoneyRange(nValueOut))
488 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
491 // Check for duplicate inputs
492 set<COutPoint> vInOutPoints;
493 BOOST_FOREACH(const CTxIn& txin, vin)
495 if (vInOutPoints.count(txin.prevout))
497 vInOutPoints.insert(txin.prevout);
502 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
503 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
507 BOOST_FOREACH(const CTxIn& txin, vin)
508 if (txin.prevout.IsNull())
509 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
515 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
516 enum GetMinFee_mode mode) const
518 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
519 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
521 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
522 unsigned int nNewBlockSize = nBlockSize + nBytes;
523 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
525 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
526 if (nMinFee < nBaseFee)
528 BOOST_FOREACH(const CTxOut& txout, vout)
529 if (txout.nValue < CENT)
533 // Raise the price as the block approaches full
534 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
536 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
538 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
541 if (!MoneyRange(nMinFee))
547 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
548 bool* pfMissingInputs)
551 *pfMissingInputs = false;
553 if (!tx.CheckTransaction())
554 return error("CTxMemPool::accept() : CheckTransaction failed");
556 // Coinbase is only valid in a block, not as a loose transaction
558 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
560 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
561 if (tx.IsCoinStake())
562 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
564 // To help v0.1.5 clients who would see it as a negative number
565 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
566 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
568 // Rather not work on nonstandard transactions (unless -testnet)
569 if (!fTestNet && !tx.IsStandard())
570 return error("CTxMemPool::accept() : nonstandard transaction type");
572 // Do we already have it?
573 uint256 hash = tx.GetHash();
576 if (mapTx.count(hash))
580 if (txdb.ContainsTx(hash))
583 // Check for conflicts with in-memory transactions
584 CTransaction* ptxOld = NULL;
585 for (unsigned int i = 0; i < tx.vin.size(); i++)
587 COutPoint outpoint = tx.vin[i].prevout;
588 if (mapNextTx.count(outpoint))
590 // Disable replacement feature for now
593 // Allow replacing with a newer version of the same transaction
596 ptxOld = mapNextTx[outpoint].ptx;
597 if (ptxOld->IsFinal())
599 if (!tx.IsNewerThan(*ptxOld))
601 for (unsigned int i = 0; i < tx.vin.size(); i++)
603 COutPoint outpoint = tx.vin[i].prevout;
604 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
614 map<uint256, CTxIndex> mapUnused;
615 bool fInvalid = false;
616 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
619 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
621 *pfMissingInputs = true;
625 // Check for non-standard pay-to-script-hash in inputs
626 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
627 return error("CTxMemPool::accept() : nonstandard transaction input");
629 // Note: if you modify this code to accept non-standard transactions, then
630 // you should add code here to check that the transaction does a
631 // reasonable number of ECDSA signature verifications.
633 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
634 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
636 // Don't accept it if it can't get into a block
637 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY);
638 if (nFees < txMinFee)
639 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
640 hash.ToString().c_str(),
643 // Continuously rate-limit free transactions
644 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
645 // be annoying or make others' transactions take longer to confirm.
646 if (nFees < MIN_RELAY_TX_FEE)
648 static CCriticalSection cs;
649 static double dFreeCount;
650 static int64 nLastTime;
651 int64 nNow = GetTime();
655 // Use an exponentially decaying ~10-minute window:
656 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
658 // -limitfreerelay unit is thousand-bytes-per-minute
659 // At default rate it would take over a month to fill 1GB
660 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
661 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
663 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
668 // Check against previous transactions
669 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
670 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
672 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
676 // Store transaction in memory
681 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
684 addUnchecked(hash, tx);
687 ///// are we sure this is ok when loading transactions or restoring block txes
688 // If updated, erase old tx from wallet
690 EraseFromWallets(ptxOld->GetHash());
692 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
693 hash.ToString().substr(0,10).c_str(),
698 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
700 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
703 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
705 // Add to memory pool without checking anything. Don't call this directly,
706 // call CTxMemPool::accept to properly check the transaction first.
709 for (unsigned int i = 0; i < tx.vin.size(); i++)
710 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
711 nTransactionsUpdated++;
717 bool CTxMemPool::remove(CTransaction &tx)
719 // Remove transaction from memory pool
722 uint256 hash = tx.GetHash();
723 if (mapTx.count(hash))
725 BOOST_FOREACH(const CTxIn& txin, tx.vin)
726 mapNextTx.erase(txin.prevout);
728 nTransactionsUpdated++;
734 void CTxMemPool::clear()
739 ++nTransactionsUpdated;
742 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
747 vtxid.reserve(mapTx.size());
748 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
749 vtxid.push_back((*mi).first);
755 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
757 if (hashBlock == 0 || nIndex == -1)
760 // Find the block it claims to be in
761 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
762 if (mi == mapBlockIndex.end())
764 CBlockIndex* pindex = (*mi).second;
765 if (!pindex || !pindex->IsInMainChain())
768 // Make sure the merkle branch connects to this block
769 if (!fMerkleVerified)
771 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
773 fMerkleVerified = true;
777 return pindexBest->nHeight - pindex->nHeight + 1;
781 int CMerkleTx::GetBlocksToMaturity() const
783 if (!(IsCoinBase() || IsCoinStake()))
785 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
789 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
793 if (!IsInMainChain() && !ClientConnectInputs())
795 return CTransaction::AcceptToMemoryPool(txdb, false);
799 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
803 bool CMerkleTx::AcceptToMemoryPool()
806 return AcceptToMemoryPool(txdb);
811 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
816 // Add previous supporting transactions first
817 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
819 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
821 uint256 hash = tx.GetHash();
822 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
823 tx.AcceptToMemoryPool(txdb, fCheckInputs);
826 return AcceptToMemoryPool(txdb, fCheckInputs);
831 bool CWalletTx::AcceptWalletTransaction()
834 return AcceptWalletTransaction(txdb);
837 int CTxIndex::GetDepthInMainChain() const
841 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
843 // Find the block in the index
844 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
845 if (mi == mapBlockIndex.end())
847 CBlockIndex* pindex = (*mi).second;
848 if (!pindex || !pindex->IsInMainChain())
850 return 1 + nBestHeight - pindex->nHeight;
853 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
854 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
860 if (mempool.exists(hash))
862 tx = mempool.lookup(hash);
868 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
871 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
872 hashBlock = block.GetHash();
886 //////////////////////////////////////////////////////////////////////////////
888 // CBlock and CBlockIndex
891 static CBlockIndex* pblockindexFBBHLast;
892 CBlockIndex* FindBlockByHeight(int nHeight)
894 CBlockIndex *pblockindex;
895 if (nHeight < nBestHeight / 2)
896 pblockindex = pindexGenesisBlock;
898 pblockindex = pindexBest;
899 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
900 pblockindex = pblockindexFBBHLast;
901 while (pblockindex->nHeight > nHeight)
902 pblockindex = pblockindex->pprev;
903 while (pblockindex->nHeight < nHeight)
904 pblockindex = pblockindex->pnext;
905 pblockindexFBBHLast = pblockindex;
909 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
911 if (!fReadTransactions)
913 *this = pindex->GetBlockHeader();
916 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
918 if (GetHash() != pindex->GetBlockHash())
919 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
923 uint256 static GetOrphanRoot(const CBlock* pblock)
925 // Work back to the first block in the orphan chain
926 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
927 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
928 return pblock->GetHash();
931 // ppcoin: find block wanted by given orphan block
932 uint256 WantedByOrphan(const CBlock* pblockOrphan)
934 // Work back to the first block in the orphan chain
935 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
936 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
937 return pblockOrphan->hashPrevBlock;
940 // select stake target limit according to hard-coded conditions
941 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
943 if(fTestNet) // separate proof of stake target limit for testnet
944 return bnProofOfStakeLimit;
945 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
946 return bnProofOfStakeLimit;
947 if(nHeight + 1 > 15000) // 24 bits since block 15000
948 return bnProofOfStakeLegacyLimit;
949 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
950 return bnProofOfStakeHardLimit;
952 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
955 // miner's coin base reward based on nBits
956 int64 GetProofOfWorkReward(unsigned int nBits)
958 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
961 bnTarget.SetCompact(nBits);
962 CBigNum bnTargetLimit = bnProofOfWorkLimit;
963 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
965 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
966 // A reasonably continuous curve is used to avoid shock to market
967 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
969 // Human readable form:
971 // nSubsidy = 100 / (diff ^ 1/6)
972 CBigNum bnLowerBound = CENT;
973 CBigNum bnUpperBound = bnSubsidyLimit;
974 while (bnLowerBound + CENT <= bnUpperBound)
976 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
977 if (fDebug && GetBoolArg("-printcreation"))
978 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
979 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
980 bnUpperBound = bnMidValue;
982 bnLowerBound = bnMidValue;
985 int64 nSubsidy = bnUpperBound.getuint64();
987 nSubsidy = (nSubsidy / CENT) * CENT;
988 if (fDebug && GetBoolArg("-printcreation"))
989 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
991 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
994 // miner's coin stake reward based on nBits and coin age spent (coin-days)
995 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
997 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
999 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1001 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1003 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1005 bnTarget.SetCompact(nBits);
1006 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1007 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1009 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1011 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1012 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1013 bnMidPart, bnRewardPart;
1015 while (bnLowerBound + CENT <= bnUpperBound)
1017 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1018 if (fDebug && GetBoolArg("-printcreation"))
1019 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1021 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1024 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1026 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1028 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1031 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1032 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1037 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1039 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1041 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1044 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1045 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1048 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1049 bnUpperBound = bnMidValue;
1051 bnLowerBound = bnMidValue;
1054 nRewardCoinYear = bnUpperBound.getuint64();
1055 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1059 // Old creation amount per coin-year, 5% fixed stake mint rate
1060 nRewardCoinYear = 5 * CENT;
1064 return nRewardCoinYear;
1066 // Fix problem with proof-of-stake rewards calculation since 20 Sep 2013
1067 if(nTime < CHAINCHECKS_SWITCH_TIME)
1068 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
1070 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1072 // Set reasonable reward limit for large inputs since 20 Oct 2013
1074 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1075 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1077 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1078 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1080 nSubsidy = min(nSubsidy, nSubsidyLimit);
1083 if (fDebug && GetBoolArg("-printcreation"))
1084 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1088 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1090 // get proof of work blocks max spacing according to hard-coded conditions
1091 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1093 if(nTime > TARGETS_SWITCH_TIME)
1094 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1097 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1099 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1103 // maximum nBits value could possible be required nTime after
1105 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1108 bnResult.SetCompact(nBase);
1110 while (nTime > 0 && bnResult < bnTargetLimit)
1112 // Maximum 200% adjustment per day...
1114 nTime -= 24 * 60 * 60;
1116 if (bnResult > bnTargetLimit)
1117 bnResult = bnTargetLimit;
1118 return bnResult.GetCompact();
1122 // minimum amount of work that could possibly be required nTime after
1123 // minimum proof-of-work required was nBase
1125 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1127 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1131 // minimum amount of stake that could possibly be required nTime after
1132 // minimum proof-of-stake required was nBase
1134 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1136 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1140 // ppcoin: find last block index up to pindex
1141 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1143 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1144 pindex = pindex->pprev;
1148 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1150 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1152 if (pindexLast == NULL)
1153 return bnTargetLimit.GetCompact(); // genesis block
1155 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1156 if (pindexPrev->pprev == NULL)
1157 return bnTargetLimit.GetCompact(); // first block
1158 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1159 if (pindexPrevPrev->pprev == NULL)
1160 return bnTargetLimit.GetCompact(); // second block
1162 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1164 // ppcoin: target change every block
1165 // ppcoin: retarget with exponential moving toward target spacing
1167 bnNew.SetCompact(pindexPrev->nBits);
1168 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1169 int64 nInterval = nTargetTimespan / nTargetSpacing;
1170 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1171 bnNew /= ((nInterval + 1) * nTargetSpacing);
1173 if (bnNew > bnTargetLimit)
1174 bnNew = bnTargetLimit;
1176 return bnNew.GetCompact();
1179 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1182 bnTarget.SetCompact(nBits);
1185 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1186 return error("CheckProofOfWork() : nBits below minimum work");
1188 // Check proof of work matches claimed amount
1189 if (hash > bnTarget.getuint256())
1190 return error("CheckProofOfWork() : hash doesn't match nBits");
1195 // Return maximum amount of blocks that other nodes claim to have
1196 int GetNumBlocksOfPeers()
1198 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1201 bool IsInitialBlockDownload()
1203 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1205 static int64 nLastUpdate;
1206 static CBlockIndex* pindexLastBest;
1207 if (pindexBest != pindexLastBest)
1209 pindexLastBest = pindexBest;
1210 nLastUpdate = GetTime();
1212 return (GetTime() - nLastUpdate < 10 &&
1213 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1216 void static InvalidChainFound(CBlockIndex* pindexNew)
1218 if (pindexNew->nChainTrust > nBestInvalidTrust)
1220 nBestInvalidTrust = pindexNew->nChainTrust;
1221 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1222 uiInterface.NotifyBlocksChanged();
1225 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1226 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1228 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1229 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1230 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1231 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1232 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1233 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1234 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1235 nBestBlockTrust.Get64(),
1236 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1240 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1242 nTime = max(GetBlockTime(), GetAdjustedTime());
1255 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1257 // Relinquish previous transactions' spent pointers
1260 BOOST_FOREACH(const CTxIn& txin, vin)
1262 COutPoint prevout = txin.prevout;
1264 // Get prev txindex from disk
1266 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1267 return error("DisconnectInputs() : ReadTxIndex failed");
1269 if (prevout.n >= txindex.vSpent.size())
1270 return error("DisconnectInputs() : prevout.n out of range");
1272 // Mark outpoint as not spent
1273 txindex.vSpent[prevout.n].SetNull();
1276 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1277 return error("DisconnectInputs() : UpdateTxIndex failed");
1281 // Remove transaction from index
1282 // This can fail if a duplicate of this transaction was in a chain that got
1283 // reorganized away. This is only possible if this transaction was completely
1284 // spent, so erasing it would be a no-op anyway.
1285 txdb.EraseTxIndex(*this);
1291 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1292 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1294 // FetchInputs can return false either because we just haven't seen some inputs
1295 // (in which case the transaction should be stored as an orphan)
1296 // or because the transaction is malformed (in which case the transaction should
1297 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1301 return true; // Coinbase transactions have no inputs to fetch.
1303 for (unsigned int i = 0; i < vin.size(); i++)
1305 COutPoint prevout = vin[i].prevout;
1306 if (inputsRet.count(prevout.hash))
1307 continue; // Got it already
1310 CTxIndex& txindex = inputsRet[prevout.hash].first;
1312 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1314 // Get txindex from current proposed changes
1315 txindex = mapTestPool.find(prevout.hash)->second;
1319 // Read txindex from txdb
1320 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1322 if (!fFound && (fBlock || fMiner))
1323 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());
1326 CTransaction& txPrev = inputsRet[prevout.hash].second;
1327 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1329 // Get prev tx from single transactions in memory
1332 if (!mempool.exists(prevout.hash))
1333 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());
1334 txPrev = mempool.lookup(prevout.hash);
1337 txindex.vSpent.resize(txPrev.vout.size());
1341 // Get prev tx from disk
1342 if (!txPrev.ReadFromDisk(txindex.pos))
1343 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1347 // Make sure all prevout.n indexes are valid:
1348 for (unsigned int i = 0; i < vin.size(); i++)
1350 const COutPoint prevout = vin[i].prevout;
1351 assert(inputsRet.count(prevout.hash) != 0);
1352 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1353 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1354 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1356 // Revisit this if/when transaction replacement is implemented and allows
1359 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()));
1366 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1368 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1369 if (mi == inputs.end())
1370 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1372 const CTransaction& txPrev = (mi->second).second;
1373 if (input.prevout.n >= txPrev.vout.size())
1374 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1376 return txPrev.vout[input.prevout.n];
1379 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1385 for (unsigned int i = 0; i < vin.size(); i++)
1387 nResult += GetOutputFor(vin[i], inputs).nValue;
1393 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1398 unsigned int nSigOps = 0;
1399 for (unsigned int i = 0; i < vin.size(); i++)
1401 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1402 if (prevout.scriptPubKey.IsPayToScriptHash())
1403 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1408 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1409 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1410 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1412 // Take over previous transactions' spent pointers
1413 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1414 // fMiner is true when called from the internal bitcoin miner
1415 // ... both are false when called from CTransaction::AcceptToMemoryPool
1420 for (unsigned int i = 0; i < vin.size(); i++)
1422 COutPoint prevout = vin[i].prevout;
1423 assert(inputs.count(prevout.hash) > 0);
1424 CTxIndex& txindex = inputs[prevout.hash].first;
1425 CTransaction& txPrev = inputs[prevout.hash].second;
1427 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1428 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()));
1430 // If prev is coinbase or coinstake, check that it's matured
1431 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1432 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1433 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1434 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1436 // ppcoin: check transaction timestamp
1437 if (txPrev.nTime > nTime)
1438 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1440 // Check for negative or overflow input values
1441 nValueIn += txPrev.vout[prevout.n].nValue;
1442 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1443 return DoS(100, error("ConnectInputs() : txin values out of range"));
1446 // The first loop above does all the inexpensive checks.
1447 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1448 // Helps prevent CPU exhaustion attacks.
1449 for (unsigned int i = 0; i < vin.size(); i++)
1451 COutPoint prevout = vin[i].prevout;
1452 assert(inputs.count(prevout.hash) > 0);
1453 CTxIndex& txindex = inputs[prevout.hash].first;
1454 CTransaction& txPrev = inputs[prevout.hash].second;
1456 // Check for conflicts (double-spend)
1457 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1458 // for an attacker to attempt to split the network.
1459 if (!txindex.vSpent[prevout.n].IsNull())
1460 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());
1462 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1463 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1464 // still computed and checked, and any change will be caught at the next checkpoint.
1465 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1468 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1470 // only during transition phase for P2SH: do not invoke anti-DoS code for
1471 // potentially old clients relaying bad P2SH transactions
1472 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1473 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1475 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1479 // Mark outpoints as spent
1480 txindex.vSpent[prevout.n] = posThisTx;
1483 if (fBlock || fMiner)
1485 mapTestPool[prevout.hash] = txindex;
1491 // ppcoin: coin stake tx earns reward instead of paying fee
1493 if (!GetCoinAge(txdb, nCoinAge))
1494 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1496 int64 nStakeReward = GetValueOut() - nValueIn;
1497 int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1499 if (nStakeReward > nCalculatedStakeReward)
1500 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1504 if (nValueIn < GetValueOut())
1505 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1507 // Tally transaction fees
1508 int64 nTxFee = nValueIn - GetValueOut();
1510 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1511 // ppcoin: enforce transaction fees for every block
1512 if (nTxFee < GetMinFee())
1513 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;
1516 if (!MoneyRange(nFees))
1517 return DoS(100, error("ConnectInputs() : nFees out of range"));
1525 bool CTransaction::ClientConnectInputs()
1530 // Take over previous transactions' spent pointers
1534 for (unsigned int i = 0; i < vin.size(); i++)
1536 // Get prev tx from single transactions in memory
1537 COutPoint prevout = vin[i].prevout;
1538 if (!mempool.exists(prevout.hash))
1540 CTransaction& txPrev = mempool.lookup(prevout.hash);
1542 if (prevout.n >= txPrev.vout.size())
1546 if (!VerifySignature(txPrev, *this, i, true, 0))
1547 return error("ConnectInputs() : VerifySignature failed");
1549 ///// this is redundant with the mempool.mapNextTx stuff,
1550 ///// not sure which I want to get rid of
1551 ///// this has to go away now that posNext is gone
1552 // // Check for conflicts
1553 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1554 // return error("ConnectInputs() : prev tx already used");
1556 // // Flag outpoints as used
1557 // txPrev.vout[prevout.n].posNext = posThisTx;
1559 nValueIn += txPrev.vout[prevout.n].nValue;
1561 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1562 return error("ClientConnectInputs() : txin values out of range");
1564 if (GetValueOut() > nValueIn)
1574 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1576 // Disconnect in reverse order
1577 for (int i = vtx.size()-1; i >= 0; i--)
1578 if (!vtx[i].DisconnectInputs(txdb))
1581 // Update block index on disk without changing it in memory.
1582 // The memory index structure will be changed after the db commits.
1585 CDiskBlockIndex blockindexPrev(pindex->pprev);
1586 blockindexPrev.hashNext = 0;
1587 if (!txdb.WriteBlockIndex(blockindexPrev))
1588 return error("DisconnectBlock() : WriteBlockIndex failed");
1591 // ppcoin: clean up wallet after disconnecting coinstake
1592 BOOST_FOREACH(CTransaction& tx, vtx)
1593 SyncWithWallets(tx, this, false, false);
1598 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1600 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1601 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1604 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1605 // unless those are already completely spent.
1606 // If such overwrites are allowed, coinbases and transactions depending upon those
1607 // can be duplicated to remove the ability to spend the first instance -- even after
1608 // being sent to another address.
1609 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1610 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1611 // already refuses previously-known transaction ids entirely.
1612 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1613 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1614 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1615 // initial block download.
1616 bool fEnforceBIP30 = true; // Always active in NovaCoin
1617 bool fStrictPayToScriptHash = true; // Always active in NovaCoin
1619 //// issue here: it doesn't know the version
1620 unsigned int nTxPos;
1622 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1623 // 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
1626 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1628 map<uint256, CTxIndex> mapQueuedChanges;
1631 int64 nValueOut = 0;
1632 unsigned int nSigOps = 0;
1633 BOOST_FOREACH(CTransaction& tx, vtx)
1635 uint256 hashTx = tx.GetHash();
1637 if (fEnforceBIP30) {
1638 CTxIndex txindexOld;
1639 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1640 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1646 nSigOps += tx.GetLegacySigOpCount();
1647 if (nSigOps > MAX_BLOCK_SIGOPS)
1648 return DoS(100, error("ConnectBlock() : too many sigops"));
1650 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1652 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1654 MapPrevTx mapInputs;
1655 if (tx.IsCoinBase())
1656 nValueOut += tx.GetValueOut();
1660 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1663 if (fStrictPayToScriptHash)
1665 // Add in sigops done by pay-to-script-hash inputs;
1666 // this is to prevent a "rogue miner" from creating
1667 // an incredibly-expensive-to-validate block.
1668 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1669 if (nSigOps > MAX_BLOCK_SIGOPS)
1670 return DoS(100, error("ConnectBlock() : too many sigops"));
1673 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1674 int64 nTxValueOut = tx.GetValueOut();
1675 nValueIn += nTxValueIn;
1676 nValueOut += nTxValueOut;
1677 if (!tx.IsCoinStake())
1678 nFees += nTxValueIn - nTxValueOut;
1680 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1684 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1687 // ppcoin: track money supply and mint amount info
1688 pindex->nMint = nValueOut - nValueIn + nFees;
1689 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1690 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1691 return error("Connect() : WriteBlockIndex for pindex failed");
1693 // ppcoin: fees are not collected by miners as in bitcoin
1694 // ppcoin: fees are destroyed to compensate the entire network
1695 if (fDebug && GetBoolArg("-printcreation"))
1696 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1701 // Write queued txindex changes
1702 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1704 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1705 return error("ConnectBlock() : UpdateTxIndex failed");
1708 // Update block index on disk without changing it in memory.
1709 // The memory index structure will be changed after the db commits.
1712 CDiskBlockIndex blockindexPrev(pindex->pprev);
1713 blockindexPrev.hashNext = pindex->GetBlockHash();
1714 if (!txdb.WriteBlockIndex(blockindexPrev))
1715 return error("ConnectBlock() : WriteBlockIndex failed");
1718 // Watch for transactions paying to me
1719 BOOST_FOREACH(CTransaction& tx, vtx)
1720 SyncWithWallets(tx, this, true);
1725 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1727 printf("REORGANIZE\n");
1730 CBlockIndex* pfork = pindexBest;
1731 CBlockIndex* plonger = pindexNew;
1732 while (pfork != plonger)
1734 while (plonger->nHeight > pfork->nHeight)
1735 if (!(plonger = plonger->pprev))
1736 return error("Reorganize() : plonger->pprev is null");
1737 if (pfork == plonger)
1739 if (!(pfork = pfork->pprev))
1740 return error("Reorganize() : pfork->pprev is null");
1743 // List of what to disconnect
1744 vector<CBlockIndex*> vDisconnect;
1745 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1746 vDisconnect.push_back(pindex);
1748 // List of what to connect
1749 vector<CBlockIndex*> vConnect;
1750 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1751 vConnect.push_back(pindex);
1752 reverse(vConnect.begin(), vConnect.end());
1754 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());
1755 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());
1757 // Disconnect shorter branch
1758 vector<CTransaction> vResurrect;
1759 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1762 if (!block.ReadFromDisk(pindex))
1763 return error("Reorganize() : ReadFromDisk for disconnect failed");
1764 if (!block.DisconnectBlock(txdb, pindex))
1765 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1767 // Queue memory transactions to resurrect
1768 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1769 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1770 vResurrect.push_back(tx);
1773 // Connect longer branch
1774 vector<CTransaction> vDelete;
1775 for (unsigned int i = 0; i < vConnect.size(); i++)
1777 CBlockIndex* pindex = vConnect[i];
1779 if (!block.ReadFromDisk(pindex))
1780 return error("Reorganize() : ReadFromDisk for connect failed");
1781 if (!block.ConnectBlock(txdb, pindex))
1784 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1787 // Queue memory transactions to delete
1788 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1789 vDelete.push_back(tx);
1791 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1792 return error("Reorganize() : WriteHashBestChain failed");
1794 // Make sure it's successfully written to disk before changing memory structure
1795 if (!txdb.TxnCommit())
1796 return error("Reorganize() : TxnCommit failed");
1798 // Disconnect shorter branch
1799 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1801 pindex->pprev->pnext = NULL;
1803 // Connect longer branch
1804 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1806 pindex->pprev->pnext = pindex;
1808 // Resurrect memory transactions that were in the disconnected branch
1809 BOOST_FOREACH(CTransaction& tx, vResurrect)
1810 tx.AcceptToMemoryPool(txdb, false);
1812 // Delete redundant memory transactions that are in the connected branch
1813 BOOST_FOREACH(CTransaction& tx, vDelete)
1816 printf("REORGANIZE: done\n");
1822 // Called from inside SetBestChain: attaches a block to the new best chain being built
1823 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1825 uint256 hash = GetHash();
1827 // Adding to current best branch
1828 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1831 InvalidChainFound(pindexNew);
1834 if (!txdb.TxnCommit())
1835 return error("SetBestChain() : TxnCommit failed");
1837 // Add to current best branch
1838 pindexNew->pprev->pnext = pindexNew;
1840 // Delete redundant memory transactions
1841 BOOST_FOREACH(CTransaction& tx, vtx)
1847 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1849 uint256 hash = GetHash();
1851 if (!txdb.TxnBegin())
1852 return error("SetBestChain() : TxnBegin failed");
1854 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1856 txdb.WriteHashBestChain(hash);
1857 if (!txdb.TxnCommit())
1858 return error("SetBestChain() : TxnCommit failed");
1859 pindexGenesisBlock = pindexNew;
1861 else if (hashPrevBlock == hashBestChain)
1863 if (!SetBestChainInner(txdb, pindexNew))
1864 return error("SetBestChain() : SetBestChainInner failed");
1868 // the first block in the new chain that will cause it to become the new best chain
1869 CBlockIndex *pindexIntermediate = pindexNew;
1871 // list of blocks that need to be connected afterwards
1872 std::vector<CBlockIndex*> vpindexSecondary;
1874 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1875 // Try to limit how much needs to be done inside
1876 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1878 vpindexSecondary.push_back(pindexIntermediate);
1879 pindexIntermediate = pindexIntermediate->pprev;
1882 if (!vpindexSecondary.empty())
1883 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1885 // Switch to new best branch
1886 if (!Reorganize(txdb, pindexIntermediate))
1889 InvalidChainFound(pindexNew);
1890 return error("SetBestChain() : Reorganize failed");
1893 // Connect further blocks
1894 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1897 if (!block.ReadFromDisk(pindex))
1899 printf("SetBestChain() : ReadFromDisk failed\n");
1902 if (!txdb.TxnBegin()) {
1903 printf("SetBestChain() : TxnBegin 2 failed\n");
1906 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1907 if (!block.SetBestChainInner(txdb, pindex))
1912 // Update best block in wallet (so we can detect restored wallets)
1913 bool fIsInitialDownload = IsInitialBlockDownload();
1914 if (!fIsInitialDownload)
1916 const CBlockLocator locator(pindexNew);
1917 ::SetBestChain(locator);
1921 hashBestChain = hash;
1922 pindexBest = pindexNew;
1923 pblockindexFBBHLast = NULL;
1924 nBestHeight = pindexBest->nHeight;
1925 nBestChainTrust = pindexNew->nChainTrust;
1926 nTimeBestReceived = GetTime();
1927 nTransactionsUpdated++;
1929 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1931 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1932 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1933 CBigNum(nBestChainTrust).ToString().c_str(),
1934 nBestBlockTrust.Get64(),
1935 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1937 // Check the version of the last 100 blocks to see if we need to upgrade:
1938 if (!fIsInitialDownload)
1941 const CBlockIndex* pindex = pindexBest;
1942 for (int i = 0; i < 100 && pindex != NULL; i++)
1944 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1946 pindex = pindex->pprev;
1949 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1950 if (nUpgraded > 100/2)
1951 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1952 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1955 std::string strCmd = GetArg("-blocknotify", "");
1957 if (!fIsInitialDownload && !strCmd.empty())
1959 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1960 boost::thread t(runCommand, strCmd); // thread runs free
1966 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1967 // Only those coins meeting minimum age requirement counts. As those
1968 // transactions not in main chain are not currently indexed so we
1969 // might not find out about their coin age. Older transactions are
1970 // guaranteed to be in main chain by sync-checkpoint. This rule is
1971 // introduced to help nodes establish a consistent view of the coin
1972 // age (trust score) of competing branches.
1973 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1975 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1981 BOOST_FOREACH(const CTxIn& txin, vin)
1983 // First try finding the previous transaction in database
1984 CTransaction txPrev;
1986 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1987 continue; // previous transaction not in main chain
1988 if (nTime < txPrev.nTime)
1989 return false; // Transaction timestamp violation
1991 // Read block header
1993 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1994 return false; // unable to read block of previous transaction
1995 if (block.GetBlockTime() + nStakeMinAge > nTime)
1996 continue; // only count coins meeting min age requirement
1998 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1999 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2001 if (fDebug && GetBoolArg("-printcoinage"))
2002 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2005 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
2006 if (fDebug && GetBoolArg("-printcoinage"))
2007 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2008 nCoinAge = bnCoinDay.getuint64();
2012 // ppcoin: total coin age spent in block, in the unit of coin-days.
2013 bool CBlock::GetCoinAge(uint64& nCoinAge) const
2018 BOOST_FOREACH(const CTransaction& tx, vtx)
2021 if (tx.GetCoinAge(txdb, nTxCoinAge))
2022 nCoinAge += nTxCoinAge;
2027 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2029 if (fDebug && GetBoolArg("-printcoinage"))
2030 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
2034 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2036 // Check for duplicate
2037 uint256 hash = GetHash();
2038 if (mapBlockIndex.count(hash))
2039 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2041 // Construct new block index object
2042 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
2044 return error("AddToBlockIndex() : new CBlockIndex failed");
2045 pindexNew->phashBlock = &hash;
2046 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2047 if (miPrev != mapBlockIndex.end())
2049 pindexNew->pprev = (*miPrev).second;
2050 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2053 // ppcoin: compute chain trust score
2054 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2056 // ppcoin: compute stake entropy bit for stake modifier
2057 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2058 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2060 // ppcoin: record proof-of-stake hash value
2061 if (pindexNew->IsProofOfStake())
2063 if (!mapProofOfStake.count(hash))
2064 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2065 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2068 // ppcoin: compute stake modifier
2069 uint64 nStakeModifier = 0;
2070 bool fGeneratedStakeModifier = false;
2071 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2072 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2073 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2074 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2075 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2076 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2078 // Add to mapBlockIndex
2079 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2080 if (pindexNew->IsProofOfStake())
2081 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2082 pindexNew->phashBlock = &((*mi).first);
2084 // Write to disk block index
2086 if (!txdb.TxnBegin())
2088 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2089 if (!txdb.TxnCommit())
2093 if (pindexNew->nChainTrust > nBestChainTrust)
2094 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 // Check that the block satisfies synchronized checkpoint
2261 if (!GetBoolArg("-nosynccheckpoints", false) && !Checkpoints::CheckSync(hash, pindexPrev))
2262 return error("AcceptBlock() : rejected by synchronized checkpoint");
2264 // Enforce rule that the coinbase starts with serialized block height
2265 CScript expect = CScript() << nHeight;
2266 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2267 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2269 // Write block to history file
2270 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2271 return error("AcceptBlock() : out of disk space");
2272 unsigned int nFile = -1;
2273 unsigned int nBlockPos = 0;
2274 if (!WriteToDisk(nFile, nBlockPos))
2275 return error("AcceptBlock() : WriteToDisk failed");
2276 if (!AddToBlockIndex(nFile, nBlockPos))
2277 return error("AcceptBlock() : AddToBlockIndex failed");
2279 // Relay inventory, but don't relay old inventory during initial block download
2280 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2281 if (hashBestChain == hash)
2284 BOOST_FOREACH(CNode* pnode, vNodes)
2285 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2286 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2289 // ppcoin: check pending sync-checkpoint
2290 Checkpoints::AcceptPendingSyncCheckpoint();
2295 uint256 CBlockIndex::GetBlockTrust() const
2298 bnTarget.SetCompact(nBits);
2303 /* Old protocol, will be removed later */
2304 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2305 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2309 // Calculate work amount for block
2310 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2312 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2313 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2315 // Return nPoWTrust for the first 12 blocks
2316 if (pprev == NULL || pprev->nHeight < 12)
2319 const CBlockIndex* currentIndex = pprev;
2321 if(IsProofOfStake())
2323 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2325 // Return 1/3 of score if parent block is not the PoW block
2326 if (!pprev->IsProofOfWork())
2327 return (bnNewTrust / 3).getuint256();
2331 // Check last 12 blocks type
2332 while (pprev->nHeight - currentIndex->nHeight < 12)
2334 if (currentIndex->IsProofOfWork())
2336 currentIndex = currentIndex->pprev;
2339 // Return 1/3 of score if less than 3 PoW blocks found
2341 return (bnNewTrust / 3).getuint256();
2343 return bnNewTrust.getuint256();
2347 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2349 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2350 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2351 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2355 // Check last 12 blocks type
2356 while (pprev->nHeight - currentIndex->nHeight < 12)
2358 if (currentIndex->IsProofOfStake())
2360 currentIndex = currentIndex->pprev;
2363 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2365 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2367 bnTarget.SetCompact(pprev->nBits);
2372 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2374 // Return nPoWTrust + full trust score for previous block nBits
2375 return nPoWTrust + bnNewTrust.getuint256();
2379 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2381 unsigned int nFound = 0;
2382 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2384 if (pstart->nVersion >= minVersion)
2386 pstart = pstart->pprev;
2388 return (nFound >= nRequired);
2391 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2393 // Check for duplicate
2394 uint256 hash = pblock->GetHash();
2395 if (mapBlockIndex.count(hash))
2396 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2397 if (mapOrphanBlocks.count(hash))
2398 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2400 // ppcoin: check proof-of-stake
2401 // Limited duplicity on stake: prevents block flood attack
2402 // Duplicate stake allowed only when there is orphan child block
2403 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2404 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());
2406 // Preliminary checks
2407 if (!pblock->CheckBlock())
2408 return error("ProcessBlock() : CheckBlock FAILED");
2410 // ppcoin: verify hash target and signature of coinstake tx
2411 if (pblock->IsProofOfStake())
2413 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2414 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2416 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2417 return false; // do not error here as we expect this during initial block download
2419 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2420 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2423 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2424 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2426 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2427 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2429 bnNewBlock.SetCompact(pblock->nBits);
2432 if (pblock->IsProofOfStake())
2433 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2435 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2437 if (bnNewBlock > bnRequired)
2440 pfrom->Misbehaving(100);
2441 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2445 // ppcoin: ask for pending sync-checkpoint if any
2446 if (!IsInitialBlockDownload())
2447 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2449 // If don't already have its previous block, shunt it off to holding area until we get it
2450 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2452 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2453 CBlock* pblock2 = new CBlock(*pblock);
2454 // ppcoin: check proof-of-stake
2455 if (pblock2->IsProofOfStake())
2457 // Limited duplicity on stake: prevents block flood attack
2458 // Duplicate stake allowed only when there is orphan child block
2459 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2460 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());
2462 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2464 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2465 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2467 // Ask this guy to fill in what we're missing
2470 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2471 // ppcoin: getblocks may not obtain the ancestor block rejected
2472 // earlier by duplicate-stake check so we ask for it again directly
2473 if (!IsInitialBlockDownload())
2474 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2480 if (!pblock->AcceptBlock())
2481 return error("ProcessBlock() : AcceptBlock FAILED");
2483 // Recursively process any orphan blocks that depended on this one
2484 vector<uint256> vWorkQueue;
2485 vWorkQueue.push_back(hash);
2486 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2488 uint256 hashPrev = vWorkQueue[i];
2489 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2490 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2493 CBlock* pblockOrphan = (*mi).second;
2494 if (pblockOrphan->AcceptBlock())
2495 vWorkQueue.push_back(pblockOrphan->GetHash());
2496 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2497 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2498 delete pblockOrphan;
2500 mapOrphanBlocksByPrev.erase(hashPrev);
2503 printf("ProcessBlock: ACCEPTED\n");
2505 // ppcoin: if responsible for sync-checkpoint send it
2506 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2507 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2512 // ppcoin: sign block
2513 bool CBlock::SignBlock(const CKeyStore& keystore)
2515 vector<valtype> vSolutions;
2516 txnouttype whichType;
2518 if(!IsProofOfStake())
2520 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2522 const CTxOut& txout = vtx[0].vout[i];
2524 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2527 if (whichType == TX_PUBKEY)
2530 valtype& vchPubKey = vSolutions[0];
2533 if (!keystore.GetKey(Hash160(vchPubKey), key))
2535 if (key.GetPubKey() != vchPubKey)
2537 if(!key.Sign(GetHash(), vchBlockSig))
2546 const CTxOut& txout = vtx[1].vout[1];
2548 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2551 if (whichType == TX_PUBKEY)
2554 valtype& vchPubKey = vSolutions[0];
2557 if (!keystore.GetKey(Hash160(vchPubKey), key))
2559 if (key.GetPubKey() != vchPubKey)
2562 return key.Sign(GetHash(), vchBlockSig);
2566 printf("Sign failed\n");
2570 // ppcoin: check block signature
2571 bool CBlock::CheckBlockSignature(bool fProofOfStake) const
2573 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2574 return vchBlockSig.empty();
2576 vector<valtype> vSolutions;
2577 txnouttype whichType;
2581 const CTxOut& txout = vtx[1].vout[1];
2583 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2585 if (whichType == TX_PUBKEY)
2587 valtype& vchPubKey = vSolutions[0];
2589 if (!key.SetPubKey(vchPubKey))
2591 if (vchBlockSig.empty())
2593 return key.Verify(GetHash(), vchBlockSig);
2598 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2600 const CTxOut& txout = vtx[0].vout[i];
2602 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2605 if (whichType == TX_PUBKEY)
2608 valtype& vchPubKey = vSolutions[0];
2610 if (!key.SetPubKey(vchPubKey))
2612 if (vchBlockSig.empty())
2614 if(!key.Verify(GetHash(), vchBlockSig))
2624 bool CheckDiskSpace(uint64 nAdditionalBytes)
2626 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2628 // Check for nMinDiskSpace bytes (currently 50MB)
2629 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2632 string strMessage = _("Warning: Disk space is low!");
2633 strMiscWarning = strMessage;
2634 printf("*** %s\n", strMessage.c_str());
2635 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2642 static filesystem::path BlockFilePath(unsigned int nFile)
2644 string strBlockFn = strprintf("blk%04u.dat", nFile);
2645 return GetDataDir() / strBlockFn;
2648 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2650 if ((nFile < 1) || (nFile == (unsigned int) -1))
2652 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2655 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2657 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2666 static unsigned int nCurrentBlockFile = 1;
2668 FILE* AppendBlockFile(unsigned int& nFileRet)
2673 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2676 if (fseek(file, 0, SEEK_END) != 0)
2678 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2679 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2681 nFileRet = nCurrentBlockFile;
2685 nCurrentBlockFile++;
2689 bool LoadBlockIndex(bool fAllowNew)
2693 pchMessageStart[0] = 0xcd;
2694 pchMessageStart[1] = 0xf2;
2695 pchMessageStart[2] = 0xc0;
2696 pchMessageStart[3] = 0xef;
2698 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2699 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2700 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2701 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2702 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2709 if (!txdb.LoadBlockIndex())
2714 // Init with genesis block
2716 if (mapBlockIndex.empty())
2725 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2726 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2727 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2729 // vMerkleTree: 4cb33b3b6a
2733 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2734 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2735 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2737 // vMerkleTree: 4cb33b3b6a
2739 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2741 txNew.nTime = 1360105017;
2742 txNew.vin.resize(1);
2743 txNew.vout.resize(1);
2744 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2745 txNew.vout[0].SetEmpty();
2747 block.vtx.push_back(txNew);
2748 block.hashPrevBlock = 0;
2749 block.hashMerkleRoot = block.BuildMerkleTree();
2751 block.nTime = 1360105017;
2752 block.nBits = bnProofOfWorkLimit.GetCompact();
2753 block.nNonce = !fTestNet ? 1575379 : 46534;
2756 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2758 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2759 assert(block.CheckBlock());
2761 // Start new block file
2763 unsigned int nBlockPos;
2764 if (!block.WriteToDisk(nFile, nBlockPos))
2765 return error("LoadBlockIndex() : writing genesis block to disk failed");
2766 if (!block.AddToBlockIndex(nFile, nBlockPos))
2767 return error("LoadBlockIndex() : genesis block not accepted");
2769 // ppcoin: initialize synchronized checkpoint
2770 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2771 return error("LoadBlockIndex() : failed to init sync checkpoint");
2774 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2777 string strPubKey = "";
2778 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2780 // write checkpoint master key to db
2782 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2783 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2784 if (!txdb.TxnCommit())
2785 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2786 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2787 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2797 void PrintBlockTree()
2799 // pre-compute tree structure
2800 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2801 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2803 CBlockIndex* pindex = (*mi).second;
2804 mapNext[pindex->pprev].push_back(pindex);
2806 //while (rand() % 3 == 0)
2807 // mapNext[pindex->pprev].push_back(pindex);
2810 vector<pair<int, CBlockIndex*> > vStack;
2811 vStack.push_back(make_pair(0, pindexGenesisBlock));
2814 while (!vStack.empty())
2816 int nCol = vStack.back().first;
2817 CBlockIndex* pindex = vStack.back().second;
2820 // print split or gap
2821 if (nCol > nPrevCol)
2823 for (int i = 0; i < nCol-1; i++)
2827 else if (nCol < nPrevCol)
2829 for (int i = 0; i < nCol; i++)
2836 for (int i = 0; i < nCol; i++)
2841 block.ReadFromDisk(pindex);
2842 printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
2846 block.GetHash().ToString().c_str(),
2848 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2849 FormatMoney(pindex->nMint).c_str(),
2852 PrintWallets(block);
2854 // put the main time-chain first
2855 vector<CBlockIndex*>& vNext = mapNext[pindex];
2856 for (unsigned int i = 0; i < vNext.size(); i++)
2858 if (vNext[i]->pnext)
2860 swap(vNext[0], vNext[i]);
2866 for (unsigned int i = 0; i < vNext.size(); i++)
2867 vStack.push_back(make_pair(nCol+i, vNext[i]));
2871 bool LoadExternalBlockFile(FILE* fileIn)
2873 int64 nStart = GetTimeMillis();
2879 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2880 unsigned int nPos = 0;
2881 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2883 unsigned char pchData[65536];
2885 fseek(blkdat, nPos, SEEK_SET);
2886 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2889 nPos = (unsigned int)-1;
2892 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2895 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2897 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2900 nPos += ((unsigned char*)nFind - pchData) + 1;
2903 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2904 } while(!fRequestShutdown);
2905 if (nPos == (unsigned int)-1)
2907 fseek(blkdat, nPos, SEEK_SET);
2910 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2914 if (ProcessBlock(NULL,&block))
2922 catch (std::exception &e) {
2923 printf("%s() : Deserialize or I/O error caught during load\n",
2924 __PRETTY_FUNCTION__);
2927 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2931 //////////////////////////////////////////////////////////////////////////////
2936 extern map<uint256, CAlert> mapAlerts;
2937 extern CCriticalSection cs_mapAlerts;
2939 extern string strMintMessage;
2940 extern string strMintWarning;
2942 string GetWarnings(string strFor)
2945 string strStatusBar;
2948 if (GetBoolArg("-testsafemode"))
2951 // ppcoin: wallet lock warning for minting
2952 if (strMintWarning != "")
2955 strStatusBar = strMintWarning;
2958 // Misc warnings like out of disk space and clock is wrong
2959 if (strMiscWarning != "")
2962 strStatusBar = strMiscWarning;
2965 // * Should not enter safe mode for longer invalid chain
2966 // * If sync-checkpoint is too old do not enter safe mode
2967 // * Do not display warning if -nosynccheckpoints specified
2968 if (!GetBoolArg("-nosynccheckpoints", false) && Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) && !fTestNet && !IsInitialBlockDownload())
2971 strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.";
2974 // ppcoin: if detected invalid checkpoint enter safe mode
2975 if (Checkpoints::hashInvalidCheckpoint != 0)
2978 strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.";
2984 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2986 const CAlert& alert = item.second;
2987 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2989 nPriority = alert.nPriority;
2990 strStatusBar = alert.strStatusBar;
2991 if (nPriority > 1000)
2992 strRPC = strStatusBar;
2997 if (strFor == "statusbar")
2998 return strStatusBar;
2999 else if (strFor == "rpc")
3001 assert(!"GetWarnings() : invalid parameter");
3012 //////////////////////////////////////////////////////////////////////////////
3018 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3024 bool txInMap = false;
3027 txInMap = (mempool.exists(inv.hash));
3030 mapOrphanTransactions.count(inv.hash) ||
3031 txdb.ContainsTx(inv.hash);
3035 return mapBlockIndex.count(inv.hash) ||
3036 mapOrphanBlocks.count(inv.hash);
3038 // Don't know what it is, just say we already got one
3045 // The message start string is designed to be unlikely to occur in normal data.
3046 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3047 // a large 4-byte int at any alignment.
3048 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3050 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3052 static map<CService, CPubKey> mapReuseKey;
3053 RandAddSeedPerfmon();
3055 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3056 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3058 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3066 if (strCommand == "version")
3068 // Each connection can only send one version message
3069 if (pfrom->nVersion != 0)
3071 pfrom->Misbehaving(1);
3079 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3080 if (pfrom->nVersion < MIN_PROTO_VERSION)
3082 // Since February 20, 2012, the protocol is initiated at version 209,
3083 // and earlier versions are no longer supported
3084 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3085 pfrom->fDisconnect = true;
3089 if (pfrom->nVersion == 10300)
3090 pfrom->nVersion = 300;
3092 vRecv >> addrFrom >> nNonce;
3094 vRecv >> pfrom->strSubVer;
3096 vRecv >> pfrom->nStartingHeight;
3098 if (pfrom->fInbound && addrMe.IsRoutable())
3100 pfrom->addrLocal = addrMe;
3104 // Disconnect if we connected to ourself
3105 if (nNonce == nLocalHostNonce && nNonce > 1)
3107 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3108 pfrom->fDisconnect = true;
3112 // ppcoin: record my external IP reported by peer
3113 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3114 addrSeenByPeer = addrMe;
3116 // Be shy and don't send version until we hear
3117 if (pfrom->fInbound)
3118 pfrom->PushVersion();
3120 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3122 AddTimeData(pfrom->addr, nTime);
3125 pfrom->PushMessage("verack");
3126 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3128 if (!pfrom->fInbound)
3130 // Advertise our address
3131 if (!fNoListen && !IsInitialBlockDownload())
3133 CAddress addr = GetLocalAddress(&pfrom->addr);
3134 if (addr.IsRoutable())
3135 pfrom->PushAddress(addr);
3138 // Get recent addresses
3139 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3141 pfrom->PushMessage("getaddr");
3142 pfrom->fGetAddr = true;
3144 addrman.Good(pfrom->addr);
3146 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3148 addrman.Add(addrFrom, addrFrom);
3149 addrman.Good(addrFrom);
3153 // Ask the first connected node for block updates
3154 static int nAskedForBlocks = 0;
3155 if (!pfrom->fClient && !pfrom->fOneShot &&
3156 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3157 (pfrom->nVersion < NOBLKS_VERSION_START ||
3158 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3159 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3162 pfrom->PushGetBlocks(pindexBest, uint256(0));
3168 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3169 item.second.RelayTo(pfrom);
3172 // ppcoin: relay sync-checkpoint
3174 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3175 if (!Checkpoints::checkpointMessage.IsNull())
3176 Checkpoints::checkpointMessage.RelayTo(pfrom);
3179 pfrom->fSuccessfullyConnected = true;
3181 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());
3183 cPeerBlockCounts.input(pfrom->nStartingHeight);
3185 // ppcoin: ask for pending sync-checkpoint if any
3186 if (!IsInitialBlockDownload())
3187 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3191 else if (pfrom->nVersion == 0)
3193 // Must have a version message before anything else
3194 pfrom->Misbehaving(1);
3199 else if (strCommand == "verack")
3201 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3205 else if (strCommand == "addr")
3207 vector<CAddress> vAddr;
3210 // Don't want addr from older versions unless seeding
3211 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3213 if (vAddr.size() > 1000)
3215 pfrom->Misbehaving(20);
3216 return error("message addr size() = %"PRIszu"", vAddr.size());
3219 // Store the new addresses
3220 vector<CAddress> vAddrOk;
3221 int64 nNow = GetAdjustedTime();
3222 int64 nSince = nNow - 10 * 60;
3223 BOOST_FOREACH(CAddress& addr, vAddr)
3227 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3228 addr.nTime = nNow - 5 * 24 * 60 * 60;
3229 pfrom->AddAddressKnown(addr);
3230 bool fReachable = IsReachable(addr);
3231 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3233 // Relay to a limited number of other nodes
3236 // Use deterministic randomness to send to the same nodes for 24 hours
3237 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3238 static uint256 hashSalt;
3240 hashSalt = GetRandHash();
3241 uint64 hashAddr = addr.GetHash();
3242 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3243 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3244 multimap<uint256, CNode*> mapMix;
3245 BOOST_FOREACH(CNode* pnode, vNodes)
3247 if (pnode->nVersion < CADDR_TIME_VERSION)
3249 unsigned int nPointer;
3250 memcpy(&nPointer, &pnode, sizeof(nPointer));
3251 uint256 hashKey = hashRand ^ nPointer;
3252 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3253 mapMix.insert(make_pair(hashKey, pnode));
3255 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3256 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3257 ((*mi).second)->PushAddress(addr);
3260 // Do not store addresses outside our network
3262 vAddrOk.push_back(addr);
3264 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3265 if (vAddr.size() < 1000)
3266 pfrom->fGetAddr = false;
3267 if (pfrom->fOneShot)
3268 pfrom->fDisconnect = true;
3272 else if (strCommand == "inv")
3276 if (vInv.size() > MAX_INV_SZ)
3278 pfrom->Misbehaving(20);
3279 return error("message inv size() = %"PRIszu"", vInv.size());
3282 // find last block in inv vector
3283 unsigned int nLastBlock = (unsigned int)(-1);
3284 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3285 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3286 nLastBlock = vInv.size() - 1 - nInv;
3291 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3293 const CInv &inv = vInv[nInv];
3297 pfrom->AddInventoryKnown(inv);
3299 bool fAlreadyHave = AlreadyHave(txdb, inv);
3301 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3305 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3306 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3307 } else if (nInv == nLastBlock) {
3308 // In case we are on a very long side-chain, it is possible that we already have
3309 // the last block in an inv bundle sent in response to getblocks. Try to detect
3310 // this situation and push another getblocks to continue.
3311 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3313 printf("force request: %s\n", inv.ToString().c_str());
3316 // Track requests for our stuff
3317 Inventory(inv.hash);
3322 else if (strCommand == "getdata")
3326 if (vInv.size() > MAX_INV_SZ)
3328 pfrom->Misbehaving(20);
3329 return error("message getdata size() = %"PRIszu"", vInv.size());
3332 if (fDebugNet || (vInv.size() != 1))
3333 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3335 BOOST_FOREACH(const CInv& inv, vInv)
3339 if (fDebugNet || (vInv.size() == 1))
3340 printf("received getdata for: %s\n", inv.ToString().c_str());
3342 if (inv.type == MSG_BLOCK)
3344 // Send block from disk
3345 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3346 if (mi != mapBlockIndex.end())
3349 block.ReadFromDisk((*mi).second);
3350 pfrom->PushMessage("block", block);
3352 // Trigger them to send a getblocks request for the next batch of inventory
3353 if (inv.hash == pfrom->hashContinue)
3355 // ppcoin: send latest proof-of-work block to allow the
3356 // download node to accept as orphan (proof-of-stake
3357 // block might be rejected by stake connection check)
3359 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3360 pfrom->PushMessage("inv", vInv);
3361 pfrom->hashContinue = 0;
3365 else if (inv.IsKnownType())
3367 // Send stream from relay memory
3368 bool pushed = false;
3371 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3372 if (mi != mapRelay.end()) {
3373 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3377 if (!pushed && inv.type == MSG_TX) {
3379 if (mempool.exists(inv.hash)) {
3380 CTransaction tx = mempool.lookup(inv.hash);
3381 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3384 pfrom->PushMessage("tx", ss);
3389 // Track requests for our stuff
3390 Inventory(inv.hash);
3395 else if (strCommand == "getblocks")
3397 CBlockLocator locator;
3399 vRecv >> locator >> hashStop;
3401 // Find the last block the caller has in the main chain
3402 CBlockIndex* pindex = locator.GetBlockIndex();
3404 // Send the rest of the chain
3406 pindex = pindex->pnext;
3408 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3409 for (; pindex; pindex = pindex->pnext)
3411 if (pindex->GetBlockHash() == hashStop)
3413 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3414 // ppcoin: tell downloading node about the latest block if it's
3415 // without risk being rejected due to stake connection check
3416 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3417 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3420 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3423 // When this block is requested, we'll send an inv that'll make them
3424 // getblocks the next batch of inventory.
3425 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3426 pfrom->hashContinue = pindex->GetBlockHash();
3431 else if (strCommand == "checkpoint")
3433 CSyncCheckpoint checkpoint;
3434 vRecv >> checkpoint;
3436 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3439 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3441 BOOST_FOREACH(CNode* pnode, vNodes)
3442 checkpoint.RelayTo(pnode);
3446 else if (strCommand == "getheaders")
3448 CBlockLocator locator;
3450 vRecv >> locator >> hashStop;
3452 CBlockIndex* pindex = NULL;
3453 if (locator.IsNull())
3455 // If locator is null, return the hashStop block
3456 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3457 if (mi == mapBlockIndex.end())
3459 pindex = (*mi).second;
3463 // Find the last block the caller has in the main chain
3464 pindex = locator.GetBlockIndex();
3466 pindex = pindex->pnext;
3469 vector<CBlock> vHeaders;
3471 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3472 for (; pindex; pindex = pindex->pnext)
3474 vHeaders.push_back(pindex->GetBlockHeader());
3475 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3478 pfrom->PushMessage("headers", vHeaders);
3482 else if (strCommand == "tx")
3484 vector<uint256> vWorkQueue;
3485 vector<uint256> vEraseQueue;
3486 CDataStream vMsg(vRecv);
3491 CInv inv(MSG_TX, tx.GetHash());
3492 pfrom->AddInventoryKnown(inv);
3494 // Truncate messages to the size of the tx in them
3495 unsigned int nSize = ::GetSerializeSize(tx,SER_NETWORK, PROTOCOL_VERSION);
3496 if (nSize < vMsg.size()){
3500 bool fMissingInputs = false;
3501 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3503 SyncWithWallets(tx, NULL, true);
3504 RelayMessage(inv, vMsg);
3505 mapAlreadyAskedFor.erase(inv);
3506 vWorkQueue.push_back(inv.hash);
3507 vEraseQueue.push_back(inv.hash);
3509 // Recursively process any orphan transactions that depended on this one
3510 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3512 uint256 hashPrev = vWorkQueue[i];
3513 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3514 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3517 const CDataStream& vMsg = *((*mi).second);
3519 CDataStream(vMsg) >> tx;
3520 CInv inv(MSG_TX, tx.GetHash());
3521 bool fMissingInputs2 = false;
3523 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3525 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3526 SyncWithWallets(tx, NULL, true);
3527 RelayMessage(inv, vMsg);
3528 mapAlreadyAskedFor.erase(inv);
3529 vWorkQueue.push_back(inv.hash);
3530 vEraseQueue.push_back(inv.hash);
3532 else if (!fMissingInputs2)
3535 vEraseQueue.push_back(inv.hash);
3536 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3541 BOOST_FOREACH(uint256 hash, vEraseQueue)
3542 EraseOrphanTx(hash);
3544 else if (fMissingInputs)
3548 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3549 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3551 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3553 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3557 else if (strCommand == "block")
3561 uint256 hashBlock = block.GetHash();
3563 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3566 CInv inv(MSG_BLOCK, hashBlock);
3567 pfrom->AddInventoryKnown(inv);
3569 if (ProcessBlock(pfrom, &block))
3570 mapAlreadyAskedFor.erase(inv);
3571 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3575 else if (strCommand == "getaddr")
3577 // Don't return addresses older than nCutOff timestamp
3578 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3579 pfrom->vAddrToSend.clear();
3580 vector<CAddress> vAddr = addrman.GetAddr();
3581 BOOST_FOREACH(const CAddress &addr, vAddr)
3582 if(addr.nTime > nCutOff)
3583 pfrom->PushAddress(addr);
3587 else if (strCommand == "mempool")
3589 std::vector<uint256> vtxid;
3590 mempool.queryHashes(vtxid);
3592 for (unsigned int i = 0; i < vtxid.size(); i++) {
3593 CInv inv(MSG_TX, vtxid[i]);
3594 vInv.push_back(inv);
3595 if (i == (MAX_INV_SZ - 1))
3598 if (vInv.size() > 0)
3599 pfrom->PushMessage("inv", vInv);
3603 else if (strCommand == "checkorder")
3608 if (!GetBoolArg("-allowreceivebyip"))
3610 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3617 /// we have a chance to check the order here
3619 // Keep giving the same key to the same ip until they use it
3620 if (!mapReuseKey.count(pfrom->addr))
3621 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3623 // Send back approval of order and pubkey to use
3624 CScript scriptPubKey;
3625 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3626 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3630 else if (strCommand == "reply")
3635 CRequestTracker tracker;
3637 LOCK(pfrom->cs_mapRequests);
3638 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3639 if (mi != pfrom->mapRequests.end())
3641 tracker = (*mi).second;
3642 pfrom->mapRequests.erase(mi);
3645 if (!tracker.IsNull())
3646 tracker.fn(tracker.param1, vRecv);
3650 else if (strCommand == "ping")
3652 if (pfrom->nVersion > BIP0031_VERSION)
3656 // Echo the message back with the nonce. This allows for two useful features:
3658 // 1) A remote node can quickly check if the connection is operational
3659 // 2) Remote nodes can measure the latency of the network thread. If this node
3660 // is overloaded it won't respond to pings quickly and the remote node can
3661 // avoid sending us more work, like chain download requests.
3663 // The nonce stops the remote getting confused between different pings: without
3664 // it, if the remote node sends a ping once per second and this node takes 5
3665 // seconds to respond to each, the 5th ping the remote sends would appear to
3666 // return very quickly.
3667 pfrom->PushMessage("pong", nonce);
3672 else if (strCommand == "alert")
3677 uint256 alertHash = alert.GetHash();
3678 if (pfrom->setKnown.count(alertHash) == 0)
3680 if (alert.ProcessAlert())
3683 pfrom->setKnown.insert(alertHash);
3686 BOOST_FOREACH(CNode* pnode, vNodes)
3687 alert.RelayTo(pnode);
3691 // Small DoS penalty so peers that send us lots of
3692 // duplicate/expired/invalid-signature/whatever alerts
3693 // eventually get banned.
3694 // This isn't a Misbehaving(100) (immediate ban) because the
3695 // peer might be an older or different implementation with
3696 // a different signature key, etc.
3697 pfrom->Misbehaving(10);
3705 // Ignore unknown commands for extensibility
3709 // Update the last seen time for this node's address
3710 if (pfrom->fNetworkNode)
3711 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3712 AddressCurrentlyConnected(pfrom->addr);
3718 bool ProcessMessages(CNode* pfrom)
3720 CDataStream& vRecv = pfrom->vRecv;
3724 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3728 // (4) message start
3737 // Don't bother if send buffer is too full to respond anyway
3738 if (pfrom->vSend.size() >= SendBufferSize())
3741 // Scan for message start
3742 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3743 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3744 if (vRecv.end() - pstart < nHeaderSize)
3746 if ((int)vRecv.size() > nHeaderSize)
3748 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3749 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3753 if (pstart - vRecv.begin() > 0)
3754 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3755 vRecv.erase(vRecv.begin(), pstart);
3758 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3763 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3766 string strCommand = hdr.GetCommand();
3769 unsigned int nMessageSize = hdr.nMessageSize;
3770 if (nMessageSize > MAX_SIZE)
3772 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3775 if (nMessageSize > vRecv.size())
3777 // Rewind and wait for rest of message
3778 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3783 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3784 unsigned int nChecksum = 0;
3785 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3786 if (nChecksum != hdr.nChecksum)
3788 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3789 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3793 // Copy message to its own buffer
3794 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3795 vRecv.ignore(nMessageSize);
3803 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3808 catch (std::ios_base::failure& e)
3810 if (strstr(e.what(), "end of data"))
3812 // Allow exceptions from under-length message on vRecv
3813 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());
3815 else if (strstr(e.what(), "size too large"))
3817 // Allow exceptions from over-long size
3818 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3822 PrintExceptionContinue(&e, "ProcessMessages()");
3825 catch (std::exception& e) {
3826 PrintExceptionContinue(&e, "ProcessMessages()");
3828 PrintExceptionContinue(NULL, "ProcessMessages()");
3832 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3840 bool SendMessages(CNode* pto, bool fSendTrickle)
3842 TRY_LOCK(cs_main, lockMain);
3844 // Don't send anything until we get their version message
3845 if (pto->nVersion == 0)
3848 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3850 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3852 if (pto->nVersion > BIP0031_VERSION)
3853 pto->PushMessage("ping", nonce);
3855 pto->PushMessage("ping");
3858 // Resend wallet transactions that haven't gotten in a block yet
3859 ResendWalletTransactions();
3861 // Address refresh broadcast
3862 static int64 nLastRebroadcast;
3863 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3867 BOOST_FOREACH(CNode* pnode, vNodes)
3869 // Periodically clear setAddrKnown to allow refresh broadcasts
3870 if (nLastRebroadcast)
3871 pnode->setAddrKnown.clear();
3873 // Rebroadcast our address
3876 CAddress addr = GetLocalAddress(&pnode->addr);
3877 if (addr.IsRoutable())
3878 pnode->PushAddress(addr);
3882 nLastRebroadcast = GetTime();
3890 vector<CAddress> vAddr;
3891 vAddr.reserve(pto->vAddrToSend.size());
3892 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3894 // returns true if wasn't already contained in the set
3895 if (pto->setAddrKnown.insert(addr).second)
3897 vAddr.push_back(addr);
3898 // receiver rejects addr messages larger than 1000
3899 if (vAddr.size() >= 1000)
3901 pto->PushMessage("addr", vAddr);
3906 pto->vAddrToSend.clear();
3908 pto->PushMessage("addr", vAddr);
3913 // Message: inventory
3916 vector<CInv> vInvWait;
3918 LOCK(pto->cs_inventory);
3919 vInv.reserve(pto->vInventoryToSend.size());
3920 vInvWait.reserve(pto->vInventoryToSend.size());
3921 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3923 if (pto->setInventoryKnown.count(inv))
3926 // trickle out tx inv to protect privacy
3927 if (inv.type == MSG_TX && !fSendTrickle)
3929 // 1/4 of tx invs blast to all immediately
3930 static uint256 hashSalt;
3932 hashSalt = GetRandHash();
3933 uint256 hashRand = inv.hash ^ hashSalt;
3934 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3935 bool fTrickleWait = ((hashRand & 3) != 0);
3937 // always trickle our own transactions
3941 if (GetTransaction(inv.hash, wtx))
3943 fTrickleWait = true;
3948 vInvWait.push_back(inv);
3953 // returns true if wasn't already contained in the set
3954 if (pto->setInventoryKnown.insert(inv).second)
3956 vInv.push_back(inv);
3957 if (vInv.size() >= 1000)
3959 pto->PushMessage("inv", vInv);
3964 pto->vInventoryToSend = vInvWait;
3967 pto->PushMessage("inv", vInv);
3973 vector<CInv> vGetData;
3974 int64 nNow = GetTime() * 1000000;
3976 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3978 const CInv& inv = (*pto->mapAskFor.begin()).second;
3979 if (!AlreadyHave(txdb, inv))
3982 printf("sending getdata: %s\n", inv.ToString().c_str());
3983 vGetData.push_back(inv);
3984 if (vGetData.size() >= 1000)
3986 pto->PushMessage("getdata", vGetData);
3989 mapAlreadyAskedFor[inv] = nNow;
3991 pto->mapAskFor.erase(pto->mapAskFor.begin());
3993 if (!vGetData.empty())
3994 pto->PushMessage("getdata", vGetData);