1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
12 #include "ui_interface.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
19 using namespace boost;
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
31 unsigned int nTransactionsUpdated = 0;
33 map<uint256, CBlockIndex*> mapBlockIndex;
34 set<pair<COutPoint, unsigned int> > setStakeSeen;
36 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
37 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
38 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
39 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
40 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
42 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
44 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as minimum age for coin age
45 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as stake age of full weight
46 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
47 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
49 int nCoinbaseMaturity = 500;
50 CBlockIndex* pindexGenesisBlock = NULL;
53 uint256 nBestChainTrust = 0;
54 uint256 nBestInvalidTrust = 0;
56 uint256 hashBestChain = 0;
57 CBlockIndex* pindexBest = NULL;
58 int64 nTimeBestReceived = 0;
60 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
62 map<uint256, CBlock*> mapOrphanBlocks;
63 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
64 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
65 map<uint256, uint256> mapProofOfStake;
67 map<uint256, CTransaction> mapOrphanTransactions;
68 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
70 // Constant stuff for coinbase transactions we create:
71 CScript COINBASE_FLAGS;
73 const string strMessageMagic = "NovaCoin Signed Message:\n";
76 int64 nTransactionFee = MIN_TX_FEE;
77 bool fStakeUsePooledKeys = false;
78 extern enum Checkpoints::CPMode CheckpointsMode;
80 //////////////////////////////////////////////////////////////////////////////
82 // dispatching functions
85 // These functions dispatch to one or all registered wallets
88 void RegisterWallet(CWallet* pwalletIn)
91 LOCK(cs_setpwalletRegistered);
92 setpwalletRegistered.insert(pwalletIn);
96 void UnregisterWallet(CWallet* pwalletIn)
99 LOCK(cs_setpwalletRegistered);
100 setpwalletRegistered.erase(pwalletIn);
104 // check whether the passed transaction is from us
105 bool static IsFromMe(CTransaction& tx)
107 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
108 if (pwallet->IsFromMe(tx))
113 // get the wallet transaction with the given hash (if it exists)
114 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
116 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
117 if (pwallet->GetTransaction(hashTx,wtx))
122 // erases transaction with the given hash from all wallets
123 void static EraseFromWallets(uint256 hash)
125 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126 pwallet->EraseFromWallet(hash);
129 // make sure all wallets know about the given transaction, in the given block
130 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
134 // ppcoin: wallets need to refund inputs when disconnecting coinstake
135 if (tx.IsCoinStake())
137 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
138 if (pwallet->IsFromMe(tx))
139 pwallet->DisableTransaction(tx);
144 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
145 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
148 // notify wallets about a new best chain
149 void static SetBestChain(const CBlockLocator& loc)
151 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
152 pwallet->SetBestChain(loc);
155 // notify wallets about an updated transaction
156 void static UpdatedTransaction(const uint256& hashTx)
158 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
159 pwallet->UpdatedTransaction(hashTx);
163 void static PrintWallets(const CBlock& block)
165 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
166 pwallet->PrintWallet(block);
169 // notify wallets about an incoming inventory (for request counts)
170 void static Inventory(const uint256& hash)
172 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
173 pwallet->Inventory(hash);
176 // ask wallets to resend their transactions
177 void ResendWalletTransactions()
179 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
180 pwallet->ResendWalletTransactions();
189 //////////////////////////////////////////////////////////////////////////////
191 // mapOrphanTransactions
194 bool AddOrphanTx(const CTransaction& tx)
196 uint256 hash = tx.GetHash();
197 if (mapOrphanTransactions.count(hash))
200 // Ignore big transactions, to avoid a
201 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
202 // large transaction with a missing parent then we assume
203 // it will rebroadcast it later, after the parent transaction(s)
204 // have been mined or received.
205 // 10,000 orphans, each of which is at most 5,000 bytes big is
206 // at most 500 megabytes of orphans:
208 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
212 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
216 mapOrphanTransactions[hash] = tx;
217 BOOST_FOREACH(const CTxIn& txin, tx.vin)
218 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
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 CTransaction& tx = mapOrphanTransactions[hash];
230 BOOST_FOREACH(const CTxIn& txin, tx.vin)
232 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
233 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
234 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
236 mapOrphanTransactions.erase(hash);
239 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
241 unsigned int nEvicted = 0;
242 while (mapOrphanTransactions.size() > nMaxOrphans)
244 // Evict a random orphan:
245 uint256 randomhash = GetRandHash();
246 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
247 if (it == mapOrphanTransactions.end())
248 it = mapOrphanTransactions.begin();
249 EraseOrphanTx(it->first);
261 //////////////////////////////////////////////////////////////////////////////
263 // CTransaction and CTxIndex
266 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
269 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
271 if (!ReadFromDisk(txindexRet.pos))
273 if (prevout.n >= vout.size())
281 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
284 return ReadFromDisk(txdb, prevout, txindex);
287 bool CTransaction::ReadFromDisk(COutPoint prevout)
291 return ReadFromDisk(txdb, prevout, txindex);
294 bool CTransaction::IsStandard() const
296 if (nVersion > CTransaction::CURRENT_VERSION)
299 BOOST_FOREACH(const CTxIn& txin, vin)
301 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
302 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
303 // ~65-byte public keys, plus a few script ops.
304 if (txin.scriptSig.size() > 500)
306 if (!txin.scriptSig.IsPushOnly())
309 BOOST_FOREACH(const CTxOut& txout, vout) {
310 if (!::IsStandard(txout.scriptPubKey))
312 if (txout.nValue == 0)
319 // Check transaction inputs, and make sure any
320 // pay-to-script-hash transactions are evaluating IsStandard scripts
322 // Why bother? To avoid denial-of-service attacks; an attacker
323 // can submit a standard HASH... OP_EQUAL transaction,
324 // which will get accepted into blocks. The redemption
325 // script can be anything; an attacker could use a very
326 // expensive-to-check-upon-redemption script like:
327 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
329 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
332 return true; // Coinbases don't use vin normally
334 for (unsigned int i = 0; i < vin.size(); i++)
336 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
338 vector<vector<unsigned char> > vSolutions;
339 txnouttype whichType;
340 // get the scriptPubKey corresponding to this input:
341 const CScript& prevScript = prev.scriptPubKey;
342 if (!Solver(prevScript, whichType, vSolutions))
344 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
345 if (nArgsExpected < 0)
348 // Transactions with extra stuff in their scriptSigs are
349 // non-standard. Note that this EvalScript() call will
350 // be quick, because if there are any operations
351 // beside "push data" in the scriptSig the
352 // IsStandard() call returns false
353 vector<vector<unsigned char> > stack;
354 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
357 if (whichType == TX_SCRIPTHASH)
361 CScript subscript(stack.back().begin(), stack.back().end());
362 vector<vector<unsigned char> > vSolutions2;
363 txnouttype whichType2;
364 if (!Solver(subscript, whichType2, vSolutions2))
366 if (whichType2 == TX_SCRIPTHASH)
370 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
373 nArgsExpected += tmpExpected;
376 if (stack.size() != (unsigned int)nArgsExpected)
384 CTransaction::GetLegacySigOpCount() const
386 unsigned int nSigOps = 0;
387 BOOST_FOREACH(const CTxIn& txin, vin)
389 nSigOps += txin.scriptSig.GetSigOpCount(false);
391 BOOST_FOREACH(const CTxOut& txout, vout)
393 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
399 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
411 // Load the block this tx is in
413 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
415 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
420 // Update the tx's hashBlock
421 hashBlock = pblock->GetHash();
423 // Locate the transaction
424 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
425 if (pblock->vtx[nIndex] == *(CTransaction*)this)
427 if (nIndex == (int)pblock->vtx.size())
429 vMerkleBranch.clear();
431 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
435 // Fill in merkle branch
436 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
439 // Is the tx in a block that's in the main chain
440 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
441 if (mi == mapBlockIndex.end())
443 CBlockIndex* pindex = (*mi).second;
444 if (!pindex || !pindex->IsInMainChain())
447 return pindexBest->nHeight - pindex->nHeight + 1;
456 bool CTransaction::CheckTransaction() const
458 // Basic checks that don't depend on any context
460 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
462 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
464 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
465 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
467 // Check for negative or overflow output values
469 for (unsigned int i = 0; i < vout.size(); i++)
471 const CTxOut& txout = vout[i];
472 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
473 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
475 // NovaCoin: enforce minimum output amount for user transactions
476 // (and for all transactions until 20 Sep 2013)
477 if ((!IsCoinBase() || nTime < CHAINCHECKS_SWITCH_TIME)
478 && (!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
479 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
481 if (txout.nValue > MAX_MONEY)
482 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
483 nValueOut += txout.nValue;
484 if (!MoneyRange(nValueOut))
485 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
488 // Check for duplicate inputs
489 set<COutPoint> vInOutPoints;
490 BOOST_FOREACH(const CTxIn& txin, vin)
492 if (vInOutPoints.count(txin.prevout))
494 vInOutPoints.insert(txin.prevout);
499 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
500 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
504 BOOST_FOREACH(const CTxIn& txin, vin)
505 if (txin.prevout.IsNull())
506 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
512 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
513 enum GetMinFee_mode mode) const
515 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
516 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
518 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
519 unsigned int nNewBlockSize = nBlockSize + nBytes;
520 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
522 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
523 if (nMinFee < nBaseFee)
525 BOOST_FOREACH(const CTxOut& txout, vout)
526 if (txout.nValue < CENT)
530 // Raise the price as the block approaches full
531 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
533 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
535 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
538 if (!MoneyRange(nMinFee))
544 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
545 bool* pfMissingInputs)
548 *pfMissingInputs = false;
550 if (!tx.CheckTransaction())
551 return error("CTxMemPool::accept() : CheckTransaction failed");
553 // Coinbase is only valid in a block, not as a loose transaction
555 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
557 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
558 if (tx.IsCoinStake())
559 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
561 // To help v0.1.5 clients who would see it as a negative number
562 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
563 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
565 // Rather not work on nonstandard transactions (unless -testnet)
566 if (!fTestNet && !tx.IsStandard())
567 return error("CTxMemPool::accept() : nonstandard transaction type");
569 // Do we already have it?
570 uint256 hash = tx.GetHash();
573 if (mapTx.count(hash))
577 if (txdb.ContainsTx(hash))
580 // Check for conflicts with in-memory transactions
581 CTransaction* ptxOld = NULL;
582 for (unsigned int i = 0; i < tx.vin.size(); i++)
584 COutPoint outpoint = tx.vin[i].prevout;
585 if (mapNextTx.count(outpoint))
587 // Disable replacement feature for now
590 // Allow replacing with a newer version of the same transaction
593 ptxOld = mapNextTx[outpoint].ptx;
594 if (ptxOld->IsFinal())
596 if (!tx.IsNewerThan(*ptxOld))
598 for (unsigned int i = 0; i < tx.vin.size(); i++)
600 COutPoint outpoint = tx.vin[i].prevout;
601 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
611 map<uint256, CTxIndex> mapUnused;
612 bool fInvalid = false;
613 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
616 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
618 *pfMissingInputs = true;
622 // Check for non-standard pay-to-script-hash in inputs
623 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
624 return error("CTxMemPool::accept() : nonstandard transaction input");
626 // Note: if you modify this code to accept non-standard transactions, then
627 // you should add code here to check that the transaction does a
628 // reasonable number of ECDSA signature verifications.
630 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
631 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
633 // Don't accept it if it can't get into a block
634 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY);
635 if (nFees < txMinFee)
636 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
637 hash.ToString().c_str(),
640 // Continuously rate-limit free transactions
641 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
642 // be annoying or make others' transactions take longer to confirm.
643 if (nFees < MIN_RELAY_TX_FEE)
645 static CCriticalSection cs;
646 static double dFreeCount;
647 static int64 nLastTime;
648 int64 nNow = GetTime();
652 // Use an exponentially decaying ~10-minute window:
653 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
655 // -limitfreerelay unit is thousand-bytes-per-minute
656 // At default rate it would take over a month to fill 1GB
657 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
658 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
660 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
665 // Check against previous transactions
666 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
667 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
669 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
673 // Store transaction in memory
678 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
681 addUnchecked(hash, tx);
684 ///// are we sure this is ok when loading transactions or restoring block txes
685 // If updated, erase old tx from wallet
687 EraseFromWallets(ptxOld->GetHash());
689 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
690 hash.ToString().substr(0,10).c_str(),
695 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
697 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
700 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
702 // Add to memory pool without checking anything. Don't call this directly,
703 // call CTxMemPool::accept to properly check the transaction first.
706 for (unsigned int i = 0; i < tx.vin.size(); i++)
707 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
708 nTransactionsUpdated++;
714 bool CTxMemPool::remove(CTransaction &tx)
716 // Remove transaction from memory pool
719 uint256 hash = tx.GetHash();
720 if (mapTx.count(hash))
722 BOOST_FOREACH(const CTxIn& txin, tx.vin)
723 mapNextTx.erase(txin.prevout);
725 nTransactionsUpdated++;
731 void CTxMemPool::clear()
736 ++nTransactionsUpdated;
739 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
744 vtxid.reserve(mapTx.size());
745 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
746 vtxid.push_back((*mi).first);
752 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
754 if (hashBlock == 0 || nIndex == -1)
757 // Find the block it claims to be in
758 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
759 if (mi == mapBlockIndex.end())
761 CBlockIndex* pindex = (*mi).second;
762 if (!pindex || !pindex->IsInMainChain())
765 // Make sure the merkle branch connects to this block
766 if (!fMerkleVerified)
768 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
770 fMerkleVerified = true;
774 return pindexBest->nHeight - pindex->nHeight + 1;
778 int CMerkleTx::GetBlocksToMaturity() const
780 if (!(IsCoinBase() || IsCoinStake()))
782 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
786 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
790 if (!IsInMainChain() && !ClientConnectInputs())
792 return CTransaction::AcceptToMemoryPool(txdb, false);
796 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
800 bool CMerkleTx::AcceptToMemoryPool()
803 return AcceptToMemoryPool(txdb);
808 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
813 // Add previous supporting transactions first
814 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
816 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
818 uint256 hash = tx.GetHash();
819 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
820 tx.AcceptToMemoryPool(txdb, fCheckInputs);
823 return AcceptToMemoryPool(txdb, fCheckInputs);
828 bool CWalletTx::AcceptWalletTransaction()
831 return AcceptWalletTransaction(txdb);
834 int CTxIndex::GetDepthInMainChain() const
838 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
840 // Find the block in the index
841 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
842 if (mi == mapBlockIndex.end())
844 CBlockIndex* pindex = (*mi).second;
845 if (!pindex || !pindex->IsInMainChain())
847 return 1 + nBestHeight - pindex->nHeight;
850 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
851 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
857 if (mempool.exists(hash))
859 tx = mempool.lookup(hash);
865 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
868 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
869 hashBlock = block.GetHash();
883 //////////////////////////////////////////////////////////////////////////////
885 // CBlock and CBlockIndex
888 static CBlockIndex* pblockindexFBBHLast;
889 CBlockIndex* FindBlockByHeight(int nHeight)
891 CBlockIndex *pblockindex;
892 if (nHeight < nBestHeight / 2)
893 pblockindex = pindexGenesisBlock;
895 pblockindex = pindexBest;
896 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
897 pblockindex = pblockindexFBBHLast;
898 while (pblockindex->nHeight > nHeight)
899 pblockindex = pblockindex->pprev;
900 while (pblockindex->nHeight < nHeight)
901 pblockindex = pblockindex->pnext;
902 pblockindexFBBHLast = pblockindex;
906 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
908 if (!fReadTransactions)
910 *this = pindex->GetBlockHeader();
913 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
915 if (GetHash() != pindex->GetBlockHash())
916 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
920 uint256 static GetOrphanRoot(const CBlock* pblock)
922 // Work back to the first block in the orphan chain
923 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
924 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
925 return pblock->GetHash();
928 // ppcoin: find block wanted by given orphan block
929 uint256 WantedByOrphan(const CBlock* pblockOrphan)
931 // Work back to the first block in the orphan chain
932 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
933 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
934 return pblockOrphan->hashPrevBlock;
937 // select stake target limit according to hard-coded conditions
938 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
940 if(fTestNet) // separate proof of stake target limit for testnet
941 return bnProofOfStakeLimit;
942 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
943 return bnProofOfStakeLimit;
944 if(nHeight + 1 > 15000) // 24 bits since block 15000
945 return bnProofOfStakeLegacyLimit;
946 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
947 return bnProofOfStakeHardLimit;
949 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
952 // miner's coin base reward based on nBits
953 int64 GetProofOfWorkReward(unsigned int nBits)
955 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
958 bnTarget.SetCompact(nBits);
959 CBigNum bnTargetLimit = bnProofOfWorkLimit;
960 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
962 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
963 // A reasonably continuous curve is used to avoid shock to market
964 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
966 // Human readable form:
968 // nSubsidy = 100 / (diff ^ 1/6)
969 CBigNum bnLowerBound = CENT;
970 CBigNum bnUpperBound = bnSubsidyLimit;
971 while (bnLowerBound + CENT <= bnUpperBound)
973 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
974 if (fDebug && GetBoolArg("-printcreation"))
975 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
976 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
977 bnUpperBound = bnMidValue;
979 bnLowerBound = bnMidValue;
982 int64 nSubsidy = bnUpperBound.getuint64();
984 nSubsidy = (nSubsidy / CENT) * CENT;
985 if (fDebug && GetBoolArg("-printcreation"))
986 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
988 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
991 // miner's coin stake reward based on nBits and coin age spent (coin-days)
992 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
994 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
996 if(fTestNet || nTime > STAKE_SWITCH_TIME)
998 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1000 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1002 bnTarget.SetCompact(nBits);
1003 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1004 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1006 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1008 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1009 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1010 bnMidPart, bnRewardPart;
1012 while (bnLowerBound + CENT <= bnUpperBound)
1014 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1015 if (fDebug && GetBoolArg("-printcreation"))
1016 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1018 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1021 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1023 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1025 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1028 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1029 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1034 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1036 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1038 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1041 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1042 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1045 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1046 bnUpperBound = bnMidValue;
1048 bnLowerBound = bnMidValue;
1051 nRewardCoinYear = bnUpperBound.getuint64();
1052 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1056 // Old creation amount per coin-year, 5% fixed stake mint rate
1057 nRewardCoinYear = 5 * CENT;
1061 return nRewardCoinYear;
1063 // Fix problem with proof-of-stake rewards calculation since 20 Sep 2013
1064 if(nTime < CHAINCHECKS_SWITCH_TIME)
1065 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
1067 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1069 // Set reasonable reward limit for large inputs since 20 Oct 2013
1071 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1072 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1074 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1075 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1077 nSubsidy = min(nSubsidy, nSubsidyLimit);
1080 if (fDebug && GetBoolArg("-printcreation"))
1081 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1085 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1087 // get proof of work blocks max spacing according to hard-coded conditions
1088 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1090 if(nTime > TARGETS_SWITCH_TIME)
1091 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1094 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1096 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1100 // maximum nBits value could possible be required nTime after
1102 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1105 bnResult.SetCompact(nBase);
1107 while (nTime > 0 && bnResult < bnTargetLimit)
1109 // Maximum 200% adjustment per day...
1111 nTime -= 24 * 60 * 60;
1113 if (bnResult > bnTargetLimit)
1114 bnResult = bnTargetLimit;
1115 return bnResult.GetCompact();
1119 // minimum amount of work that could possibly be required nTime after
1120 // minimum proof-of-work required was nBase
1122 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1124 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1128 // minimum amount of stake that could possibly be required nTime after
1129 // minimum proof-of-stake required was nBase
1131 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1133 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1137 // ppcoin: find last block index up to pindex
1138 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1140 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1141 pindex = pindex->pprev;
1145 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1147 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1149 if (pindexLast == NULL)
1150 return bnTargetLimit.GetCompact(); // genesis block
1152 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1153 if (pindexPrev->pprev == NULL)
1154 return bnTargetLimit.GetCompact(); // first block
1155 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1156 if (pindexPrevPrev->pprev == NULL)
1157 return bnTargetLimit.GetCompact(); // second block
1159 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1161 // ppcoin: target change every block
1162 // ppcoin: retarget with exponential moving toward target spacing
1164 bnNew.SetCompact(pindexPrev->nBits);
1165 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1166 int64 nInterval = nTargetTimespan / nTargetSpacing;
1167 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1168 bnNew /= ((nInterval + 1) * nTargetSpacing);
1170 if (bnNew > bnTargetLimit)
1171 bnNew = bnTargetLimit;
1173 return bnNew.GetCompact();
1176 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1179 bnTarget.SetCompact(nBits);
1182 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1183 return error("CheckProofOfWork() : nBits below minimum work");
1185 // Check proof of work matches claimed amount
1186 if (hash > bnTarget.getuint256())
1187 return error("CheckProofOfWork() : hash doesn't match nBits");
1192 // Return maximum amount of blocks that other nodes claim to have
1193 int GetNumBlocksOfPeers()
1195 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1198 bool IsInitialBlockDownload()
1200 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1202 static int64 nLastUpdate;
1203 static CBlockIndex* pindexLastBest;
1204 if (pindexBest != pindexLastBest)
1206 pindexLastBest = pindexBest;
1207 nLastUpdate = GetTime();
1209 return (GetTime() - nLastUpdate < 10 &&
1210 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1213 void static InvalidChainFound(CBlockIndex* pindexNew)
1215 if (pindexNew->nChainTrust > nBestInvalidTrust)
1217 nBestInvalidTrust = pindexNew->nChainTrust;
1218 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1219 uiInterface.NotifyBlocksChanged();
1222 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1223 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1225 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1226 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1227 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1228 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1229 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1230 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1231 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1232 nBestBlockTrust.Get64(),
1233 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1237 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1239 nTime = max(GetBlockTime(), GetAdjustedTime());
1252 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1254 // Relinquish previous transactions' spent pointers
1257 BOOST_FOREACH(const CTxIn& txin, vin)
1259 COutPoint prevout = txin.prevout;
1261 // Get prev txindex from disk
1263 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1264 return error("DisconnectInputs() : ReadTxIndex failed");
1266 if (prevout.n >= txindex.vSpent.size())
1267 return error("DisconnectInputs() : prevout.n out of range");
1269 // Mark outpoint as not spent
1270 txindex.vSpent[prevout.n].SetNull();
1273 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1274 return error("DisconnectInputs() : UpdateTxIndex failed");
1278 // Remove transaction from index
1279 // This can fail if a duplicate of this transaction was in a chain that got
1280 // reorganized away. This is only possible if this transaction was completely
1281 // spent, so erasing it would be a no-op anyway.
1282 txdb.EraseTxIndex(*this);
1288 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1289 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1291 // FetchInputs can return false either because we just haven't seen some inputs
1292 // (in which case the transaction should be stored as an orphan)
1293 // or because the transaction is malformed (in which case the transaction should
1294 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1298 return true; // Coinbase transactions have no inputs to fetch.
1300 for (unsigned int i = 0; i < vin.size(); i++)
1302 COutPoint prevout = vin[i].prevout;
1303 if (inputsRet.count(prevout.hash))
1304 continue; // Got it already
1307 CTxIndex& txindex = inputsRet[prevout.hash].first;
1309 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1311 // Get txindex from current proposed changes
1312 txindex = mapTestPool.find(prevout.hash)->second;
1316 // Read txindex from txdb
1317 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1319 if (!fFound && (fBlock || fMiner))
1320 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());
1323 CTransaction& txPrev = inputsRet[prevout.hash].second;
1324 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1326 // Get prev tx from single transactions in memory
1329 if (!mempool.exists(prevout.hash))
1330 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());
1331 txPrev = mempool.lookup(prevout.hash);
1334 txindex.vSpent.resize(txPrev.vout.size());
1338 // Get prev tx from disk
1339 if (!txPrev.ReadFromDisk(txindex.pos))
1340 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1344 // Make sure all prevout.n indexes are valid:
1345 for (unsigned int i = 0; i < vin.size(); i++)
1347 const COutPoint prevout = vin[i].prevout;
1348 assert(inputsRet.count(prevout.hash) != 0);
1349 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1350 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1351 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1353 // Revisit this if/when transaction replacement is implemented and allows
1356 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()));
1363 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1365 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1366 if (mi == inputs.end())
1367 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1369 const CTransaction& txPrev = (mi->second).second;
1370 if (input.prevout.n >= txPrev.vout.size())
1371 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1373 return txPrev.vout[input.prevout.n];
1376 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1382 for (unsigned int i = 0; i < vin.size(); i++)
1384 nResult += GetOutputFor(vin[i], inputs).nValue;
1390 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1395 unsigned int nSigOps = 0;
1396 for (unsigned int i = 0; i < vin.size(); i++)
1398 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1399 if (prevout.scriptPubKey.IsPayToScriptHash())
1400 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1405 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1406 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1407 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1409 // Take over previous transactions' spent pointers
1410 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1411 // fMiner is true when called from the internal bitcoin miner
1412 // ... both are false when called from CTransaction::AcceptToMemoryPool
1417 for (unsigned int i = 0; i < vin.size(); i++)
1419 COutPoint prevout = vin[i].prevout;
1420 assert(inputs.count(prevout.hash) > 0);
1421 CTxIndex& txindex = inputs[prevout.hash].first;
1422 CTransaction& txPrev = inputs[prevout.hash].second;
1424 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1425 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()));
1427 // If prev is coinbase or coinstake, check that it's matured
1428 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1429 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1430 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1431 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1433 // ppcoin: check transaction timestamp
1434 if (txPrev.nTime > nTime)
1435 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1437 // Check for negative or overflow input values
1438 nValueIn += txPrev.vout[prevout.n].nValue;
1439 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1440 return DoS(100, error("ConnectInputs() : txin values out of range"));
1443 // The first loop above does all the inexpensive checks.
1444 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1445 // Helps prevent CPU exhaustion attacks.
1446 for (unsigned int i = 0; i < vin.size(); i++)
1448 COutPoint prevout = vin[i].prevout;
1449 assert(inputs.count(prevout.hash) > 0);
1450 CTxIndex& txindex = inputs[prevout.hash].first;
1451 CTransaction& txPrev = inputs[prevout.hash].second;
1453 // Check for conflicts (double-spend)
1454 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1455 // for an attacker to attempt to split the network.
1456 if (!txindex.vSpent[prevout.n].IsNull())
1457 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());
1459 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1460 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1461 // still computed and checked, and any change will be caught at the next checkpoint.
1462 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1465 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1467 // only during transition phase for P2SH: do not invoke anti-DoS code for
1468 // potentially old clients relaying bad P2SH transactions
1469 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1470 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1472 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1476 // Mark outpoints as spent
1477 txindex.vSpent[prevout.n] = posThisTx;
1480 if (fBlock || fMiner)
1482 mapTestPool[prevout.hash] = txindex;
1488 // ppcoin: coin stake tx earns reward instead of paying fee
1490 if (!GetCoinAge(txdb, nCoinAge))
1491 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1493 int64 nStakeReward = GetValueOut() - nValueIn;
1494 int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1496 if (nStakeReward > nCalculatedStakeReward)
1497 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1501 if (nValueIn < GetValueOut())
1502 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1504 // Tally transaction fees
1505 int64 nTxFee = nValueIn - GetValueOut();
1507 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1508 // ppcoin: enforce transaction fees for every block
1509 if (nTxFee < GetMinFee())
1510 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;
1513 if (!MoneyRange(nFees))
1514 return DoS(100, error("ConnectInputs() : nFees out of range"));
1522 bool CTransaction::ClientConnectInputs()
1527 // Take over previous transactions' spent pointers
1531 for (unsigned int i = 0; i < vin.size(); i++)
1533 // Get prev tx from single transactions in memory
1534 COutPoint prevout = vin[i].prevout;
1535 if (!mempool.exists(prevout.hash))
1537 CTransaction& txPrev = mempool.lookup(prevout.hash);
1539 if (prevout.n >= txPrev.vout.size())
1543 if (!VerifySignature(txPrev, *this, i, true, 0))
1544 return error("ConnectInputs() : VerifySignature failed");
1546 ///// this is redundant with the mempool.mapNextTx stuff,
1547 ///// not sure which I want to get rid of
1548 ///// this has to go away now that posNext is gone
1549 // // Check for conflicts
1550 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1551 // return error("ConnectInputs() : prev tx already used");
1553 // // Flag outpoints as used
1554 // txPrev.vout[prevout.n].posNext = posThisTx;
1556 nValueIn += txPrev.vout[prevout.n].nValue;
1558 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1559 return error("ClientConnectInputs() : txin values out of range");
1561 if (GetValueOut() > nValueIn)
1571 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1573 // Disconnect in reverse order
1574 for (int i = vtx.size()-1; i >= 0; i--)
1575 if (!vtx[i].DisconnectInputs(txdb))
1578 // Update block index on disk without changing it in memory.
1579 // The memory index structure will be changed after the db commits.
1582 CDiskBlockIndex blockindexPrev(pindex->pprev);
1583 blockindexPrev.hashNext = 0;
1584 if (!txdb.WriteBlockIndex(blockindexPrev))
1585 return error("DisconnectBlock() : WriteBlockIndex failed");
1588 // ppcoin: clean up wallet after disconnecting coinstake
1589 BOOST_FOREACH(CTransaction& tx, vtx)
1590 SyncWithWallets(tx, this, false, false);
1595 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1597 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1598 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1601 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1602 // unless those are already completely spent.
1603 // If such overwrites are allowed, coinbases and transactions depending upon those
1604 // can be duplicated to remove the ability to spend the first instance -- even after
1605 // being sent to another address.
1606 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1607 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1608 // already refuses previously-known transaction ids entirely.
1609 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1610 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1611 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1612 // initial block download.
1613 bool fEnforceBIP30 = true; // Always active in NovaCoin
1614 bool fStrictPayToScriptHash = true; // Always active in NovaCoin
1616 //// issue here: it doesn't know the version
1617 unsigned int nTxPos;
1619 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1620 // 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
1623 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1625 map<uint256, CTxIndex> mapQueuedChanges;
1628 int64 nValueOut = 0;
1629 unsigned int nSigOps = 0;
1630 BOOST_FOREACH(CTransaction& tx, vtx)
1632 uint256 hashTx = tx.GetHash();
1634 if (fEnforceBIP30) {
1635 CTxIndex txindexOld;
1636 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1637 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1643 nSigOps += tx.GetLegacySigOpCount();
1644 if (nSigOps > MAX_BLOCK_SIGOPS)
1645 return DoS(100, error("ConnectBlock() : too many sigops"));
1647 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1649 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1651 MapPrevTx mapInputs;
1652 if (tx.IsCoinBase())
1653 nValueOut += tx.GetValueOut();
1657 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1660 if (fStrictPayToScriptHash)
1662 // Add in sigops done by pay-to-script-hash inputs;
1663 // this is to prevent a "rogue miner" from creating
1664 // an incredibly-expensive-to-validate block.
1665 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1666 if (nSigOps > MAX_BLOCK_SIGOPS)
1667 return DoS(100, error("ConnectBlock() : too many sigops"));
1670 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1671 int64 nTxValueOut = tx.GetValueOut();
1672 nValueIn += nTxValueIn;
1673 nValueOut += nTxValueOut;
1674 if (!tx.IsCoinStake())
1675 nFees += nTxValueIn - nTxValueOut;
1677 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1681 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1684 // ppcoin: track money supply and mint amount info
1685 pindex->nMint = nValueOut - nValueIn + nFees;
1686 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1687 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1688 return error("Connect() : WriteBlockIndex for pindex failed");
1690 // ppcoin: fees are not collected by miners as in bitcoin
1691 // ppcoin: fees are destroyed to compensate the entire network
1692 if (fDebug && GetBoolArg("-printcreation"))
1693 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1698 // Write queued txindex changes
1699 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1701 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1702 return error("ConnectBlock() : UpdateTxIndex failed");
1705 // Update block index on disk without changing it in memory.
1706 // The memory index structure will be changed after the db commits.
1709 CDiskBlockIndex blockindexPrev(pindex->pprev);
1710 blockindexPrev.hashNext = pindex->GetBlockHash();
1711 if (!txdb.WriteBlockIndex(blockindexPrev))
1712 return error("ConnectBlock() : WriteBlockIndex failed");
1715 // Watch for transactions paying to me
1716 BOOST_FOREACH(CTransaction& tx, vtx)
1717 SyncWithWallets(tx, this, true);
1722 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1724 printf("REORGANIZE\n");
1727 CBlockIndex* pfork = pindexBest;
1728 CBlockIndex* plonger = pindexNew;
1729 while (pfork != plonger)
1731 while (plonger->nHeight > pfork->nHeight)
1732 if (!(plonger = plonger->pprev))
1733 return error("Reorganize() : plonger->pprev is null");
1734 if (pfork == plonger)
1736 if (!(pfork = pfork->pprev))
1737 return error("Reorganize() : pfork->pprev is null");
1740 // List of what to disconnect
1741 vector<CBlockIndex*> vDisconnect;
1742 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1743 vDisconnect.push_back(pindex);
1745 // List of what to connect
1746 vector<CBlockIndex*> vConnect;
1747 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1748 vConnect.push_back(pindex);
1749 reverse(vConnect.begin(), vConnect.end());
1751 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());
1752 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());
1754 // Disconnect shorter branch
1755 vector<CTransaction> vResurrect;
1756 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1759 if (!block.ReadFromDisk(pindex))
1760 return error("Reorganize() : ReadFromDisk for disconnect failed");
1761 if (!block.DisconnectBlock(txdb, pindex))
1762 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1764 // Queue memory transactions to resurrect
1765 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1766 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1767 vResurrect.push_back(tx);
1770 // Connect longer branch
1771 vector<CTransaction> vDelete;
1772 for (unsigned int i = 0; i < vConnect.size(); i++)
1774 CBlockIndex* pindex = vConnect[i];
1776 if (!block.ReadFromDisk(pindex))
1777 return error("Reorganize() : ReadFromDisk for connect failed");
1778 if (!block.ConnectBlock(txdb, pindex))
1781 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1784 // Queue memory transactions to delete
1785 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1786 vDelete.push_back(tx);
1788 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1789 return error("Reorganize() : WriteHashBestChain failed");
1791 // Make sure it's successfully written to disk before changing memory structure
1792 if (!txdb.TxnCommit())
1793 return error("Reorganize() : TxnCommit failed");
1795 // Disconnect shorter branch
1796 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1798 pindex->pprev->pnext = NULL;
1800 // Connect longer branch
1801 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1803 pindex->pprev->pnext = pindex;
1805 // Resurrect memory transactions that were in the disconnected branch
1806 BOOST_FOREACH(CTransaction& tx, vResurrect)
1807 tx.AcceptToMemoryPool(txdb, false);
1809 // Delete redundant memory transactions that are in the connected branch
1810 BOOST_FOREACH(CTransaction& tx, vDelete)
1813 printf("REORGANIZE: done\n");
1819 // Called from inside SetBestChain: attaches a block to the new best chain being built
1820 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1822 uint256 hash = GetHash();
1824 // Adding to current best branch
1825 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1828 InvalidChainFound(pindexNew);
1831 if (!txdb.TxnCommit())
1832 return error("SetBestChain() : TxnCommit failed");
1834 // Add to current best branch
1835 pindexNew->pprev->pnext = pindexNew;
1837 // Delete redundant memory transactions
1838 BOOST_FOREACH(CTransaction& tx, vtx)
1844 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1846 uint256 hash = GetHash();
1848 if (!txdb.TxnBegin())
1849 return error("SetBestChain() : TxnBegin failed");
1851 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1853 txdb.WriteHashBestChain(hash);
1854 if (!txdb.TxnCommit())
1855 return error("SetBestChain() : TxnCommit failed");
1856 pindexGenesisBlock = pindexNew;
1858 else if (hashPrevBlock == hashBestChain)
1860 if (!SetBestChainInner(txdb, pindexNew))
1861 return error("SetBestChain() : SetBestChainInner failed");
1865 // the first block in the new chain that will cause it to become the new best chain
1866 CBlockIndex *pindexIntermediate = pindexNew;
1868 // list of blocks that need to be connected afterwards
1869 std::vector<CBlockIndex*> vpindexSecondary;
1871 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1872 // Try to limit how much needs to be done inside
1873 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1875 vpindexSecondary.push_back(pindexIntermediate);
1876 pindexIntermediate = pindexIntermediate->pprev;
1879 if (!vpindexSecondary.empty())
1880 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1882 // Switch to new best branch
1883 if (!Reorganize(txdb, pindexIntermediate))
1886 InvalidChainFound(pindexNew);
1887 return error("SetBestChain() : Reorganize failed");
1890 // Connect further blocks
1891 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1894 if (!block.ReadFromDisk(pindex))
1896 printf("SetBestChain() : ReadFromDisk failed\n");
1899 if (!txdb.TxnBegin()) {
1900 printf("SetBestChain() : TxnBegin 2 failed\n");
1903 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1904 if (!block.SetBestChainInner(txdb, pindex))
1909 // Update best block in wallet (so we can detect restored wallets)
1910 bool fIsInitialDownload = IsInitialBlockDownload();
1911 if (!fIsInitialDownload)
1913 const CBlockLocator locator(pindexNew);
1914 ::SetBestChain(locator);
1918 hashBestChain = hash;
1919 pindexBest = pindexNew;
1920 pblockindexFBBHLast = NULL;
1921 nBestHeight = pindexBest->nHeight;
1922 nBestChainTrust = pindexNew->nChainTrust;
1923 nTimeBestReceived = GetTime();
1924 nTransactionsUpdated++;
1926 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1928 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1929 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1930 CBigNum(nBestChainTrust).ToString().c_str(),
1931 nBestBlockTrust.Get64(),
1932 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1934 // Check the version of the last 100 blocks to see if we need to upgrade:
1935 if (!fIsInitialDownload)
1938 const CBlockIndex* pindex = pindexBest;
1939 for (int i = 0; i < 100 && pindex != NULL; i++)
1941 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1943 pindex = pindex->pprev;
1946 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1947 if (nUpgraded > 100/2)
1948 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1949 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1952 std::string strCmd = GetArg("-blocknotify", "");
1954 if (!fIsInitialDownload && !strCmd.empty())
1956 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1957 boost::thread t(runCommand, strCmd); // thread runs free
1963 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1964 // Only those coins meeting minimum age requirement counts. As those
1965 // transactions not in main chain are not currently indexed so we
1966 // might not find out about their coin age. Older transactions are
1967 // guaranteed to be in main chain by sync-checkpoint. This rule is
1968 // introduced to help nodes establish a consistent view of the coin
1969 // age (trust score) of competing branches.
1970 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1972 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1978 BOOST_FOREACH(const CTxIn& txin, vin)
1980 // First try finding the previous transaction in database
1981 CTransaction txPrev;
1983 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1984 continue; // previous transaction not in main chain
1985 if (nTime < txPrev.nTime)
1986 return false; // Transaction timestamp violation
1988 // Read block header
1990 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1991 return false; // unable to read block of previous transaction
1992 if (block.GetBlockTime() + nStakeMinAge > nTime)
1993 continue; // only count coins meeting min age requirement
1995 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1996 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1998 if (fDebug && GetBoolArg("-printcoinage"))
1999 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2002 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
2003 if (fDebug && GetBoolArg("-printcoinage"))
2004 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2005 nCoinAge = bnCoinDay.getuint64();
2009 // ppcoin: total coin age spent in block, in the unit of coin-days.
2010 bool CBlock::GetCoinAge(uint64& nCoinAge) const
2015 BOOST_FOREACH(const CTransaction& tx, vtx)
2018 if (tx.GetCoinAge(txdb, nTxCoinAge))
2019 nCoinAge += nTxCoinAge;
2024 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2026 if (fDebug && GetBoolArg("-printcoinage"))
2027 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
2031 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2033 // Check for duplicate
2034 uint256 hash = GetHash();
2035 if (mapBlockIndex.count(hash))
2036 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2038 // Construct new block index object
2039 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
2041 return error("AddToBlockIndex() : new CBlockIndex failed");
2042 pindexNew->phashBlock = &hash;
2043 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2044 if (miPrev != mapBlockIndex.end())
2046 pindexNew->pprev = (*miPrev).second;
2047 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2050 // ppcoin: compute chain trust score
2051 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2053 // ppcoin: compute stake entropy bit for stake modifier
2054 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2055 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2057 // ppcoin: record proof-of-stake hash value
2058 if (pindexNew->IsProofOfStake())
2060 if (!mapProofOfStake.count(hash))
2061 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2062 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2065 // ppcoin: compute stake modifier
2066 uint64 nStakeModifier = 0;
2067 bool fGeneratedStakeModifier = false;
2068 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2069 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2070 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2071 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2072 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2073 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2075 // Add to mapBlockIndex
2076 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2077 if (pindexNew->IsProofOfStake())
2078 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2079 pindexNew->phashBlock = &((*mi).first);
2081 // Write to disk block index
2083 if (!txdb.TxnBegin())
2085 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2086 if (!txdb.TxnCommit())
2090 if (pindexNew->nChainTrust > nBestChainTrust)
2091 if (!SetBestChain(txdb, pindexNew))
2094 if (pindexNew == pindexBest)
2096 // Notify UI to display prev block's coinbase if it was ours
2097 static uint256 hashPrevBestCoinBase;
2098 UpdatedTransaction(hashPrevBestCoinBase);
2099 hashPrevBestCoinBase = vtx[0].GetHash();
2102 uiInterface.NotifyBlocksChanged();
2109 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2111 // These are checks that are independent of context
2112 // that can be verified before saving an orphan block.
2115 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2116 return DoS(100, error("CheckBlock() : size limits failed"));
2118 // Check proof of work matches claimed amount
2119 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2120 return DoS(50, error("CheckBlock() : proof of work failed"));
2123 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
2124 return error("CheckBlock() : block timestamp too far in the future");
2126 // First transaction must be coinbase, the rest must not be
2127 if (vtx.empty() || !vtx[0].IsCoinBase())
2128 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2129 for (unsigned int i = 1; i < vtx.size(); i++)
2130 if (vtx[i].IsCoinBase())
2131 return DoS(100, error("CheckBlock() : more than one coinbase"));
2133 // Check coinbase timestamp
2134 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
2135 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2137 if (IsProofOfStake())
2139 // Coinbase output should be empty if proof-of-stake block
2140 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2141 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2143 // Second transaction must be coinstake, the rest must not be
2144 if (vtx.empty() || !vtx[1].IsCoinStake())
2145 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2146 for (unsigned int i = 2; i < vtx.size(); i++)
2147 if (vtx[i].IsCoinStake())
2148 return DoS(100, error("CheckBlock() : more than one coinstake"));
2150 // Check coinstake timestamp
2151 if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2152 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2154 // NovaCoin: check proof-of-stake block signature
2155 if (fCheckSig && !CheckBlockSignature(true))
2156 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2160 // Coinbase fee paid until 20 Sep 2013
2161 int64 nFee = GetBlockTime() < CHAINCHECKS_SWITCH_TIME ? vtx[0].GetMinFee() - MIN_TX_FEE : 0;
2163 // Check coinbase reward
2164 if (vtx[0].GetValueOut() > (GetProofOfWorkReward(nBits) - nFee))
2165 return DoS(50, error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
2166 vtx[0].GetValueOut(),
2167 GetProofOfWorkReward(nBits) - nFee));
2169 // Should we check proof-of-work block signature or not?
2171 // * Always skip on TestNet
2172 // * Perform checking for the first 9689 blocks
2173 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2175 if(!fTestNet && fCheckSig)
2177 bool isAfterCheckpoint = (GetBlockTime() > Checkpoints::GetLastCheckpointTime());
2178 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2179 bool checkPoWSig = (isAfterCheckpoint && GetBlockTime() < CHAINCHECKS_SWITCH_TIME);
2181 // NovaCoin: check proof-of-work block signature
2182 if ((checkEntropySig || checkPoWSig) && !CheckBlockSignature(false))
2183 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2187 // Check transactions
2188 BOOST_FOREACH(const CTransaction& tx, vtx)
2190 if (!tx.CheckTransaction())
2191 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2193 // ppcoin: check transaction timestamp
2194 if (GetBlockTime() < (int64)tx.nTime)
2195 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2198 // Check for duplicate txids. This is caught by ConnectInputs(),
2199 // but catching it earlier avoids a potential DoS attack:
2200 set<uint256> uniqueTx;
2201 BOOST_FOREACH(const CTransaction& tx, vtx)
2203 uniqueTx.insert(tx.GetHash());
2205 if (uniqueTx.size() != vtx.size())
2206 return DoS(100, error("CheckBlock() : duplicate transaction"));
2208 unsigned int nSigOps = 0;
2209 BOOST_FOREACH(const CTransaction& tx, vtx)
2211 nSigOps += tx.GetLegacySigOpCount();
2213 if (nSigOps > MAX_BLOCK_SIGOPS)
2214 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2216 // Check merkle root
2217 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2218 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2224 bool CBlock::AcceptBlock()
2226 // Check for duplicate
2227 uint256 hash = GetHash();
2228 if (mapBlockIndex.count(hash))
2229 return error("AcceptBlock() : block already in mapBlockIndex");
2231 // Get prev block index
2232 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2233 if (mi == mapBlockIndex.end())
2234 return DoS(10, error("AcceptBlock() : prev block not found"));
2235 CBlockIndex* pindexPrev = (*mi).second;
2236 int nHeight = pindexPrev->nHeight+1;
2238 // Check proof-of-work or proof-of-stake
2239 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2240 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2242 // Check timestamp against prev
2243 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
2244 return error("AcceptBlock() : block's timestamp is too early");
2246 // Check that all transactions are finalized
2247 BOOST_FOREACH(const CTransaction& tx, vtx)
2248 if (!tx.IsFinal(nHeight, GetBlockTime()))
2249 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2251 // Check that the block chain matches the known block chain up to a checkpoint
2252 if (!Checkpoints::CheckHardened(nHeight, hash))
2253 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2255 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2257 // Check that the block satisfies synchronized checkpoint
2258 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2259 return error("AcceptBlock() : rejected by synchronized checkpoint");
2261 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2262 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2264 // Enforce rule that the coinbase starts with serialized block height
2265 CScript expect = CScript() << nHeight;
2266 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2267 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2268 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2270 // Write block to history file
2271 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2272 return error("AcceptBlock() : out of disk space");
2273 unsigned int nFile = -1;
2274 unsigned int nBlockPos = 0;
2275 if (!WriteToDisk(nFile, nBlockPos))
2276 return error("AcceptBlock() : WriteToDisk failed");
2277 if (!AddToBlockIndex(nFile, nBlockPos))
2278 return error("AcceptBlock() : AddToBlockIndex failed");
2280 // Relay inventory, but don't relay old inventory during initial block download
2281 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2282 if (hashBestChain == hash)
2285 BOOST_FOREACH(CNode* pnode, vNodes)
2286 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2287 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2290 // ppcoin: check pending sync-checkpoint
2291 Checkpoints::AcceptPendingSyncCheckpoint();
2296 uint256 CBlockIndex::GetBlockTrust() const
2299 bnTarget.SetCompact(nBits);
2304 /* Old protocol, will be removed later */
2305 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2306 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2310 // Calculate work amount for block
2311 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2313 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2314 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2316 // Return nPoWTrust for the first 12 blocks
2317 if (pprev == NULL || pprev->nHeight < 12)
2320 const CBlockIndex* currentIndex = pprev;
2322 if(IsProofOfStake())
2324 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2326 // Return 1/3 of score if parent block is not the PoW block
2327 if (!pprev->IsProofOfWork())
2328 return (bnNewTrust / 3).getuint256();
2332 // Check last 12 blocks type
2333 while (pprev->nHeight - currentIndex->nHeight < 12)
2335 if (currentIndex->IsProofOfWork())
2337 currentIndex = currentIndex->pprev;
2340 // Return 1/3 of score if less than 3 PoW blocks found
2342 return (bnNewTrust / 3).getuint256();
2344 return bnNewTrust.getuint256();
2348 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2350 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2351 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2352 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2356 // Check last 12 blocks type
2357 while (pprev->nHeight - currentIndex->nHeight < 12)
2359 if (currentIndex->IsProofOfStake())
2361 currentIndex = currentIndex->pprev;
2364 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2366 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2368 bnTarget.SetCompact(pprev->nBits);
2373 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2375 // Return nPoWTrust + full trust score for previous block nBits
2376 return nPoWTrust + bnNewTrust.getuint256();
2380 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2382 unsigned int nFound = 0;
2383 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2385 if (pstart->nVersion >= minVersion)
2387 pstart = pstart->pprev;
2389 return (nFound >= nRequired);
2392 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2394 // Check for duplicate
2395 uint256 hash = pblock->GetHash();
2396 if (mapBlockIndex.count(hash))
2397 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2398 if (mapOrphanBlocks.count(hash))
2399 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2401 // ppcoin: check proof-of-stake
2402 // Limited duplicity on stake: prevents block flood attack
2403 // Duplicate stake allowed only when there is orphan child block
2404 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2405 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());
2407 // Preliminary checks
2408 if (!pblock->CheckBlock())
2409 return error("ProcessBlock() : CheckBlock FAILED");
2411 // ppcoin: verify hash target and signature of coinstake tx
2412 if (pblock->IsProofOfStake())
2414 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2415 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2417 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2418 return false; // do not error here as we expect this during initial block download
2420 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2421 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2424 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2425 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2427 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2428 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2430 bnNewBlock.SetCompact(pblock->nBits);
2433 if (pblock->IsProofOfStake())
2434 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2436 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2438 if (bnNewBlock > bnRequired)
2441 pfrom->Misbehaving(100);
2442 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2446 // ppcoin: ask for pending sync-checkpoint if any
2447 if (!IsInitialBlockDownload())
2448 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2450 // If don't already have its previous block, shunt it off to holding area until we get it
2451 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2453 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2454 CBlock* pblock2 = new CBlock(*pblock);
2455 // ppcoin: check proof-of-stake
2456 if (pblock2->IsProofOfStake())
2458 // Limited duplicity on stake: prevents block flood attack
2459 // Duplicate stake allowed only when there is orphan child block
2460 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2461 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());
2463 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2465 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2466 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2468 // Ask this guy to fill in what we're missing
2471 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2472 // ppcoin: getblocks may not obtain the ancestor block rejected
2473 // earlier by duplicate-stake check so we ask for it again directly
2474 if (!IsInitialBlockDownload())
2475 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2481 if (!pblock->AcceptBlock())
2482 return error("ProcessBlock() : AcceptBlock FAILED");
2484 // Recursively process any orphan blocks that depended on this one
2485 vector<uint256> vWorkQueue;
2486 vWorkQueue.push_back(hash);
2487 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2489 uint256 hashPrev = vWorkQueue[i];
2490 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2491 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2494 CBlock* pblockOrphan = (*mi).second;
2495 if (pblockOrphan->AcceptBlock())
2496 vWorkQueue.push_back(pblockOrphan->GetHash());
2497 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2498 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2499 delete pblockOrphan;
2501 mapOrphanBlocksByPrev.erase(hashPrev);
2504 printf("ProcessBlock: ACCEPTED\n");
2506 // ppcoin: if responsible for sync-checkpoint send it
2507 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2508 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2513 // ppcoin: sign block
2514 bool CBlock::SignBlock(const CKeyStore& keystore)
2516 vector<valtype> vSolutions;
2517 txnouttype whichType;
2519 if(!IsProofOfStake())
2521 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2523 const CTxOut& txout = vtx[0].vout[i];
2525 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2528 if (whichType == TX_PUBKEY)
2531 valtype& vchPubKey = vSolutions[0];
2534 if (!keystore.GetKey(Hash160(vchPubKey), key))
2536 if (key.GetPubKey() != vchPubKey)
2538 if(!key.Sign(GetHash(), vchBlockSig))
2547 const CTxOut& txout = vtx[1].vout[1];
2549 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2552 if (whichType == TX_PUBKEY)
2555 valtype& vchPubKey = vSolutions[0];
2558 if (!keystore.GetKey(Hash160(vchPubKey), key))
2560 if (key.GetPubKey() != vchPubKey)
2563 return key.Sign(GetHash(), vchBlockSig);
2567 printf("Sign failed\n");
2571 // ppcoin: check block signature
2572 bool CBlock::CheckBlockSignature(bool fProofOfStake) const
2574 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2575 return vchBlockSig.empty();
2577 vector<valtype> vSolutions;
2578 txnouttype whichType;
2582 const CTxOut& txout = vtx[1].vout[1];
2584 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2586 if (whichType == TX_PUBKEY)
2588 valtype& vchPubKey = vSolutions[0];
2590 if (!key.SetPubKey(vchPubKey))
2592 if (vchBlockSig.empty())
2594 return key.Verify(GetHash(), vchBlockSig);
2599 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2601 const CTxOut& txout = vtx[0].vout[i];
2603 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2606 if (whichType == TX_PUBKEY)
2609 valtype& vchPubKey = vSolutions[0];
2611 if (!key.SetPubKey(vchPubKey))
2613 if (vchBlockSig.empty())
2615 if(!key.Verify(GetHash(), vchBlockSig))
2625 bool CheckDiskSpace(uint64 nAdditionalBytes)
2627 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2629 // Check for nMinDiskSpace bytes (currently 50MB)
2630 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2633 string strMessage = _("Warning: Disk space is low!");
2634 strMiscWarning = strMessage;
2635 printf("*** %s\n", strMessage.c_str());
2636 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2643 static filesystem::path BlockFilePath(unsigned int nFile)
2645 string strBlockFn = strprintf("blk%04u.dat", nFile);
2646 return GetDataDir() / strBlockFn;
2649 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2651 if ((nFile < 1) || (nFile == (unsigned int) -1))
2653 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2656 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2658 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2667 static unsigned int nCurrentBlockFile = 1;
2669 FILE* AppendBlockFile(unsigned int& nFileRet)
2674 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2677 if (fseek(file, 0, SEEK_END) != 0)
2679 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2680 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2682 nFileRet = nCurrentBlockFile;
2686 nCurrentBlockFile++;
2690 bool LoadBlockIndex(bool fAllowNew)
2694 pchMessageStart[0] = 0xcd;
2695 pchMessageStart[1] = 0xf2;
2696 pchMessageStart[2] = 0xc0;
2697 pchMessageStart[3] = 0xef;
2699 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2700 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2701 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2702 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2703 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2710 if (!txdb.LoadBlockIndex())
2715 // Init with genesis block
2717 if (mapBlockIndex.empty())
2726 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2727 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2728 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2730 // vMerkleTree: 4cb33b3b6a
2734 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2735 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2736 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2738 // vMerkleTree: 4cb33b3b6a
2740 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2742 txNew.nTime = 1360105017;
2743 txNew.vin.resize(1);
2744 txNew.vout.resize(1);
2745 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2746 txNew.vout[0].SetEmpty();
2748 block.vtx.push_back(txNew);
2749 block.hashPrevBlock = 0;
2750 block.hashMerkleRoot = block.BuildMerkleTree();
2752 block.nTime = 1360105017;
2753 block.nBits = bnProofOfWorkLimit.GetCompact();
2754 block.nNonce = !fTestNet ? 1575379 : 46534;
2757 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2759 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2760 assert(block.CheckBlock());
2762 // Start new block file
2764 unsigned int nBlockPos;
2765 if (!block.WriteToDisk(nFile, nBlockPos))
2766 return error("LoadBlockIndex() : writing genesis block to disk failed");
2767 if (!block.AddToBlockIndex(nFile, nBlockPos))
2768 return error("LoadBlockIndex() : genesis block not accepted");
2770 // ppcoin: initialize synchronized checkpoint
2771 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2772 return error("LoadBlockIndex() : failed to init sync checkpoint");
2775 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2778 string strPubKey = "";
2779 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2781 // write checkpoint master key to db
2783 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2784 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2785 if (!txdb.TxnCommit())
2786 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2787 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2788 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2801 void PrintBlockTree()
2803 // pre-compute tree structure
2804 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2805 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2807 CBlockIndex* pindex = (*mi).second;
2808 mapNext[pindex->pprev].push_back(pindex);
2810 //while (rand() % 3 == 0)
2811 // mapNext[pindex->pprev].push_back(pindex);
2814 vector<pair<int, CBlockIndex*> > vStack;
2815 vStack.push_back(make_pair(0, pindexGenesisBlock));
2818 while (!vStack.empty())
2820 int nCol = vStack.back().first;
2821 CBlockIndex* pindex = vStack.back().second;
2824 // print split or gap
2825 if (nCol > nPrevCol)
2827 for (int i = 0; i < nCol-1; i++)
2831 else if (nCol < nPrevCol)
2833 for (int i = 0; i < nCol; i++)
2840 for (int i = 0; i < nCol; i++)
2845 block.ReadFromDisk(pindex);
2846 printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
2850 block.GetHash().ToString().c_str(),
2852 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2853 FormatMoney(pindex->nMint).c_str(),
2856 PrintWallets(block);
2858 // put the main time-chain first
2859 vector<CBlockIndex*>& vNext = mapNext[pindex];
2860 for (unsigned int i = 0; i < vNext.size(); i++)
2862 if (vNext[i]->pnext)
2864 swap(vNext[0], vNext[i]);
2870 for (unsigned int i = 0; i < vNext.size(); i++)
2871 vStack.push_back(make_pair(nCol+i, vNext[i]));
2875 bool LoadExternalBlockFile(FILE* fileIn)
2877 int64 nStart = GetTimeMillis();
2883 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2884 unsigned int nPos = 0;
2885 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2887 unsigned char pchData[65536];
2889 fseek(blkdat, nPos, SEEK_SET);
2890 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2893 nPos = (unsigned int)-1;
2896 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2899 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2901 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2904 nPos += ((unsigned char*)nFind - pchData) + 1;
2907 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2908 } while(!fRequestShutdown);
2909 if (nPos == (unsigned int)-1)
2911 fseek(blkdat, nPos, SEEK_SET);
2914 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2918 if (ProcessBlock(NULL,&block))
2926 catch (std::exception &e) {
2927 printf("%s() : Deserialize or I/O error caught during load\n",
2928 __PRETTY_FUNCTION__);
2931 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2935 //////////////////////////////////////////////////////////////////////////////
2940 extern map<uint256, CAlert> mapAlerts;
2941 extern CCriticalSection cs_mapAlerts;
2943 extern string strMintMessage;
2944 extern string strMintWarning;
2946 string GetWarnings(string strFor)
2949 string strStatusBar;
2952 if (GetBoolArg("-testsafemode"))
2955 // ppcoin: wallet lock warning for minting
2956 if (strMintWarning != "")
2959 strStatusBar = strMintWarning;
2962 // Misc warnings like out of disk space and clock is wrong
2963 if (strMiscWarning != "")
2966 strStatusBar = strMiscWarning;
2969 // * Should not enter safe mode for longer invalid chain
2970 // * If sync-checkpoint is too old do not enter safe mode
2971 // * Display warning only in the STRICT mode
2972 if (CheckpointsMode == Checkpoints::STRICT && Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) &&
2973 !fTestNet && !IsInitialBlockDownload())
2976 strStatusBar = _("WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.");
2979 // ppcoin: if detected invalid checkpoint enter safe mode
2980 if (Checkpoints::hashInvalidCheckpoint != 0)
2983 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
2989 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2991 const CAlert& alert = item.second;
2992 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2994 nPriority = alert.nPriority;
2995 strStatusBar = alert.strStatusBar;
2996 if (nPriority > 1000)
2997 strRPC = strStatusBar;
3002 if (strFor == "statusbar")
3003 return strStatusBar;
3004 else if (strFor == "rpc")
3006 assert(!"GetWarnings() : invalid parameter");
3017 //////////////////////////////////////////////////////////////////////////////
3023 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3029 bool txInMap = false;
3032 txInMap = (mempool.exists(inv.hash));
3035 mapOrphanTransactions.count(inv.hash) ||
3036 txdb.ContainsTx(inv.hash);
3040 return mapBlockIndex.count(inv.hash) ||
3041 mapOrphanBlocks.count(inv.hash);
3043 // Don't know what it is, just say we already got one
3050 // The message start string is designed to be unlikely to occur in normal data.
3051 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3052 // a large 4-byte int at any alignment.
3053 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3055 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3057 static map<CService, CPubKey> mapReuseKey;
3058 RandAddSeedPerfmon();
3060 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3061 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3063 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3067 if (strCommand == "version")
3069 // Each connection can only send one version message
3070 if (pfrom->nVersion != 0)
3072 pfrom->Misbehaving(1);
3080 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3081 if (pfrom->nVersion < MIN_PROTO_VERSION)
3083 // Since February 20, 2012, the protocol is initiated at version 209,
3084 // and earlier versions are no longer supported
3085 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3086 pfrom->fDisconnect = true;
3090 if (pfrom->nVersion == 10300)
3091 pfrom->nVersion = 300;
3093 vRecv >> addrFrom >> nNonce;
3095 vRecv >> pfrom->strSubVer;
3097 vRecv >> pfrom->nStartingHeight;
3099 if (pfrom->fInbound && addrMe.IsRoutable())
3101 pfrom->addrLocal = addrMe;
3105 // Disconnect if we connected to ourself
3106 if (nNonce == nLocalHostNonce && nNonce > 1)
3108 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3109 pfrom->fDisconnect = true;
3113 // record my external IP reported by peer
3114 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3115 addrSeenByPeer = addrMe;
3117 // Be shy and don't send version until we hear
3118 if (pfrom->fInbound)
3119 pfrom->PushVersion();
3121 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3123 AddTimeData(pfrom->addr, nTime);
3126 pfrom->PushMessage("verack");
3127 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3129 if (!pfrom->fInbound)
3131 // Advertise our address
3132 if (!fNoListen && !IsInitialBlockDownload())
3134 CAddress addr = GetLocalAddress(&pfrom->addr);
3135 if (addr.IsRoutable())
3136 pfrom->PushAddress(addr);
3139 // Get recent addresses
3140 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3142 pfrom->PushMessage("getaddr");
3143 pfrom->fGetAddr = true;
3145 addrman.Good(pfrom->addr);
3147 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3149 addrman.Add(addrFrom, addrFrom);
3150 addrman.Good(addrFrom);
3154 // Ask the first connected node for block updates
3155 static int nAskedForBlocks = 0;
3156 if (!pfrom->fClient && !pfrom->fOneShot &&
3157 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3158 (pfrom->nVersion < NOBLKS_VERSION_START ||
3159 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3160 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3163 pfrom->PushGetBlocks(pindexBest, uint256(0));
3169 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3170 item.second.RelayTo(pfrom);
3173 // Relay sync-checkpoint
3175 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3176 if (!Checkpoints::checkpointMessage.IsNull())
3177 Checkpoints::checkpointMessage.RelayTo(pfrom);
3180 pfrom->fSuccessfullyConnected = true;
3182 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());
3184 cPeerBlockCounts.input(pfrom->nStartingHeight);
3186 // ppcoin: ask for pending sync-checkpoint if any
3187 if (!IsInitialBlockDownload())
3188 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3192 else if (pfrom->nVersion == 0)
3194 // Must have a version message before anything else
3195 pfrom->Misbehaving(1);
3200 else if (strCommand == "verack")
3202 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3206 else if (strCommand == "addr")
3208 vector<CAddress> vAddr;
3211 // Don't want addr from older versions unless seeding
3212 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3214 if (vAddr.size() > 1000)
3216 pfrom->Misbehaving(20);
3217 return error("message addr size() = %"PRIszu"", vAddr.size());
3220 // Store the new addresses
3221 vector<CAddress> vAddrOk;
3222 int64 nNow = GetAdjustedTime();
3223 int64 nSince = nNow - 10 * 60;
3224 BOOST_FOREACH(CAddress& addr, vAddr)
3228 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3229 addr.nTime = nNow - 5 * 24 * 60 * 60;
3230 pfrom->AddAddressKnown(addr);
3231 bool fReachable = IsReachable(addr);
3232 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3234 // Relay to a limited number of other nodes
3237 // Use deterministic randomness to send to the same nodes for 24 hours
3238 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3239 static uint256 hashSalt;
3241 hashSalt = GetRandHash();
3242 uint64 hashAddr = addr.GetHash();
3243 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3244 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3245 multimap<uint256, CNode*> mapMix;
3246 BOOST_FOREACH(CNode* pnode, vNodes)
3248 if (pnode->nVersion < CADDR_TIME_VERSION)
3250 unsigned int nPointer;
3251 memcpy(&nPointer, &pnode, sizeof(nPointer));
3252 uint256 hashKey = hashRand ^ nPointer;
3253 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3254 mapMix.insert(make_pair(hashKey, pnode));
3256 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3257 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3258 ((*mi).second)->PushAddress(addr);
3261 // Do not store addresses outside our network
3263 vAddrOk.push_back(addr);
3265 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3266 if (vAddr.size() < 1000)
3267 pfrom->fGetAddr = false;
3268 if (pfrom->fOneShot)
3269 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 bool fMissingInputs = false;
3495 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3497 SyncWithWallets(tx, NULL, true);
3498 RelayTransaction(tx, inv.hash);
3499 mapAlreadyAskedFor.erase(inv);
3500 vWorkQueue.push_back(inv.hash);
3501 vEraseQueue.push_back(inv.hash);
3503 // Recursively process any orphan transactions that depended on this one
3504 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3506 uint256 hashPrev = vWorkQueue[i];
3507 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3508 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3511 const uint256& orphanTxHash = *mi;
3512 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3513 bool fMissingInputs2 = false;
3515 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3517 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3518 SyncWithWallets(tx, NULL, true);
3519 RelayTransaction(orphanTx, orphanTxHash);
3520 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3521 vWorkQueue.push_back(orphanTxHash);
3522 vEraseQueue.push_back(orphanTxHash);
3524 else if (!fMissingInputs2)
3527 vEraseQueue.push_back(orphanTxHash);
3528 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3533 BOOST_FOREACH(uint256 hash, vEraseQueue)
3534 EraseOrphanTx(hash);
3536 else if (fMissingInputs)
3540 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3541 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3543 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3545 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3549 else if (strCommand == "block")
3553 uint256 hashBlock = block.GetHash();
3555 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3558 CInv inv(MSG_BLOCK, hashBlock);
3559 pfrom->AddInventoryKnown(inv);
3561 if (ProcessBlock(pfrom, &block))
3562 mapAlreadyAskedFor.erase(inv);
3563 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3567 else if (strCommand == "getaddr")
3569 // Don't return addresses older than nCutOff timestamp
3570 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3571 pfrom->vAddrToSend.clear();
3572 vector<CAddress> vAddr = addrman.GetAddr();
3573 BOOST_FOREACH(const CAddress &addr, vAddr)
3574 if(addr.nTime > nCutOff)
3575 pfrom->PushAddress(addr);
3579 else if (strCommand == "mempool")
3581 std::vector<uint256> vtxid;
3582 mempool.queryHashes(vtxid);
3584 for (unsigned int i = 0; i < vtxid.size(); i++) {
3585 CInv inv(MSG_TX, vtxid[i]);
3586 vInv.push_back(inv);
3587 if (i == (MAX_INV_SZ - 1))
3590 if (vInv.size() > 0)
3591 pfrom->PushMessage("inv", vInv);
3595 else if (strCommand == "checkorder")
3600 if (!GetBoolArg("-allowreceivebyip"))
3602 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3609 /// we have a chance to check the order here
3611 // Keep giving the same key to the same ip until they use it
3612 if (!mapReuseKey.count(pfrom->addr))
3613 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3615 // Send back approval of order and pubkey to use
3616 CScript scriptPubKey;
3617 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3618 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3622 else if (strCommand == "reply")
3627 CRequestTracker tracker;
3629 LOCK(pfrom->cs_mapRequests);
3630 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3631 if (mi != pfrom->mapRequests.end())
3633 tracker = (*mi).second;
3634 pfrom->mapRequests.erase(mi);
3637 if (!tracker.IsNull())
3638 tracker.fn(tracker.param1, vRecv);
3642 else if (strCommand == "ping")
3644 if (pfrom->nVersion > BIP0031_VERSION)
3648 // Echo the message back with the nonce. This allows for two useful features:
3650 // 1) A remote node can quickly check if the connection is operational
3651 // 2) Remote nodes can measure the latency of the network thread. If this node
3652 // is overloaded it won't respond to pings quickly and the remote node can
3653 // avoid sending us more work, like chain download requests.
3655 // The nonce stops the remote getting confused between different pings: without
3656 // it, if the remote node sends a ping once per second and this node takes 5
3657 // seconds to respond to each, the 5th ping the remote sends would appear to
3658 // return very quickly.
3659 pfrom->PushMessage("pong", nonce);
3664 else if (strCommand == "alert")
3669 uint256 alertHash = alert.GetHash();
3670 if (pfrom->setKnown.count(alertHash) == 0)
3672 if (alert.ProcessAlert())
3675 pfrom->setKnown.insert(alertHash);
3678 BOOST_FOREACH(CNode* pnode, vNodes)
3679 alert.RelayTo(pnode);
3683 // Small DoS penalty so peers that send us lots of
3684 // duplicate/expired/invalid-signature/whatever alerts
3685 // eventually get banned.
3686 // This isn't a Misbehaving(100) (immediate ban) because the
3687 // peer might be an older or different implementation with
3688 // a different signature key, etc.
3689 pfrom->Misbehaving(10);
3697 // Ignore unknown commands for extensibility
3701 // Update the last seen time for this node's address
3702 if (pfrom->fNetworkNode)
3703 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3704 AddressCurrentlyConnected(pfrom->addr);
3710 bool ProcessMessages(CNode* pfrom)
3712 CDataStream& vRecv = pfrom->vRecv;
3716 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3720 // (4) message start
3729 // Don't bother if send buffer is too full to respond anyway
3730 if (pfrom->vSend.size() >= SendBufferSize())
3733 // Scan for message start
3734 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3735 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3736 if (vRecv.end() - pstart < nHeaderSize)
3738 if ((int)vRecv.size() > nHeaderSize)
3740 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3741 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3745 if (pstart - vRecv.begin() > 0)
3746 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3747 vRecv.erase(vRecv.begin(), pstart);
3750 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3755 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3758 string strCommand = hdr.GetCommand();
3761 unsigned int nMessageSize = hdr.nMessageSize;
3762 if (nMessageSize > MAX_SIZE)
3764 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3767 if (nMessageSize > vRecv.size())
3769 // Rewind and wait for rest of message
3770 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3775 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3776 unsigned int nChecksum = 0;
3777 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3778 if (nChecksum != hdr.nChecksum)
3780 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3781 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3785 // Copy message to its own buffer
3786 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3787 vRecv.ignore(nMessageSize);
3795 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3800 catch (std::ios_base::failure& e)
3802 if (strstr(e.what(), "end of data"))
3804 // Allow exceptions from under-length message on vRecv
3805 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());
3807 else if (strstr(e.what(), "size too large"))
3809 // Allow exceptions from over-long size
3810 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3814 PrintExceptionContinue(&e, "ProcessMessages()");
3817 catch (std::exception& e) {
3818 PrintExceptionContinue(&e, "ProcessMessages()");
3820 PrintExceptionContinue(NULL, "ProcessMessages()");
3824 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3832 bool SendMessages(CNode* pto, bool fSendTrickle)
3834 TRY_LOCK(cs_main, lockMain);
3836 // Don't send anything until we get their version message
3837 if (pto->nVersion == 0)
3840 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3842 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3844 if (pto->nVersion > BIP0031_VERSION)
3845 pto->PushMessage("ping", nonce);
3847 pto->PushMessage("ping");
3850 // Resend wallet transactions that haven't gotten in a block yet
3851 ResendWalletTransactions();
3853 // Address refresh broadcast
3854 static int64 nLastRebroadcast;
3855 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3859 BOOST_FOREACH(CNode* pnode, vNodes)
3861 // Periodically clear setAddrKnown to allow refresh broadcasts
3862 if (nLastRebroadcast)
3863 pnode->setAddrKnown.clear();
3865 // Rebroadcast our address
3868 CAddress addr = GetLocalAddress(&pnode->addr);
3869 if (addr.IsRoutable())
3870 pnode->PushAddress(addr);
3874 nLastRebroadcast = GetTime();
3882 vector<CAddress> vAddr;
3883 vAddr.reserve(pto->vAddrToSend.size());
3884 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3886 // returns true if wasn't already contained in the set
3887 if (pto->setAddrKnown.insert(addr).second)
3889 vAddr.push_back(addr);
3890 // receiver rejects addr messages larger than 1000
3891 if (vAddr.size() >= 1000)
3893 pto->PushMessage("addr", vAddr);
3898 pto->vAddrToSend.clear();
3900 pto->PushMessage("addr", vAddr);
3905 // Message: inventory
3908 vector<CInv> vInvWait;
3910 LOCK(pto->cs_inventory);
3911 vInv.reserve(pto->vInventoryToSend.size());
3912 vInvWait.reserve(pto->vInventoryToSend.size());
3913 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3915 if (pto->setInventoryKnown.count(inv))
3918 // trickle out tx inv to protect privacy
3919 if (inv.type == MSG_TX && !fSendTrickle)
3921 // 1/4 of tx invs blast to all immediately
3922 static uint256 hashSalt;
3924 hashSalt = GetRandHash();
3925 uint256 hashRand = inv.hash ^ hashSalt;
3926 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3927 bool fTrickleWait = ((hashRand & 3) != 0);
3929 // always trickle our own transactions
3933 if (GetTransaction(inv.hash, wtx))
3935 fTrickleWait = true;
3940 vInvWait.push_back(inv);
3945 // returns true if wasn't already contained in the set
3946 if (pto->setInventoryKnown.insert(inv).second)
3948 vInv.push_back(inv);
3949 if (vInv.size() >= 1000)
3951 pto->PushMessage("inv", vInv);
3956 pto->vInventoryToSend = vInvWait;
3959 pto->PushMessage("inv", vInv);
3965 vector<CInv> vGetData;
3966 int64 nNow = GetTime() * 1000000;
3968 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3970 const CInv& inv = (*pto->mapAskFor.begin()).second;
3971 if (!AlreadyHave(txdb, inv))
3974 printf("sending getdata: %s\n", inv.ToString().c_str());
3975 vGetData.push_back(inv);
3976 if (vGetData.size() >= 1000)
3978 pto->PushMessage("getdata", vGetData);
3981 mapAlreadyAskedFor[inv] = nNow;
3983 pto->mapAskFor.erase(pto->mapAskFor.begin());
3985 if (!vGetData.empty())
3986 pto->PushMessage("getdata", vGetData);