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 "zerocoin/Zerocoin.h"
15 #include <boost/algorithm/string/replace.hpp>
16 #include <boost/filesystem.hpp>
17 #include <boost/filesystem/fstream.hpp>
21 using namespace boost;
27 CCriticalSection cs_setpwalletRegistered;
28 set<CWallet*> setpwalletRegistered;
30 CCriticalSection cs_main;
33 unsigned int nTransactionsUpdated = 0;
35 map<uint256, CBlockIndex*> mapBlockIndex;
36 set<pair<COutPoint, unsigned int> > setStakeSeen;
37 libzerocoin::Params* ZCParams;
39 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
40 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
41 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
42 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
43 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
45 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
47 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as zero time weight
48 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
49 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
50 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
52 int nCoinbaseMaturity = 500;
53 CBlockIndex* pindexGenesisBlock = NULL;
56 uint256 nBestChainTrust = 0;
57 uint256 nBestInvalidTrust = 0;
59 uint256 hashBestChain = 0;
60 CBlockIndex* pindexBest = NULL;
61 int64 nTimeBestReceived = 0;
63 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
65 map<uint256, CBlock*> mapOrphanBlocks;
66 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
67 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
68 map<uint256, uint256> mapProofOfStake;
70 map<uint256, CTransaction> mapOrphanTransactions;
71 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
73 // Constant stuff for coinbase transactions we create:
74 CScript COINBASE_FLAGS;
76 const string strMessageMagic = "NovaCoin Signed Message:\n";
79 int64 nTransactionFee = MIN_TX_FEE;
80 int64 nMinimumInputValue = MIN_TX_FEE;
82 extern enum Checkpoints::CPMode CheckpointsMode;
84 //////////////////////////////////////////////////////////////////////////////
86 // dispatching functions
89 // These functions dispatch to one or all registered wallets
92 void RegisterWallet(CWallet* pwalletIn)
95 LOCK(cs_setpwalletRegistered);
96 setpwalletRegistered.insert(pwalletIn);
100 void UnregisterWallet(CWallet* pwalletIn)
103 LOCK(cs_setpwalletRegistered);
104 setpwalletRegistered.erase(pwalletIn);
108 // check whether the passed transaction is from us
109 bool static IsFromMe(CTransaction& tx)
111 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
112 if (pwallet->IsFromMe(tx))
117 // get the wallet transaction with the given hash (if it exists)
118 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
120 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
121 if (pwallet->GetTransaction(hashTx,wtx))
126 // erases transaction with the given hash from all wallets
127 void static EraseFromWallets(uint256 hash)
129 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
130 pwallet->EraseFromWallet(hash);
133 // make sure all wallets know about the given transaction, in the given block
134 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
138 // ppcoin: wallets need to refund inputs when disconnecting coinstake
139 if (tx.IsCoinStake())
141 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
142 if (pwallet->IsFromMe(tx))
143 pwallet->DisableTransaction(tx);
148 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
149 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
152 // notify wallets about a new best chain
153 void static SetBestChain(const CBlockLocator& loc)
155 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
156 pwallet->SetBestChain(loc);
159 // notify wallets about an updated transaction
160 void static UpdatedTransaction(const uint256& hashTx)
162 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
163 pwallet->UpdatedTransaction(hashTx);
167 void static PrintWallets(const CBlock& block)
169 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
170 pwallet->PrintWallet(block);
173 // notify wallets about an incoming inventory (for request counts)
174 void static Inventory(const uint256& hash)
176 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
177 pwallet->Inventory(hash);
180 // ask wallets to resend their transactions
181 void ResendWalletTransactions()
183 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
184 pwallet->ResendWalletTransactions();
193 //////////////////////////////////////////////////////////////////////////////
195 // mapOrphanTransactions
198 bool AddOrphanTx(const CTransaction& tx)
200 uint256 hash = tx.GetHash();
201 if (mapOrphanTransactions.count(hash))
204 // Ignore big transactions, to avoid a
205 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
206 // large transaction with a missing parent then we assume
207 // it will rebroadcast it later, after the parent transaction(s)
208 // have been mined or received.
209 // 10,000 orphans, each of which is at most 5,000 bytes big is
210 // at most 500 megabytes of orphans:
212 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
216 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
220 mapOrphanTransactions[hash] = tx;
221 BOOST_FOREACH(const CTxIn& txin, tx.vin)
222 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
224 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
225 mapOrphanTransactions.size());
229 void static EraseOrphanTx(uint256 hash)
231 if (!mapOrphanTransactions.count(hash))
233 const CTransaction& tx = mapOrphanTransactions[hash];
234 BOOST_FOREACH(const CTxIn& txin, tx.vin)
236 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
237 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
238 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
240 mapOrphanTransactions.erase(hash);
243 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
245 unsigned int nEvicted = 0;
246 while (mapOrphanTransactions.size() > nMaxOrphans)
248 // Evict a random orphan:
249 uint256 randomhash = GetRandHash();
250 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
251 if (it == mapOrphanTransactions.end())
252 it = mapOrphanTransactions.begin();
253 EraseOrphanTx(it->first);
265 //////////////////////////////////////////////////////////////////////////////
267 // CTransaction and CTxIndex
270 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
273 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
275 if (!ReadFromDisk(txindexRet.pos))
277 if (prevout.n >= vout.size())
285 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
288 return ReadFromDisk(txdb, prevout, txindex);
291 bool CTransaction::ReadFromDisk(COutPoint prevout)
295 return ReadFromDisk(txdb, prevout, txindex);
298 bool CTransaction::IsStandard() const
300 if (nVersion > CTransaction::CURRENT_VERSION)
303 unsigned int nDataOut = 0;
304 txnouttype whichType;
305 BOOST_FOREACH(const CTxIn& txin, vin)
307 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
308 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
309 // ~65-byte public keys, plus a few script ops.
310 if (txin.scriptSig.size() > 500)
312 if (!txin.scriptSig.IsPushOnly())
314 if (fEnforceCanonical && !txin.scriptSig.HasCanonicalPushes()) {
318 BOOST_FOREACH(const CTxOut& txout, vout) {
319 if (!::IsStandard(txout.scriptPubKey, whichType)) {
322 if (whichType == TX_NULL_DATA)
325 if (txout.nValue == 0) {
328 if (fEnforceCanonical && !txout.scriptPubKey.HasCanonicalPushes()) {
334 // only one OP_RETURN txout is permitted
343 // Check transaction inputs, and make sure any
344 // pay-to-script-hash transactions are evaluating IsStandard scripts
346 // Why bother? To avoid denial-of-service attacks; an attacker
347 // can submit a standard HASH... OP_EQUAL transaction,
348 // which will get accepted into blocks. The redemption
349 // script can be anything; an attacker could use a very
350 // expensive-to-check-upon-redemption script like:
351 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
353 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
356 return true; // Coinbases don't use vin normally
358 for (unsigned int i = 0; i < vin.size(); i++)
360 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
362 vector<vector<unsigned char> > vSolutions;
363 txnouttype whichType;
364 // get the scriptPubKey corresponding to this input:
365 const CScript& prevScript = prev.scriptPubKey;
366 if (!Solver(prevScript, whichType, vSolutions))
368 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
369 if (nArgsExpected < 0)
372 // Transactions with extra stuff in their scriptSigs are
373 // non-standard. Note that this EvalScript() call will
374 // be quick, because if there are any operations
375 // beside "push data" in the scriptSig the
376 // IsStandard() call returns false
377 vector<vector<unsigned char> > stack;
378 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
381 if (whichType == TX_SCRIPTHASH)
385 CScript subscript(stack.back().begin(), stack.back().end());
386 vector<vector<unsigned char> > vSolutions2;
387 txnouttype whichType2;
388 if (!Solver(subscript, whichType2, vSolutions2))
390 if (whichType2 == TX_SCRIPTHASH)
394 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
397 nArgsExpected += tmpExpected;
400 if (stack.size() != (unsigned int)nArgsExpected)
408 CTransaction::GetLegacySigOpCount() const
410 unsigned int nSigOps = 0;
411 BOOST_FOREACH(const CTxIn& txin, vin)
413 nSigOps += txin.scriptSig.GetSigOpCount(false);
415 BOOST_FOREACH(const CTxOut& txout, vout)
417 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
423 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
435 // Load the block this tx is in
437 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
439 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
444 // Update the tx's hashBlock
445 hashBlock = pblock->GetHash();
447 // Locate the transaction
448 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
449 if (pblock->vtx[nIndex] == *(CTransaction*)this)
451 if (nIndex == (int)pblock->vtx.size())
453 vMerkleBranch.clear();
455 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
459 // Fill in merkle branch
460 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
463 // Is the tx in a block that's in the main chain
464 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
465 if (mi == mapBlockIndex.end())
467 CBlockIndex* pindex = (*mi).second;
468 if (!pindex || !pindex->IsInMainChain())
471 return pindexBest->nHeight - pindex->nHeight + 1;
480 bool CTransaction::CheckTransaction() const
482 // Basic checks that don't depend on any context
484 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
486 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
488 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
489 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
491 // Check for negative or overflow output values
493 for (unsigned int i = 0; i < vout.size(); i++)
495 const CTxOut& txout = vout[i];
496 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
497 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
499 if (txout.nValue < 0)
500 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
501 if (txout.nValue > MAX_MONEY)
502 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
503 nValueOut += txout.nValue;
504 if (!MoneyRange(nValueOut))
505 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
508 // Check for duplicate inputs
509 set<COutPoint> vInOutPoints;
510 BOOST_FOREACH(const CTxIn& txin, vin)
512 if (vInOutPoints.count(txin.prevout))
514 vInOutPoints.insert(txin.prevout);
519 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
520 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
524 BOOST_FOREACH(const CTxIn& txin, vin)
525 if (txin.prevout.IsNull())
526 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
532 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
534 // Use new fees approach if we are on test network or
535 // switch date has been reached
536 bool fNewApproach = fTestNet || nTime > FEE_SWITCH_TIME;
538 int64 nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
540 if(!fNewApproach || IsCoinStake())
542 // Enforce 0.01 as minimum fee for old approach or coinstake
544 nMinRelayTxFee = CENT;
547 // Base fee is either nMinTxFee or nMinRelayTxFee
548 int64 nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
550 unsigned int nNewBlockSize = nBlockSize + nBytes;
551 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
559 // Transactions under 1K are free
565 // Free transaction area
566 if (nNewBlockSize < 27000)
571 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
572 // each non empty output which is less than 0.01
574 // It's safe to ignore empty outputs here, because these inputs are allowed
575 // only for coinbase and coinstake transactions.
576 BOOST_FOREACH(const CTxOut& txout, vout)
577 if (txout.nValue < CENT && !txout.IsEmpty())
580 else if (nMinFee < nBaseFee)
582 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if
583 // any output is less than 0.01
584 BOOST_FOREACH(const CTxOut& txout, vout)
585 if (txout.nValue < CENT)
589 // Raise the price as the block approaches full
590 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
592 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
594 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
597 if (!MoneyRange(nMinFee))
604 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
605 bool* pfMissingInputs)
608 *pfMissingInputs = false;
610 if (!tx.CheckTransaction())
611 return error("CTxMemPool::accept() : CheckTransaction failed");
613 // Coinbase is only valid in a block, not as a loose transaction
615 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
617 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
618 if (tx.IsCoinStake())
619 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
621 // To help v0.1.5 clients who would see it as a negative number
622 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
623 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
625 // Rather not work on nonstandard transactions (unless -testnet)
626 if (!fTestNet && !tx.IsStandard())
627 return error("CTxMemPool::accept() : nonstandard transaction type");
629 // Do we already have it?
630 uint256 hash = tx.GetHash();
633 if (mapTx.count(hash))
637 if (txdb.ContainsTx(hash))
640 // Check for conflicts with in-memory transactions
641 CTransaction* ptxOld = NULL;
642 for (unsigned int i = 0; i < tx.vin.size(); i++)
644 COutPoint outpoint = tx.vin[i].prevout;
645 if (mapNextTx.count(outpoint))
647 // Disable replacement feature for now
650 // Allow replacing with a newer version of the same transaction
653 ptxOld = mapNextTx[outpoint].ptx;
654 if (ptxOld->IsFinal())
656 if (!tx.IsNewerThan(*ptxOld))
658 for (unsigned int i = 0; i < tx.vin.size(); i++)
660 COutPoint outpoint = tx.vin[i].prevout;
661 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
671 map<uint256, CTxIndex> mapUnused;
672 bool fInvalid = false;
673 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
676 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
678 *pfMissingInputs = true;
682 // Check for non-standard pay-to-script-hash in inputs
683 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
684 return error("CTxMemPool::accept() : nonstandard transaction input");
686 // Note: if you modify this code to accept non-standard transactions, then
687 // you should add code here to check that the transaction does a
688 // reasonable number of ECDSA signature verifications.
690 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
691 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
693 // Don't accept it if it can't get into a block
694 int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
695 if (nFees < txMinFee)
696 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
697 hash.ToString().c_str(),
700 // Continuously rate-limit free transactions
701 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
702 // be annoying or make others' transactions take longer to confirm.
703 if (nFees < MIN_RELAY_TX_FEE)
705 static CCriticalSection cs;
706 static double dFreeCount;
707 static int64 nLastTime;
708 int64 nNow = GetTime();
712 // Use an exponentially decaying ~10-minute window:
713 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
715 // -limitfreerelay unit is thousand-bytes-per-minute
716 // At default rate it would take over a month to fill 1GB
717 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
718 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
720 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
725 // Check against previous transactions
726 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
727 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
729 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
733 // Store transaction in memory
738 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
741 addUnchecked(hash, tx);
744 ///// are we sure this is ok when loading transactions or restoring block txes
745 // If updated, erase old tx from wallet
747 EraseFromWallets(ptxOld->GetHash());
749 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
750 hash.ToString().substr(0,10).c_str(),
755 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
757 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
760 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
762 // Add to memory pool without checking anything. Don't call this directly,
763 // call CTxMemPool::accept to properly check the transaction first.
766 for (unsigned int i = 0; i < tx.vin.size(); i++)
767 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
768 nTransactionsUpdated++;
774 bool CTxMemPool::remove(CTransaction &tx)
776 // Remove transaction from memory pool
779 uint256 hash = tx.GetHash();
780 if (mapTx.count(hash))
782 BOOST_FOREACH(const CTxIn& txin, tx.vin)
783 mapNextTx.erase(txin.prevout);
785 nTransactionsUpdated++;
791 void CTxMemPool::clear()
796 ++nTransactionsUpdated;
799 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
804 vtxid.reserve(mapTx.size());
805 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
806 vtxid.push_back((*mi).first);
812 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
814 if (hashBlock == 0 || nIndex == -1)
817 // Find the block it claims to be in
818 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
819 if (mi == mapBlockIndex.end())
821 CBlockIndex* pindex = (*mi).second;
822 if (!pindex || !pindex->IsInMainChain())
825 // Make sure the merkle branch connects to this block
826 if (!fMerkleVerified)
828 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
830 fMerkleVerified = true;
834 return pindexBest->nHeight - pindex->nHeight + 1;
838 int CMerkleTx::GetBlocksToMaturity() const
840 if (!(IsCoinBase() || IsCoinStake()))
842 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
846 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
850 if (!IsInMainChain() && !ClientConnectInputs())
852 return CTransaction::AcceptToMemoryPool(txdb, false);
856 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
860 bool CMerkleTx::AcceptToMemoryPool()
863 return AcceptToMemoryPool(txdb);
868 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
873 // Add previous supporting transactions first
874 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
876 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
878 uint256 hash = tx.GetHash();
879 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
880 tx.AcceptToMemoryPool(txdb, fCheckInputs);
883 return AcceptToMemoryPool(txdb, fCheckInputs);
888 bool CWalletTx::AcceptWalletTransaction()
891 return AcceptWalletTransaction(txdb);
894 int CTxIndex::GetDepthInMainChain() const
898 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
900 // Find the block in the index
901 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
902 if (mi == mapBlockIndex.end())
904 CBlockIndex* pindex = (*mi).second;
905 if (!pindex || !pindex->IsInMainChain())
907 return 1 + nBestHeight - pindex->nHeight;
910 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
911 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
917 if (mempool.exists(hash))
919 tx = mempool.lookup(hash);
925 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
928 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
929 hashBlock = block.GetHash();
943 //////////////////////////////////////////////////////////////////////////////
945 // CBlock and CBlockIndex
948 static CBlockIndex* pblockindexFBBHLast;
949 CBlockIndex* FindBlockByHeight(int nHeight)
951 CBlockIndex *pblockindex;
952 if (nHeight < nBestHeight / 2)
953 pblockindex = pindexGenesisBlock;
955 pblockindex = pindexBest;
956 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
957 pblockindex = pblockindexFBBHLast;
958 while (pblockindex->nHeight > nHeight)
959 pblockindex = pblockindex->pprev;
960 while (pblockindex->nHeight < nHeight)
961 pblockindex = pblockindex->pnext;
962 pblockindexFBBHLast = pblockindex;
966 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
968 if (!fReadTransactions)
970 *this = pindex->GetBlockHeader();
973 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
975 if (GetHash() != pindex->GetBlockHash())
976 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
980 uint256 static GetOrphanRoot(const CBlock* pblock)
982 // Work back to the first block in the orphan chain
983 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
984 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
985 return pblock->GetHash();
988 // ppcoin: find block wanted by given orphan block
989 uint256 WantedByOrphan(const CBlock* pblockOrphan)
991 // Work back to the first block in the orphan chain
992 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
993 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
994 return pblockOrphan->hashPrevBlock;
997 // select stake target limit according to hard-coded conditions
998 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1000 if(fTestNet) // separate proof of stake target limit for testnet
1001 return bnProofOfStakeLimit;
1002 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1003 return bnProofOfStakeLimit;
1004 if(nHeight + 1 > 15000) // 24 bits since block 15000
1005 return bnProofOfStakeLegacyLimit;
1006 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1007 return bnProofOfStakeHardLimit;
1009 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1012 // miner's coin base reward based on nBits
1013 int64 GetProofOfWorkReward(unsigned int nBits, int64 nFees)
1015 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1018 bnTarget.SetCompact(nBits);
1019 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1020 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1022 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1023 // A reasonably continuous curve is used to avoid shock to market
1024 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1026 // Human readable form:
1028 // nSubsidy = 100 / (diff ^ 1/6)
1029 CBigNum bnLowerBound = CENT;
1030 CBigNum bnUpperBound = bnSubsidyLimit;
1031 while (bnLowerBound + CENT <= bnUpperBound)
1033 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1034 if (fDebug && GetBoolArg("-printcreation"))
1035 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1036 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1037 bnUpperBound = bnMidValue;
1039 bnLowerBound = bnMidValue;
1042 int64 nSubsidy = bnUpperBound.getuint64();
1044 nSubsidy = (nSubsidy / CENT) * CENT;
1045 if (fDebug && GetBoolArg("-printcreation"))
1046 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1048 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1051 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1052 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
1054 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1056 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1058 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1060 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1062 bnTarget.SetCompact(nBits);
1063 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1064 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1066 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1068 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1069 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1070 bnMidPart, bnRewardPart;
1072 while (bnLowerBound + CENT <= bnUpperBound)
1074 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1075 if (fDebug && GetBoolArg("-printcreation"))
1076 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1078 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1081 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1083 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1085 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1088 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1089 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1094 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1096 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1098 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1101 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1102 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1105 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1106 bnUpperBound = bnMidValue;
1108 bnLowerBound = bnMidValue;
1111 nRewardCoinYear = bnUpperBound.getuint64();
1112 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1116 // Old creation amount per coin-year, 5% fixed stake mint rate
1117 nRewardCoinYear = 5 * CENT;
1121 return nRewardCoinYear;
1123 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1125 // Set reasonable reward limit for large inputs since 20 Oct 2013
1127 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1128 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1130 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1131 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1133 nSubsidy = min(nSubsidy, nSubsidyLimit);
1136 if (fDebug && GetBoolArg("-printcreation"))
1137 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1141 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1143 // get proof of work blocks max spacing according to hard-coded conditions
1144 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1146 if(nTime > TARGETS_SWITCH_TIME)
1147 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1150 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1152 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1156 // maximum nBits value could possible be required nTime after
1158 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1161 bnResult.SetCompact(nBase);
1163 while (nTime > 0 && bnResult < bnTargetLimit)
1165 // Maximum 200% adjustment per day...
1167 nTime -= 24 * 60 * 60;
1169 if (bnResult > bnTargetLimit)
1170 bnResult = bnTargetLimit;
1171 return bnResult.GetCompact();
1175 // minimum amount of work that could possibly be required nTime after
1176 // minimum proof-of-work required was nBase
1178 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1180 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1184 // minimum amount of stake that could possibly be required nTime after
1185 // minimum proof-of-stake required was nBase
1187 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1189 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1193 // ppcoin: find last block index up to pindex
1194 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1196 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1197 pindex = pindex->pprev;
1201 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1203 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1205 if (pindexLast == NULL)
1206 return bnTargetLimit.GetCompact(); // genesis block
1208 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1209 if (pindexPrev->pprev == NULL)
1210 return bnTargetLimit.GetCompact(); // first block
1211 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1212 if (pindexPrevPrev->pprev == NULL)
1213 return bnTargetLimit.GetCompact(); // second block
1215 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1217 // ppcoin: target change every block
1218 // ppcoin: retarget with exponential moving toward target spacing
1220 bnNew.SetCompact(pindexPrev->nBits);
1221 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1222 int64 nInterval = nTargetTimespan / nTargetSpacing;
1223 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1224 bnNew /= ((nInterval + 1) * nTargetSpacing);
1226 if (bnNew > bnTargetLimit)
1227 bnNew = bnTargetLimit;
1229 return bnNew.GetCompact();
1232 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1235 bnTarget.SetCompact(nBits);
1238 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1239 return error("CheckProofOfWork() : nBits below minimum work");
1241 // Check proof of work matches claimed amount
1242 if (hash > bnTarget.getuint256())
1243 return error("CheckProofOfWork() : hash doesn't match nBits");
1248 // Return maximum amount of blocks that other nodes claim to have
1249 int GetNumBlocksOfPeers()
1251 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1254 bool IsInitialBlockDownload()
1256 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1258 static int64 nLastUpdate;
1259 static CBlockIndex* pindexLastBest;
1260 if (pindexBest != pindexLastBest)
1262 pindexLastBest = pindexBest;
1263 nLastUpdate = GetTime();
1265 return (GetTime() - nLastUpdate < 10 &&
1266 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1269 void static InvalidChainFound(CBlockIndex* pindexNew)
1271 if (pindexNew->nChainTrust > nBestInvalidTrust)
1273 nBestInvalidTrust = pindexNew->nChainTrust;
1274 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1275 uiInterface.NotifyBlocksChanged();
1278 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1279 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1281 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1282 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1283 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1284 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1285 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1286 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1287 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1288 nBestBlockTrust.Get64(),
1289 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1293 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1295 nTime = max(GetBlockTime(), GetAdjustedTime());
1308 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1310 // Relinquish previous transactions' spent pointers
1313 BOOST_FOREACH(const CTxIn& txin, vin)
1315 COutPoint prevout = txin.prevout;
1317 // Get prev txindex from disk
1319 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1320 return error("DisconnectInputs() : ReadTxIndex failed");
1322 if (prevout.n >= txindex.vSpent.size())
1323 return error("DisconnectInputs() : prevout.n out of range");
1325 // Mark outpoint as not spent
1326 txindex.vSpent[prevout.n].SetNull();
1329 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1330 return error("DisconnectInputs() : UpdateTxIndex failed");
1334 // Remove transaction from index
1335 // This can fail if a duplicate of this transaction was in a chain that got
1336 // reorganized away. This is only possible if this transaction was completely
1337 // spent, so erasing it would be a no-op anyway.
1338 txdb.EraseTxIndex(*this);
1344 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1345 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1347 // FetchInputs can return false either because we just haven't seen some inputs
1348 // (in which case the transaction should be stored as an orphan)
1349 // or because the transaction is malformed (in which case the transaction should
1350 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1354 return true; // Coinbase transactions have no inputs to fetch.
1356 for (unsigned int i = 0; i < vin.size(); i++)
1358 COutPoint prevout = vin[i].prevout;
1359 if (inputsRet.count(prevout.hash))
1360 continue; // Got it already
1363 CTxIndex& txindex = inputsRet[prevout.hash].first;
1365 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1367 // Get txindex from current proposed changes
1368 txindex = mapTestPool.find(prevout.hash)->second;
1372 // Read txindex from txdb
1373 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1375 if (!fFound && (fBlock || fMiner))
1376 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());
1379 CTransaction& txPrev = inputsRet[prevout.hash].second;
1380 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1382 // Get prev tx from single transactions in memory
1385 if (!mempool.exists(prevout.hash))
1386 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());
1387 txPrev = mempool.lookup(prevout.hash);
1390 txindex.vSpent.resize(txPrev.vout.size());
1394 // Get prev tx from disk
1395 if (!txPrev.ReadFromDisk(txindex.pos))
1396 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1400 // Make sure all prevout.n indexes are valid:
1401 for (unsigned int i = 0; i < vin.size(); i++)
1403 const COutPoint prevout = vin[i].prevout;
1404 assert(inputsRet.count(prevout.hash) != 0);
1405 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1406 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1407 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1409 // Revisit this if/when transaction replacement is implemented and allows
1412 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()));
1419 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1421 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1422 if (mi == inputs.end())
1423 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1425 const CTransaction& txPrev = (mi->second).second;
1426 if (input.prevout.n >= txPrev.vout.size())
1427 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1429 return txPrev.vout[input.prevout.n];
1432 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1438 for (unsigned int i = 0; i < vin.size(); i++)
1440 nResult += GetOutputFor(vin[i], inputs).nValue;
1446 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1451 unsigned int nSigOps = 0;
1452 for (unsigned int i = 0; i < vin.size(); i++)
1454 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1455 if (prevout.scriptPubKey.IsPayToScriptHash())
1456 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1461 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1462 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1464 // Take over previous transactions' spent pointers
1465 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1466 // fMiner is true when called from the internal bitcoin miner
1467 // ... both are false when called from CTransaction::AcceptToMemoryPool
1472 for (unsigned int i = 0; i < vin.size(); i++)
1474 COutPoint prevout = vin[i].prevout;
1475 assert(inputs.count(prevout.hash) > 0);
1476 CTxIndex& txindex = inputs[prevout.hash].first;
1477 CTransaction& txPrev = inputs[prevout.hash].second;
1479 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1480 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()));
1482 // If prev is coinbase or coinstake, check that it's matured
1483 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1484 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1485 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1486 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1488 // ppcoin: check transaction timestamp
1489 if (txPrev.nTime > nTime)
1490 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1492 // Check for negative or overflow input values
1493 nValueIn += txPrev.vout[prevout.n].nValue;
1494 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1495 return DoS(100, error("ConnectInputs() : txin values out of range"));
1498 // The first loop above does all the inexpensive checks.
1499 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1500 // Helps prevent CPU exhaustion attacks.
1501 for (unsigned int i = 0; i < vin.size(); i++)
1503 COutPoint prevout = vin[i].prevout;
1504 assert(inputs.count(prevout.hash) > 0);
1505 CTxIndex& txindex = inputs[prevout.hash].first;
1506 CTransaction& txPrev = inputs[prevout.hash].second;
1508 // Check for conflicts (double-spend)
1509 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1510 // for an attacker to attempt to split the network.
1511 if (!txindex.vSpent[prevout.n].IsNull())
1512 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());
1514 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1515 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1516 // still computed and checked, and any change will be caught at the next checkpoint.
1517 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1520 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1522 // only during transition phase for P2SH: do not invoke anti-DoS code for
1523 // potentially old clients relaying bad P2SH transactions
1524 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1525 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1527 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1531 // Mark outpoints as spent
1532 txindex.vSpent[prevout.n] = posThisTx;
1535 if (fBlock || fMiner)
1537 mapTestPool[prevout.hash] = txindex;
1543 // ppcoin: coin stake tx earns reward instead of paying fee
1545 if (!GetCoinAge(txdb, nCoinAge))
1546 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1548 unsigned int nTxSize = (nTime > VALIDATION_SWITCH_TIME || fTestNet) ? GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION) : 0;
1550 int64 nReward = GetValueOut() - nValueIn;
1551 int64 nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1553 if (nReward > nCalculatedReward)
1554 return DoS(100, error("CheckInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nReward, nCalculatedReward));
1558 if (nValueIn < GetValueOut())
1559 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1561 // Tally transaction fees
1562 int64 nTxFee = nValueIn - GetValueOut();
1564 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1567 if (!MoneyRange(nFees))
1568 return DoS(100, error("ConnectInputs() : nFees out of range"));
1576 bool CTransaction::ClientConnectInputs()
1581 // Take over previous transactions' spent pointers
1585 for (unsigned int i = 0; i < vin.size(); i++)
1587 // Get prev tx from single transactions in memory
1588 COutPoint prevout = vin[i].prevout;
1589 if (!mempool.exists(prevout.hash))
1591 CTransaction& txPrev = mempool.lookup(prevout.hash);
1593 if (prevout.n >= txPrev.vout.size())
1597 if (!VerifySignature(txPrev, *this, i, true, 0))
1598 return error("ConnectInputs() : VerifySignature failed");
1600 ///// this is redundant with the mempool.mapNextTx stuff,
1601 ///// not sure which I want to get rid of
1602 ///// this has to go away now that posNext is gone
1603 // // Check for conflicts
1604 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1605 // return error("ConnectInputs() : prev tx already used");
1607 // // Flag outpoints as used
1608 // txPrev.vout[prevout.n].posNext = posThisTx;
1610 nValueIn += txPrev.vout[prevout.n].nValue;
1612 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1613 return error("ClientConnectInputs() : txin values out of range");
1615 if (GetValueOut() > nValueIn)
1625 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1627 // Disconnect in reverse order
1628 for (int i = vtx.size()-1; i >= 0; i--)
1629 if (!vtx[i].DisconnectInputs(txdb))
1632 // Update block index on disk without changing it in memory.
1633 // The memory index structure will be changed after the db commits.
1636 CDiskBlockIndex blockindexPrev(pindex->pprev);
1637 blockindexPrev.hashNext = 0;
1638 if (!txdb.WriteBlockIndex(blockindexPrev))
1639 return error("DisconnectBlock() : WriteBlockIndex failed");
1642 // ppcoin: clean up wallet after disconnecting coinstake
1643 BOOST_FOREACH(CTransaction& tx, vtx)
1644 SyncWithWallets(tx, this, false, false);
1649 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1651 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1652 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1655 bool fProtocol048 = fTestNet || VALIDATION_SWITCH_TIME < nTime;
1657 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1658 // unless those are already completely spent.
1659 // If such overwrites are allowed, coinbases and transactions depending upon those
1660 // can be duplicated to remove the ability to spend the first instance -- even after
1661 // being sent to another address.
1662 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1663 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1664 // already refuses previously-known transaction ids entirely.
1665 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1666 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1667 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1668 // initial block download.
1669 bool fEnforceBIP30 = true; // Always active in NovaCoin
1670 bool fStrictPayToScriptHash = true; // Always active in NovaCoin
1672 //// issue here: it doesn't know the version
1673 unsigned int nTxPos;
1675 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1676 // 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
1679 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1681 map<uint256, CTxIndex> mapQueuedChanges;
1684 int64 nValueOut = 0;
1685 unsigned int nSigOps = 0;
1686 BOOST_FOREACH(CTransaction& tx, vtx)
1688 uint256 hashTx = tx.GetHash();
1690 if (fEnforceBIP30) {
1691 CTxIndex txindexOld;
1692 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1693 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1699 nSigOps += tx.GetLegacySigOpCount();
1700 if (nSigOps > MAX_BLOCK_SIGOPS)
1701 return DoS(100, error("ConnectBlock() : too many sigops"));
1703 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1705 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1707 MapPrevTx mapInputs;
1708 if (tx.IsCoinBase())
1709 nValueOut += tx.GetValueOut();
1713 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1716 if (fStrictPayToScriptHash)
1718 // Add in sigops done by pay-to-script-hash inputs;
1719 // this is to prevent a "rogue miner" from creating
1720 // an incredibly-expensive-to-validate block.
1721 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1722 if (nSigOps > MAX_BLOCK_SIGOPS)
1723 return DoS(100, error("ConnectBlock() : too many sigops"));
1726 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1727 int64 nTxValueOut = tx.GetValueOut();
1728 nValueIn += nTxValueIn;
1729 nValueOut += nTxValueOut;
1730 if (!tx.IsCoinStake())
1731 nFees += nTxValueIn - nTxValueOut;
1733 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1737 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1740 if (IsProofOfWork())
1742 int64 nBlockReward = GetProofOfWorkReward(nBits, fProtocol048 ? nFees : 0);
1744 // Check coinbase reward
1745 if (vtx[0].GetValueOut() > nBlockReward)
1746 return error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
1747 vtx[0].GetValueOut(),
1751 // track money supply and mint amount info
1752 pindex->nMint = nValueOut - nValueIn + nFees;
1753 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1754 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1755 return error("Connect() : WriteBlockIndex for pindex failed");
1757 // fees are not collected by proof-of-stake miners
1758 // fees are destroyed to compensate the entire network
1759 if (fProtocol048 && fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1760 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1765 // Write queued txindex changes
1766 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1768 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1769 return error("ConnectBlock() : UpdateTxIndex failed");
1772 // Update block index on disk without changing it in memory.
1773 // The memory index structure will be changed after the db commits.
1776 CDiskBlockIndex blockindexPrev(pindex->pprev);
1777 blockindexPrev.hashNext = pindex->GetBlockHash();
1778 if (!txdb.WriteBlockIndex(blockindexPrev))
1779 return error("ConnectBlock() : WriteBlockIndex failed");
1782 // Watch for transactions paying to me
1783 BOOST_FOREACH(CTransaction& tx, vtx)
1784 SyncWithWallets(tx, this, true);
1789 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1791 printf("REORGANIZE\n");
1794 CBlockIndex* pfork = pindexBest;
1795 CBlockIndex* plonger = pindexNew;
1796 while (pfork != plonger)
1798 while (plonger->nHeight > pfork->nHeight)
1799 if (!(plonger = plonger->pprev))
1800 return error("Reorganize() : plonger->pprev is null");
1801 if (pfork == plonger)
1803 if (!(pfork = pfork->pprev))
1804 return error("Reorganize() : pfork->pprev is null");
1807 // List of what to disconnect
1808 vector<CBlockIndex*> vDisconnect;
1809 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1810 vDisconnect.push_back(pindex);
1812 // List of what to connect
1813 vector<CBlockIndex*> vConnect;
1814 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1815 vConnect.push_back(pindex);
1816 reverse(vConnect.begin(), vConnect.end());
1818 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());
1819 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());
1821 // Disconnect shorter branch
1822 vector<CTransaction> vResurrect;
1823 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1826 if (!block.ReadFromDisk(pindex))
1827 return error("Reorganize() : ReadFromDisk for disconnect failed");
1828 if (!block.DisconnectBlock(txdb, pindex))
1829 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1831 // Queue memory transactions to resurrect
1832 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1833 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1834 vResurrect.push_back(tx);
1837 // Connect longer branch
1838 vector<CTransaction> vDelete;
1839 for (unsigned int i = 0; i < vConnect.size(); i++)
1841 CBlockIndex* pindex = vConnect[i];
1843 if (!block.ReadFromDisk(pindex))
1844 return error("Reorganize() : ReadFromDisk for connect failed");
1845 if (!block.ConnectBlock(txdb, pindex))
1848 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1851 // Queue memory transactions to delete
1852 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1853 vDelete.push_back(tx);
1855 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1856 return error("Reorganize() : WriteHashBestChain failed");
1858 // Make sure it's successfully written to disk before changing memory structure
1859 if (!txdb.TxnCommit())
1860 return error("Reorganize() : TxnCommit failed");
1862 // Disconnect shorter branch
1863 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1865 pindex->pprev->pnext = NULL;
1867 // Connect longer branch
1868 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1870 pindex->pprev->pnext = pindex;
1872 // Resurrect memory transactions that were in the disconnected branch
1873 BOOST_FOREACH(CTransaction& tx, vResurrect)
1874 tx.AcceptToMemoryPool(txdb, false);
1876 // Delete redundant memory transactions that are in the connected branch
1877 BOOST_FOREACH(CTransaction& tx, vDelete)
1880 printf("REORGANIZE: done\n");
1886 // Called from inside SetBestChain: attaches a block to the new best chain being built
1887 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1889 uint256 hash = GetHash();
1891 // Adding to current best branch
1892 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1895 InvalidChainFound(pindexNew);
1898 if (!txdb.TxnCommit())
1899 return error("SetBestChain() : TxnCommit failed");
1901 // Add to current best branch
1902 pindexNew->pprev->pnext = pindexNew;
1904 // Delete redundant memory transactions
1905 BOOST_FOREACH(CTransaction& tx, vtx)
1911 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1913 uint256 hash = GetHash();
1915 if (!txdb.TxnBegin())
1916 return error("SetBestChain() : TxnBegin failed");
1918 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1920 txdb.WriteHashBestChain(hash);
1921 if (!txdb.TxnCommit())
1922 return error("SetBestChain() : TxnCommit failed");
1923 pindexGenesisBlock = pindexNew;
1925 else if (hashPrevBlock == hashBestChain)
1927 if (!SetBestChainInner(txdb, pindexNew))
1928 return error("SetBestChain() : SetBestChainInner failed");
1932 // the first block in the new chain that will cause it to become the new best chain
1933 CBlockIndex *pindexIntermediate = pindexNew;
1935 // list of blocks that need to be connected afterwards
1936 std::vector<CBlockIndex*> vpindexSecondary;
1938 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1939 // Try to limit how much needs to be done inside
1940 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1942 vpindexSecondary.push_back(pindexIntermediate);
1943 pindexIntermediate = pindexIntermediate->pprev;
1946 if (!vpindexSecondary.empty())
1947 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1949 // Switch to new best branch
1950 if (!Reorganize(txdb, pindexIntermediate))
1953 InvalidChainFound(pindexNew);
1954 return error("SetBestChain() : Reorganize failed");
1957 // Connect further blocks
1958 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1961 if (!block.ReadFromDisk(pindex))
1963 printf("SetBestChain() : ReadFromDisk failed\n");
1966 if (!txdb.TxnBegin()) {
1967 printf("SetBestChain() : TxnBegin 2 failed\n");
1970 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1971 if (!block.SetBestChainInner(txdb, pindex))
1976 // Update best block in wallet (so we can detect restored wallets)
1977 bool fIsInitialDownload = IsInitialBlockDownload();
1978 if (!fIsInitialDownload)
1980 const CBlockLocator locator(pindexNew);
1981 ::SetBestChain(locator);
1985 hashBestChain = hash;
1986 pindexBest = pindexNew;
1987 pblockindexFBBHLast = NULL;
1988 nBestHeight = pindexBest->nHeight;
1989 nBestChainTrust = pindexNew->nChainTrust;
1990 nTimeBestReceived = GetTime();
1991 nTransactionsUpdated++;
1993 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1995 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1996 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1997 CBigNum(nBestChainTrust).ToString().c_str(),
1998 nBestBlockTrust.Get64(),
1999 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2001 // Check the version of the last 100 blocks to see if we need to upgrade:
2002 if (!fIsInitialDownload)
2005 const CBlockIndex* pindex = pindexBest;
2006 for (int i = 0; i < 100 && pindex != NULL; i++)
2008 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2010 pindex = pindex->pprev;
2013 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2014 if (nUpgraded > 100/2)
2015 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2016 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2019 std::string strCmd = GetArg("-blocknotify", "");
2021 if (!fIsInitialDownload && !strCmd.empty())
2023 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
2024 boost::thread t(runCommand, strCmd); // thread runs free
2030 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2031 // Only those coins meeting minimum age requirement counts. As those
2032 // transactions not in main chain are not currently indexed so we
2033 // might not find out about their coin age. Older transactions are
2034 // guaranteed to be in main chain by sync-checkpoint. This rule is
2035 // introduced to help nodes establish a consistent view of the coin
2036 // age (trust score) of competing branches.
2037 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
2039 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2045 BOOST_FOREACH(const CTxIn& txin, vin)
2047 // First try finding the previous transaction in database
2048 CTransaction txPrev;
2050 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2051 continue; // previous transaction not in main chain
2052 if (nTime < txPrev.nTime)
2053 return false; // Transaction timestamp violation
2055 // Read block header
2057 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2058 return false; // unable to read block of previous transaction
2059 if (block.GetBlockTime() + nStakeMinAge > nTime)
2060 continue; // only count coins meeting min age requirement
2062 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2063 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2065 if (fDebug && GetBoolArg("-printcoinage"))
2066 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2069 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
2070 if (fDebug && GetBoolArg("-printcoinage"))
2071 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2072 nCoinAge = bnCoinDay.getuint64();
2076 // ppcoin: total coin age spent in block, in the unit of coin-days.
2077 bool CBlock::GetCoinAge(uint64& nCoinAge) const
2082 BOOST_FOREACH(const CTransaction& tx, vtx)
2085 if (tx.GetCoinAge(txdb, nTxCoinAge))
2086 nCoinAge += nTxCoinAge;
2091 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2093 if (fDebug && GetBoolArg("-printcoinage"))
2094 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
2098 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2100 // Check for duplicate
2101 uint256 hash = GetHash();
2102 if (mapBlockIndex.count(hash))
2103 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2105 // Construct new block index object
2106 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
2108 return error("AddToBlockIndex() : new CBlockIndex failed");
2109 pindexNew->phashBlock = &hash;
2110 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2111 if (miPrev != mapBlockIndex.end())
2113 pindexNew->pprev = (*miPrev).second;
2114 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2117 // ppcoin: compute chain trust score
2118 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2120 // ppcoin: compute stake entropy bit for stake modifier
2121 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2122 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2124 // ppcoin: record proof-of-stake hash value
2125 if (pindexNew->IsProofOfStake())
2127 if (!mapProofOfStake.count(hash))
2128 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2129 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2132 // ppcoin: compute stake modifier
2133 uint64 nStakeModifier = 0;
2134 bool fGeneratedStakeModifier = false;
2135 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2136 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2137 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2138 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2139 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2140 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2142 // Add to mapBlockIndex
2143 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2144 if (pindexNew->IsProofOfStake())
2145 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2146 pindexNew->phashBlock = &((*mi).first);
2148 // Write to disk block index
2150 if (!txdb.TxnBegin())
2152 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2153 if (!txdb.TxnCommit())
2157 if (pindexNew->nChainTrust > nBestChainTrust)
2158 if (!SetBestChain(txdb, pindexNew))
2161 if (pindexNew == pindexBest)
2163 // Notify UI to display prev block's coinbase if it was ours
2164 static uint256 hashPrevBestCoinBase;
2165 UpdatedTransaction(hashPrevBestCoinBase);
2166 hashPrevBestCoinBase = vtx[0].GetHash();
2169 uiInterface.NotifyBlocksChanged();
2176 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2178 // These are checks that are independent of context
2179 // that can be verified before saving an orphan block.
2182 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2183 return DoS(100, error("CheckBlock() : size limits failed"));
2185 bool fProtocol048 = fTestNet || VALIDATION_SWITCH_TIME < nTime;
2187 // Check proof of work matches claimed amount
2188 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2189 return DoS(50, error("CheckBlock() : proof of work failed"));
2192 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2193 return error("CheckBlock() : block timestamp too far in the future");
2195 // First transaction must be coinbase, the rest must not be
2196 if (vtx.empty() || !vtx[0].IsCoinBase())
2197 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2201 // Check coinbase timestamp
2202 if (GetBlockTime() < (int64)vtx[0].nTime)
2203 return DoS(100, error("CheckBlock() : coinbase timestamp violation"));
2207 // Check coinbase timestamp
2208 if (GetBlockTime() < PastDrift((int64)vtx[0].nTime))
2209 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2212 for (unsigned int i = 1; i < vtx.size(); i++)
2214 if (vtx[i].IsCoinBase())
2215 return DoS(100, error("CheckBlock() : more than one coinbase"));
2217 // Check transaction timestamp
2218 if (GetBlockTime() < (int64)vtx[i].nTime)
2219 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2222 if (IsProofOfStake())
2227 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2230 // Coinbase output should be empty if proof-of-stake block
2231 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2232 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2234 // Second transaction must be coinstake, the rest must not be
2235 if (vtx.empty() || !vtx[1].IsCoinStake())
2236 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2237 for (unsigned int i = 2; i < vtx.size(); i++)
2238 if (vtx[i].IsCoinStake())
2239 return DoS(100, error("CheckBlock() : more than one coinstake"));
2241 // Check coinstake timestamp
2242 if (GetBlockTime() != (int64)vtx[1].nTime)
2243 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2245 // NovaCoin: check proof-of-stake block signature
2246 if (fCheckSig && !CheckBlockSignature(true))
2247 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2251 // Should we check proof-of-work block signature or not?
2253 // * Always skip on TestNet
2254 // * Perform checking for the first 9689 blocks
2255 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2257 if(!fTestNet && fCheckSig)
2259 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2261 // NovaCoin: check proof-of-work block signature
2262 if (checkEntropySig && !CheckBlockSignature(false))
2263 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2267 // Check transactions
2268 BOOST_FOREACH(const CTransaction& tx, vtx)
2270 if (!tx.CheckTransaction())
2271 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2274 // Check for duplicate txids. This is caught by ConnectInputs(),
2275 // but catching it earlier avoids a potential DoS attack:
2276 set<uint256> uniqueTx;
2277 BOOST_FOREACH(const CTransaction& tx, vtx)
2279 uniqueTx.insert(tx.GetHash());
2281 if (uniqueTx.size() != vtx.size())
2282 return DoS(100, error("CheckBlock() : duplicate transaction"));
2284 unsigned int nSigOps = 0;
2285 BOOST_FOREACH(const CTransaction& tx, vtx)
2287 nSigOps += tx.GetLegacySigOpCount();
2289 if (nSigOps > MAX_BLOCK_SIGOPS)
2290 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2292 // Check merkle root
2293 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2294 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2300 bool CBlock::AcceptBlock()
2302 // Check for duplicate
2303 uint256 hash = GetHash();
2304 if (mapBlockIndex.count(hash))
2305 return error("AcceptBlock() : block already in mapBlockIndex");
2307 // Get prev block index
2308 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2309 if (mi == mapBlockIndex.end())
2310 return DoS(10, error("AcceptBlock() : prev block not found"));
2311 CBlockIndex* pindexPrev = (*mi).second;
2312 int nHeight = pindexPrev->nHeight+1;
2314 // Check proof-of-work or proof-of-stake
2315 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2316 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2318 // Check timestamp against prev
2319 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2320 return error("AcceptBlock() : block's timestamp is too early");
2322 // Check that all transactions are finalized
2323 BOOST_FOREACH(const CTransaction& tx, vtx)
2324 if (!tx.IsFinal(nHeight, GetBlockTime()))
2325 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2327 // Check that the block chain matches the known block chain up to a checkpoint
2328 if (!Checkpoints::CheckHardened(nHeight, hash))
2329 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2331 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2333 // Check that the block satisfies synchronized checkpoint
2334 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2335 return error("AcceptBlock() : rejected by synchronized checkpoint");
2337 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2338 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2340 // Enforce rule that the coinbase starts with serialized block height
2341 CScript expect = CScript() << nHeight;
2342 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2343 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2344 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2346 // Write block to history file
2347 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2348 return error("AcceptBlock() : out of disk space");
2349 unsigned int nFile = -1;
2350 unsigned int nBlockPos = 0;
2351 if (!WriteToDisk(nFile, nBlockPos))
2352 return error("AcceptBlock() : WriteToDisk failed");
2353 if (!AddToBlockIndex(nFile, nBlockPos))
2354 return error("AcceptBlock() : AddToBlockIndex failed");
2356 // Relay inventory, but don't relay old inventory during initial block download
2357 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2358 if (hashBestChain == hash)
2361 BOOST_FOREACH(CNode* pnode, vNodes)
2362 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2363 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2366 // ppcoin: check pending sync-checkpoint
2367 Checkpoints::AcceptPendingSyncCheckpoint();
2372 uint256 CBlockIndex::GetBlockTrust() const
2375 bnTarget.SetCompact(nBits);
2381 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2382 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2386 // Calculate work amount for block
2387 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2389 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2390 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2392 // Return nPoWTrust for the first 12 blocks
2393 if (pprev == NULL || pprev->nHeight < 12)
2396 const CBlockIndex* currentIndex = pprev;
2398 if(IsProofOfStake())
2400 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2402 // Return 1/3 of score if parent block is not the PoW block
2403 if (!pprev->IsProofOfWork())
2404 return (bnNewTrust / 3).getuint256();
2408 // Check last 12 blocks type
2409 while (pprev->nHeight - currentIndex->nHeight < 12)
2411 if (currentIndex->IsProofOfWork())
2413 currentIndex = currentIndex->pprev;
2416 // Return 1/3 of score if less than 3 PoW blocks found
2418 return (bnNewTrust / 3).getuint256();
2420 return bnNewTrust.getuint256();
2424 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2426 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2427 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2428 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2432 // Check last 12 blocks type
2433 while (pprev->nHeight - currentIndex->nHeight < 12)
2435 if (currentIndex->IsProofOfStake())
2437 currentIndex = currentIndex->pprev;
2440 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2442 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2444 bnTarget.SetCompact(pprev->nBits);
2449 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2451 // Return nPoWTrust + full trust score for previous block nBits
2452 return nPoWTrust + bnNewTrust.getuint256();
2456 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2458 unsigned int nFound = 0;
2459 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2461 if (pstart->nVersion >= minVersion)
2463 pstart = pstart->pprev;
2465 return (nFound >= nRequired);
2468 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2470 // Check for duplicate
2471 uint256 hash = pblock->GetHash();
2472 if (mapBlockIndex.count(hash))
2473 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2474 if (mapOrphanBlocks.count(hash))
2475 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2477 // ppcoin: check proof-of-stake
2478 // Limited duplicity on stake: prevents block flood attack
2479 // Duplicate stake allowed only when there is orphan child block
2480 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2481 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());
2483 // Preliminary checks
2484 if (!pblock->CheckBlock())
2485 return error("ProcessBlock() : CheckBlock FAILED");
2487 // ppcoin: verify hash target and signature of coinstake tx
2488 if (pblock->IsProofOfStake())
2490 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2491 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2493 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2494 return false; // do not error here as we expect this during initial block download
2496 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2497 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2500 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2501 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2503 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2504 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2506 bnNewBlock.SetCompact(pblock->nBits);
2509 if (pblock->IsProofOfStake())
2510 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2512 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2514 if (bnNewBlock > bnRequired)
2517 pfrom->Misbehaving(100);
2518 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2522 // ppcoin: ask for pending sync-checkpoint if any
2523 if (!IsInitialBlockDownload())
2524 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2526 // If don't already have its previous block, shunt it off to holding area until we get it
2527 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2529 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2530 CBlock* pblock2 = new CBlock(*pblock);
2531 // ppcoin: check proof-of-stake
2532 if (pblock2->IsProofOfStake())
2534 // Limited duplicity on stake: prevents block flood attack
2535 // Duplicate stake allowed only when there is orphan child block
2536 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2537 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());
2539 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2541 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2542 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2544 // Ask this guy to fill in what we're missing
2547 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2548 // ppcoin: getblocks may not obtain the ancestor block rejected
2549 // earlier by duplicate-stake check so we ask for it again directly
2550 if (!IsInitialBlockDownload())
2551 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2557 if (!pblock->AcceptBlock())
2558 return error("ProcessBlock() : AcceptBlock FAILED");
2560 // Recursively process any orphan blocks that depended on this one
2561 vector<uint256> vWorkQueue;
2562 vWorkQueue.push_back(hash);
2563 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2565 uint256 hashPrev = vWorkQueue[i];
2566 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2567 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2570 CBlock* pblockOrphan = (*mi).second;
2571 if (pblockOrphan->AcceptBlock())
2572 vWorkQueue.push_back(pblockOrphan->GetHash());
2573 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2574 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2575 delete pblockOrphan;
2577 mapOrphanBlocksByPrev.erase(hashPrev);
2580 printf("ProcessBlock: ACCEPTED\n");
2582 // ppcoin: if responsible for sync-checkpoint send it
2583 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2584 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2589 // novacoin: attempt to generate suitable proof-of-stake
2590 bool CBlock::SignBlock(CWallet& wallet)
2592 // if we are trying to sign
2593 // something except proof-of-stake block template
2594 if (!vtx[0].vout[0].IsEmpty())
2597 // if we are trying to sign
2598 // a complete proof-of-stake block
2599 if (IsProofOfStake())
2602 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2605 CTransaction txCoinStake;
2606 int64 nSearchTime = txCoinStake.nTime; // search to current time
2608 if (nSearchTime > nLastCoinStakeSearchTime)
2610 if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2612 if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2614 // make sure coinstake would meet timestamp protocol
2615 // as it would be the same as the block timestamp
2616 vtx[0].nTime = nTime = txCoinStake.nTime;
2617 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2618 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2620 // we have to make sure that we have no future timestamps in
2621 // our transactions set
2622 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2623 if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2625 vtx.insert(vtx.begin() + 1, txCoinStake);
2626 hashMerkleRoot = BuildMerkleTree();
2628 // append a signature to our block
2629 return key.Sign(GetHash(), vchBlockSig);
2632 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2633 nLastCoinStakeSearchTime = nSearchTime;
2639 // ppcoin: check block signature
2640 bool CBlock::CheckBlockSignature(bool fProofOfStake) const
2642 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2643 return vchBlockSig.empty();
2645 vector<valtype> vSolutions;
2646 txnouttype whichType;
2650 const CTxOut& txout = vtx[1].vout[1];
2652 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2654 if (whichType == TX_PUBKEY)
2656 valtype& vchPubKey = vSolutions[0];
2658 if (!key.SetPubKey(vchPubKey))
2660 if (vchBlockSig.empty())
2662 return key.Verify(GetHash(), vchBlockSig);
2667 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2669 const CTxOut& txout = vtx[0].vout[i];
2671 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2674 if (whichType == TX_PUBKEY)
2677 valtype& vchPubKey = vSolutions[0];
2679 if (!key.SetPubKey(vchPubKey))
2681 if (vchBlockSig.empty())
2683 if(!key.Verify(GetHash(), vchBlockSig))
2693 bool CheckDiskSpace(uint64 nAdditionalBytes)
2695 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2697 // Check for nMinDiskSpace bytes (currently 50MB)
2698 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2701 string strMessage = _("Warning: Disk space is low!");
2702 strMiscWarning = strMessage;
2703 printf("*** %s\n", strMessage.c_str());
2704 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2711 static filesystem::path BlockFilePath(unsigned int nFile)
2713 string strBlockFn = strprintf("blk%04u.dat", nFile);
2714 return GetDataDir() / strBlockFn;
2717 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2719 if ((nFile < 1) || (nFile == (unsigned int) -1))
2721 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2724 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2726 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2735 static unsigned int nCurrentBlockFile = 1;
2737 FILE* AppendBlockFile(unsigned int& nFileRet)
2742 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2745 if (fseek(file, 0, SEEK_END) != 0)
2747 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2748 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2750 nFileRet = nCurrentBlockFile;
2754 nCurrentBlockFile++;
2758 bool LoadBlockIndex(bool fAllowNew)
2760 CBigNum bnTrustedModulus;
2764 pchMessageStart[0] = 0xcd;
2765 pchMessageStart[1] = 0xf2;
2766 pchMessageStart[2] = 0xc0;
2767 pchMessageStart[3] = 0xef;
2769 bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
2770 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2771 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2772 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2773 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2774 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2778 bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
2781 // Set up the Zerocoin Params object
2782 ZCParams = new libzerocoin::Params(bnTrustedModulus);
2788 if (!txdb.LoadBlockIndex())
2792 // Init with genesis block
2794 if (mapBlockIndex.empty())
2803 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2804 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2805 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2807 // vMerkleTree: 4cb33b3b6a
2811 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2812 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2813 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2815 // vMerkleTree: 4cb33b3b6a
2817 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2819 txNew.nTime = 1360105017;
2820 txNew.vin.resize(1);
2821 txNew.vout.resize(1);
2822 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2823 txNew.vout[0].SetEmpty();
2825 block.vtx.push_back(txNew);
2826 block.hashPrevBlock = 0;
2827 block.hashMerkleRoot = block.BuildMerkleTree();
2829 block.nTime = 1360105017;
2830 block.nBits = bnProofOfWorkLimit.GetCompact();
2831 block.nNonce = !fTestNet ? 1575379 : 46534;
2834 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2836 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2837 assert(block.CheckBlock());
2839 // Start new block file
2841 unsigned int nBlockPos;
2842 if (!block.WriteToDisk(nFile, nBlockPos))
2843 return error("LoadBlockIndex() : writing genesis block to disk failed");
2844 if (!block.AddToBlockIndex(nFile, nBlockPos))
2845 return error("LoadBlockIndex() : genesis block not accepted");
2847 // initialize synchronized checkpoint
2848 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2849 return error("LoadBlockIndex() : failed to init sync checkpoint");
2851 // upgrade time set to zero if txdb initialized
2853 if (!txdb.WriteModifierUpgradeTime(0))
2854 return error("LoadBlockIndex() : failed to init upgrade info");
2855 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2859 string strPubKey = "";
2861 // if checkpoint master key changed must reset sync-checkpoint
2862 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2864 // write checkpoint master key to db
2866 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2867 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2868 if (!txdb.TxnCommit())
2869 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2870 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2871 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2874 // upgrade time set to zero if blocktreedb initialized
2875 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2877 if (nModifierUpgradeTime)
2878 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2880 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2884 nModifierUpgradeTime = GetTime();
2885 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2886 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2887 return error("LoadBlockIndex() : failed to write upgrade info");
2896 void PrintBlockTree()
2898 // pre-compute tree structure
2899 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2900 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2902 CBlockIndex* pindex = (*mi).second;
2903 mapNext[pindex->pprev].push_back(pindex);
2905 //while (rand() % 3 == 0)
2906 // mapNext[pindex->pprev].push_back(pindex);
2909 vector<pair<int, CBlockIndex*> > vStack;
2910 vStack.push_back(make_pair(0, pindexGenesisBlock));
2913 while (!vStack.empty())
2915 int nCol = vStack.back().first;
2916 CBlockIndex* pindex = vStack.back().second;
2919 // print split or gap
2920 if (nCol > nPrevCol)
2922 for (int i = 0; i < nCol-1; i++)
2926 else if (nCol < nPrevCol)
2928 for (int i = 0; i < nCol; i++)
2935 for (int i = 0; i < nCol; i++)
2940 block.ReadFromDisk(pindex);
2941 printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
2945 block.GetHash().ToString().c_str(),
2947 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2948 FormatMoney(pindex->nMint).c_str(),
2951 PrintWallets(block);
2953 // put the main time-chain first
2954 vector<CBlockIndex*>& vNext = mapNext[pindex];
2955 for (unsigned int i = 0; i < vNext.size(); i++)
2957 if (vNext[i]->pnext)
2959 swap(vNext[0], vNext[i]);
2965 for (unsigned int i = 0; i < vNext.size(); i++)
2966 vStack.push_back(make_pair(nCol+i, vNext[i]));
2970 bool LoadExternalBlockFile(FILE* fileIn)
2972 int64 nStart = GetTimeMillis();
2978 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2979 unsigned int nPos = 0;
2980 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2982 unsigned char pchData[65536];
2984 fseek(blkdat, nPos, SEEK_SET);
2985 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2988 nPos = (unsigned int)-1;
2991 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2994 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2996 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2999 nPos += ((unsigned char*)nFind - pchData) + 1;
3002 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
3003 } while(!fRequestShutdown);
3004 if (nPos == (unsigned int)-1)
3006 fseek(blkdat, nPos, SEEK_SET);
3009 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
3013 if (ProcessBlock(NULL,&block))
3021 catch (std::exception &e) {
3022 printf("%s() : Deserialize or I/O error caught during load\n",
3023 __PRETTY_FUNCTION__);
3026 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
3030 //////////////////////////////////////////////////////////////////////////////
3035 extern map<uint256, CAlert> mapAlerts;
3036 extern CCriticalSection cs_mapAlerts;
3038 string GetWarnings(string strFor)
3041 string strStatusBar;
3044 if (GetBoolArg("-testsafemode"))
3047 // Misc warnings like out of disk space and clock is wrong
3048 if (strMiscWarning != "")
3051 strStatusBar = strMiscWarning;
3054 // if detected unmet upgrade requirement enter safe mode
3055 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3056 if (IsFixedModifierInterval(nModifierUpgradeTime + 60*60*24)) // 1 day margin
3059 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3062 // if detected invalid checkpoint enter safe mode
3063 if (Checkpoints::hashInvalidCheckpoint != 0)
3066 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3072 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3074 const CAlert& alert = item.second;
3075 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3077 nPriority = alert.nPriority;
3078 strStatusBar = alert.strStatusBar;
3079 if (nPriority > 1000)
3080 strRPC = strStatusBar;
3085 if (strFor == "statusbar")
3086 return strStatusBar;
3087 else if (strFor == "rpc")
3089 assert(!"GetWarnings() : invalid parameter");
3100 //////////////////////////////////////////////////////////////////////////////
3106 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3112 bool txInMap = false;
3115 txInMap = (mempool.exists(inv.hash));
3118 mapOrphanTransactions.count(inv.hash) ||
3119 txdb.ContainsTx(inv.hash);
3123 return mapBlockIndex.count(inv.hash) ||
3124 mapOrphanBlocks.count(inv.hash);
3126 // Don't know what it is, just say we already got one
3133 // The message start string is designed to be unlikely to occur in normal data.
3134 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3135 // a large 4-byte int at any alignment.
3136 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3138 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3140 static map<CService, CPubKey> mapReuseKey;
3141 RandAddSeedPerfmon();
3143 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3144 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3146 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3150 if (strCommand == "version")
3152 // Each connection can only send one version message
3153 if (pfrom->nVersion != 0)
3155 pfrom->Misbehaving(1);
3163 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3164 if (pfrom->nVersion < MIN_PROTO_VERSION)
3166 // Since February 20, 2012, the protocol is initiated at version 209,
3167 // and earlier versions are no longer supported
3168 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3169 pfrom->fDisconnect = true;
3173 if (pfrom->nVersion == 10300)
3174 pfrom->nVersion = 300;
3176 vRecv >> addrFrom >> nNonce;
3178 vRecv >> pfrom->strSubVer;
3180 vRecv >> pfrom->nStartingHeight;
3182 if (pfrom->fInbound && addrMe.IsRoutable())
3184 pfrom->addrLocal = addrMe;
3188 // Disconnect if we connected to ourself
3189 if (nNonce == nLocalHostNonce && nNonce > 1)
3191 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3192 pfrom->fDisconnect = true;
3196 if (pfrom->nVersion < 60010)
3198 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3199 pfrom->fDisconnect = true;
3203 // record my external IP reported by peer
3204 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3205 addrSeenByPeer = addrMe;
3207 // Be shy and don't send version until we hear
3208 if (pfrom->fInbound)
3209 pfrom->PushVersion();
3211 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3213 AddTimeData(pfrom->addr, nTime);
3216 pfrom->PushMessage("verack");
3217 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3219 if (!pfrom->fInbound)
3221 // Advertise our address
3222 if (!fNoListen && !IsInitialBlockDownload())
3224 CAddress addr = GetLocalAddress(&pfrom->addr);
3225 if (addr.IsRoutable())
3226 pfrom->PushAddress(addr);
3229 // Get recent addresses
3230 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3232 pfrom->PushMessage("getaddr");
3233 pfrom->fGetAddr = true;
3235 addrman.Good(pfrom->addr);
3237 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3239 addrman.Add(addrFrom, addrFrom);
3240 addrman.Good(addrFrom);
3244 // Ask the first connected node for block updates
3245 static int nAskedForBlocks = 0;
3246 if (!pfrom->fClient && !pfrom->fOneShot &&
3247 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3248 (pfrom->nVersion < NOBLKS_VERSION_START ||
3249 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3250 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3253 pfrom->PushGetBlocks(pindexBest, uint256(0));
3259 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3260 item.second.RelayTo(pfrom);
3263 // Relay sync-checkpoint
3265 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3266 if (!Checkpoints::checkpointMessage.IsNull())
3267 Checkpoints::checkpointMessage.RelayTo(pfrom);
3270 pfrom->fSuccessfullyConnected = true;
3272 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());
3274 cPeerBlockCounts.input(pfrom->nStartingHeight);
3276 // ppcoin: ask for pending sync-checkpoint if any
3277 if (!IsInitialBlockDownload())
3278 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3282 else if (pfrom->nVersion == 0)
3284 // Must have a version message before anything else
3285 pfrom->Misbehaving(1);
3290 else if (strCommand == "verack")
3292 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3296 else if (strCommand == "addr")
3298 vector<CAddress> vAddr;
3301 // Don't want addr from older versions unless seeding
3302 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3304 if (vAddr.size() > 1000)
3306 pfrom->Misbehaving(20);
3307 return error("message addr size() = %"PRIszu"", vAddr.size());
3310 // Store the new addresses
3311 vector<CAddress> vAddrOk;
3312 int64 nNow = GetAdjustedTime();
3313 int64 nSince = nNow - 10 * 60;
3314 BOOST_FOREACH(CAddress& addr, vAddr)
3318 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3319 addr.nTime = nNow - 5 * 24 * 60 * 60;
3320 pfrom->AddAddressKnown(addr);
3321 bool fReachable = IsReachable(addr);
3322 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3324 // Relay to a limited number of other nodes
3327 // Use deterministic randomness to send to the same nodes for 24 hours
3328 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3329 static uint256 hashSalt;
3331 hashSalt = GetRandHash();
3332 uint64 hashAddr = addr.GetHash();
3333 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3334 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3335 multimap<uint256, CNode*> mapMix;
3336 BOOST_FOREACH(CNode* pnode, vNodes)
3338 if (pnode->nVersion < CADDR_TIME_VERSION)
3340 unsigned int nPointer;
3341 memcpy(&nPointer, &pnode, sizeof(nPointer));
3342 uint256 hashKey = hashRand ^ nPointer;
3343 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3344 mapMix.insert(make_pair(hashKey, pnode));
3346 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3347 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3348 ((*mi).second)->PushAddress(addr);
3351 // Do not store addresses outside our network
3353 vAddrOk.push_back(addr);
3355 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3356 if (vAddr.size() < 1000)
3357 pfrom->fGetAddr = false;
3358 if (pfrom->fOneShot)
3359 pfrom->fDisconnect = true;
3362 else if (strCommand == "inv")
3366 if (vInv.size() > MAX_INV_SZ)
3368 pfrom->Misbehaving(20);
3369 return error("message inv size() = %"PRIszu"", vInv.size());
3372 // find last block in inv vector
3373 unsigned int nLastBlock = (unsigned int)(-1);
3374 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3375 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3376 nLastBlock = vInv.size() - 1 - nInv;
3381 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3383 const CInv &inv = vInv[nInv];
3387 pfrom->AddInventoryKnown(inv);
3389 bool fAlreadyHave = AlreadyHave(txdb, inv);
3391 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3395 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3396 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3397 } else if (nInv == nLastBlock) {
3398 // In case we are on a very long side-chain, it is possible that we already have
3399 // the last block in an inv bundle sent in response to getblocks. Try to detect
3400 // this situation and push another getblocks to continue.
3401 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3403 printf("force request: %s\n", inv.ToString().c_str());
3406 // Track requests for our stuff
3407 Inventory(inv.hash);
3412 else if (strCommand == "getdata")
3416 if (vInv.size() > MAX_INV_SZ)
3418 pfrom->Misbehaving(20);
3419 return error("message getdata size() = %"PRIszu"", vInv.size());
3422 if (fDebugNet || (vInv.size() != 1))
3423 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3425 BOOST_FOREACH(const CInv& inv, vInv)
3429 if (fDebugNet || (vInv.size() == 1))
3430 printf("received getdata for: %s\n", inv.ToString().c_str());
3432 if (inv.type == MSG_BLOCK)
3434 // Send block from disk
3435 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3436 if (mi != mapBlockIndex.end())
3439 block.ReadFromDisk((*mi).second);
3440 pfrom->PushMessage("block", block);
3442 // Trigger them to send a getblocks request for the next batch of inventory
3443 if (inv.hash == pfrom->hashContinue)
3445 // ppcoin: send latest proof-of-work block to allow the
3446 // download node to accept as orphan (proof-of-stake
3447 // block might be rejected by stake connection check)
3449 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3450 pfrom->PushMessage("inv", vInv);
3451 pfrom->hashContinue = 0;
3455 else if (inv.IsKnownType())
3457 // Send stream from relay memory
3458 bool pushed = false;
3461 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3462 if (mi != mapRelay.end()) {
3463 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3467 if (!pushed && inv.type == MSG_TX) {
3469 if (mempool.exists(inv.hash)) {
3470 CTransaction tx = mempool.lookup(inv.hash);
3471 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3474 pfrom->PushMessage("tx", ss);
3479 // Track requests for our stuff
3480 Inventory(inv.hash);
3485 else if (strCommand == "getblocks")
3487 CBlockLocator locator;
3489 vRecv >> locator >> hashStop;
3491 // Find the last block the caller has in the main chain
3492 CBlockIndex* pindex = locator.GetBlockIndex();
3494 // Send the rest of the chain
3496 pindex = pindex->pnext;
3498 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3499 for (; pindex; pindex = pindex->pnext)
3501 if (pindex->GetBlockHash() == hashStop)
3503 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3504 // ppcoin: tell downloading node about the latest block if it's
3505 // without risk being rejected due to stake connection check
3506 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3507 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3510 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3513 // When this block is requested, we'll send an inv that'll make them
3514 // getblocks the next batch of inventory.
3515 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3516 pfrom->hashContinue = pindex->GetBlockHash();
3521 else if (strCommand == "checkpoint")
3523 CSyncCheckpoint checkpoint;
3524 vRecv >> checkpoint;
3526 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3529 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3531 BOOST_FOREACH(CNode* pnode, vNodes)
3532 checkpoint.RelayTo(pnode);
3536 else if (strCommand == "getheaders")
3538 CBlockLocator locator;
3540 vRecv >> locator >> hashStop;
3542 CBlockIndex* pindex = NULL;
3543 if (locator.IsNull())
3545 // If locator is null, return the hashStop block
3546 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3547 if (mi == mapBlockIndex.end())
3549 pindex = (*mi).second;
3553 // Find the last block the caller has in the main chain
3554 pindex = locator.GetBlockIndex();
3556 pindex = pindex->pnext;
3559 vector<CBlock> vHeaders;
3561 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3562 for (; pindex; pindex = pindex->pnext)
3564 vHeaders.push_back(pindex->GetBlockHeader());
3565 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3568 pfrom->PushMessage("headers", vHeaders);
3572 else if (strCommand == "tx")
3574 vector<uint256> vWorkQueue;
3575 vector<uint256> vEraseQueue;
3576 CDataStream vMsg(vRecv);
3581 CInv inv(MSG_TX, tx.GetHash());
3582 pfrom->AddInventoryKnown(inv);
3584 bool fMissingInputs = false;
3585 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3587 SyncWithWallets(tx, NULL, true);
3588 RelayTransaction(tx, inv.hash);
3589 mapAlreadyAskedFor.erase(inv);
3590 vWorkQueue.push_back(inv.hash);
3591 vEraseQueue.push_back(inv.hash);
3593 // Recursively process any orphan transactions that depended on this one
3594 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3596 uint256 hashPrev = vWorkQueue[i];
3597 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3598 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3601 const uint256& orphanTxHash = *mi;
3602 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3603 bool fMissingInputs2 = false;
3605 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3607 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3608 SyncWithWallets(tx, NULL, true);
3609 RelayTransaction(orphanTx, orphanTxHash);
3610 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3611 vWorkQueue.push_back(orphanTxHash);
3612 vEraseQueue.push_back(orphanTxHash);
3614 else if (!fMissingInputs2)
3617 vEraseQueue.push_back(orphanTxHash);
3618 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3623 BOOST_FOREACH(uint256 hash, vEraseQueue)
3624 EraseOrphanTx(hash);
3626 else if (fMissingInputs)
3630 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3631 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3633 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3635 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3639 else if (strCommand == "block")
3643 uint256 hashBlock = block.GetHash();
3645 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3648 CInv inv(MSG_BLOCK, hashBlock);
3649 pfrom->AddInventoryKnown(inv);
3651 if (ProcessBlock(pfrom, &block))
3652 mapAlreadyAskedFor.erase(inv);
3653 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3657 else if (strCommand == "getaddr")
3659 // Don't return addresses older than nCutOff timestamp
3660 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3661 pfrom->vAddrToSend.clear();
3662 vector<CAddress> vAddr = addrman.GetAddr();
3663 BOOST_FOREACH(const CAddress &addr, vAddr)
3664 if(addr.nTime > nCutOff)
3665 pfrom->PushAddress(addr);
3669 else if (strCommand == "mempool")
3671 std::vector<uint256> vtxid;
3672 mempool.queryHashes(vtxid);
3674 for (unsigned int i = 0; i < vtxid.size(); i++) {
3675 CInv inv(MSG_TX, vtxid[i]);
3676 vInv.push_back(inv);
3677 if (i == (MAX_INV_SZ - 1))
3680 if (vInv.size() > 0)
3681 pfrom->PushMessage("inv", vInv);
3685 else if (strCommand == "checkorder")
3690 if (!GetBoolArg("-allowreceivebyip"))
3692 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3699 /// we have a chance to check the order here
3701 // Keep giving the same key to the same ip until they use it
3702 if (!mapReuseKey.count(pfrom->addr))
3703 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3705 // Send back approval of order and pubkey to use
3706 CScript scriptPubKey;
3707 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3708 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3712 else if (strCommand == "reply")
3717 CRequestTracker tracker;
3719 LOCK(pfrom->cs_mapRequests);
3720 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3721 if (mi != pfrom->mapRequests.end())
3723 tracker = (*mi).second;
3724 pfrom->mapRequests.erase(mi);
3727 if (!tracker.IsNull())
3728 tracker.fn(tracker.param1, vRecv);
3732 else if (strCommand == "ping")
3734 if (pfrom->nVersion > BIP0031_VERSION)
3738 // Echo the message back with the nonce. This allows for two useful features:
3740 // 1) A remote node can quickly check if the connection is operational
3741 // 2) Remote nodes can measure the latency of the network thread. If this node
3742 // is overloaded it won't respond to pings quickly and the remote node can
3743 // avoid sending us more work, like chain download requests.
3745 // The nonce stops the remote getting confused between different pings: without
3746 // it, if the remote node sends a ping once per second and this node takes 5
3747 // seconds to respond to each, the 5th ping the remote sends would appear to
3748 // return very quickly.
3749 pfrom->PushMessage("pong", nonce);
3754 else if (strCommand == "alert")
3759 uint256 alertHash = alert.GetHash();
3760 if (pfrom->setKnown.count(alertHash) == 0)
3762 if (alert.ProcessAlert())
3765 pfrom->setKnown.insert(alertHash);
3768 BOOST_FOREACH(CNode* pnode, vNodes)
3769 alert.RelayTo(pnode);
3773 // Small DoS penalty so peers that send us lots of
3774 // duplicate/expired/invalid-signature/whatever alerts
3775 // eventually get banned.
3776 // This isn't a Misbehaving(100) (immediate ban) because the
3777 // peer might be an older or different implementation with
3778 // a different signature key, etc.
3779 pfrom->Misbehaving(10);
3787 // Ignore unknown commands for extensibility
3791 // Update the last seen time for this node's address
3792 if (pfrom->fNetworkNode)
3793 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3794 AddressCurrentlyConnected(pfrom->addr);
3800 bool ProcessMessages(CNode* pfrom)
3802 CDataStream& vRecv = pfrom->vRecv;
3806 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3810 // (4) message start
3819 // Don't bother if send buffer is too full to respond anyway
3820 if (pfrom->vSend.size() >= SendBufferSize())
3823 // Scan for message start
3824 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3825 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3826 if (vRecv.end() - pstart < nHeaderSize)
3828 if ((int)vRecv.size() > nHeaderSize)
3830 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3831 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3835 if (pstart - vRecv.begin() > 0)
3836 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3837 vRecv.erase(vRecv.begin(), pstart);
3840 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3845 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3848 string strCommand = hdr.GetCommand();
3851 unsigned int nMessageSize = hdr.nMessageSize;
3852 if (nMessageSize > MAX_SIZE)
3854 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3857 if (nMessageSize > vRecv.size())
3859 // Rewind and wait for rest of message
3860 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3865 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3866 unsigned int nChecksum = 0;
3867 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3868 if (nChecksum != hdr.nChecksum)
3870 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3871 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3875 // Copy message to its own buffer
3876 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3877 vRecv.ignore(nMessageSize);
3885 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3890 catch (std::ios_base::failure& e)
3892 if (strstr(e.what(), "end of data"))
3894 // Allow exceptions from under-length message on vRecv
3895 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());
3897 else if (strstr(e.what(), "size too large"))
3899 // Allow exceptions from over-long size
3900 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3904 PrintExceptionContinue(&e, "ProcessMessages()");
3907 catch (std::exception& e) {
3908 PrintExceptionContinue(&e, "ProcessMessages()");
3910 PrintExceptionContinue(NULL, "ProcessMessages()");
3914 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3922 bool SendMessages(CNode* pto, bool fSendTrickle)
3924 TRY_LOCK(cs_main, lockMain);
3926 // Don't send anything until we get their version message
3927 if (pto->nVersion == 0)
3930 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3932 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3934 if (pto->nVersion > BIP0031_VERSION)
3935 pto->PushMessage("ping", nonce);
3937 pto->PushMessage("ping");
3940 // Resend wallet transactions that haven't gotten in a block yet
3941 ResendWalletTransactions();
3943 // Address refresh broadcast
3944 static int64 nLastRebroadcast;
3945 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3949 BOOST_FOREACH(CNode* pnode, vNodes)
3951 // Periodically clear setAddrKnown to allow refresh broadcasts
3952 if (nLastRebroadcast)
3953 pnode->setAddrKnown.clear();
3955 // Rebroadcast our address
3958 CAddress addr = GetLocalAddress(&pnode->addr);
3959 if (addr.IsRoutable())
3960 pnode->PushAddress(addr);
3964 nLastRebroadcast = GetTime();
3972 vector<CAddress> vAddr;
3973 vAddr.reserve(pto->vAddrToSend.size());
3974 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3976 // returns true if wasn't already contained in the set
3977 if (pto->setAddrKnown.insert(addr).second)
3979 vAddr.push_back(addr);
3980 // receiver rejects addr messages larger than 1000
3981 if (vAddr.size() >= 1000)
3983 pto->PushMessage("addr", vAddr);
3988 pto->vAddrToSend.clear();
3990 pto->PushMessage("addr", vAddr);
3995 // Message: inventory
3998 vector<CInv> vInvWait;
4000 LOCK(pto->cs_inventory);
4001 vInv.reserve(pto->vInventoryToSend.size());
4002 vInvWait.reserve(pto->vInventoryToSend.size());
4003 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4005 if (pto->setInventoryKnown.count(inv))
4008 // trickle out tx inv to protect privacy
4009 if (inv.type == MSG_TX && !fSendTrickle)
4011 // 1/4 of tx invs blast to all immediately
4012 static uint256 hashSalt;
4014 hashSalt = GetRandHash();
4015 uint256 hashRand = inv.hash ^ hashSalt;
4016 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4017 bool fTrickleWait = ((hashRand & 3) != 0);
4019 // always trickle our own transactions
4023 if (GetTransaction(inv.hash, wtx))
4025 fTrickleWait = true;
4030 vInvWait.push_back(inv);
4035 // returns true if wasn't already contained in the set
4036 if (pto->setInventoryKnown.insert(inv).second)
4038 vInv.push_back(inv);
4039 if (vInv.size() >= 1000)
4041 pto->PushMessage("inv", vInv);
4046 pto->vInventoryToSend = vInvWait;
4049 pto->PushMessage("inv", vInv);
4055 vector<CInv> vGetData;
4056 int64 nNow = GetTime() * 1000000;
4058 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4060 const CInv& inv = (*pto->mapAskFor.begin()).second;
4061 if (!AlreadyHave(txdb, inv))
4064 printf("sending getdata: %s\n", inv.ToString().c_str());
4065 vGetData.push_back(inv);
4066 if (vGetData.size() >= 1000)
4068 pto->PushMessage("getdata", vGetData);
4071 mapAlreadyAskedFor[inv] = nNow;
4073 pto->mapAskFor.erase(pto->mapAskFor.begin());
4075 if (!vGetData.empty())
4076 pto->PushMessage("getdata", vGetData);