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"
13 #include "checkqueue.h"
15 #include <boost/algorithm/string/replace.hpp>
16 #include <boost/filesystem.hpp>
17 #include <boost/filesystem/fstream.hpp>
22 using namespace boost;
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
29 CCriticalSection cs_main;
32 unsigned int nTransactionsUpdated = 0;
34 map<uint256, CBlockIndex*> mapBlockIndex;
35 set<pair<COutPoint, unsigned int> > setStakeSeen;
37 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
38 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
39 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
40 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
41 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
43 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
45 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as zero time weight
46 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
47 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
48 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
50 int nCoinbaseMaturity = 500;
52 CBlockIndex* pindexGenesisBlock = NULL;
55 uint256 nBestChainTrust = 0;
56 uint256 nBestInvalidTrust = 0;
58 uint256 hashBestChain = 0;
59 CBlockIndex* pindexBest = NULL;
60 int64_t nTimeBestReceived = 0;
61 int nScriptCheckThreads = 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_t nTransactionFee = MIN_TX_FEE;
80 int64_t nMinimumInputValue = MIN_TXOUT_AMOUNT;
82 // Ping and address broadcast intervals
83 int64_t nPingInterval = 30 * 60;
84 int64_t nBroadcastInterval = 24 * 60 * 60;
86 extern enum Checkpoints::CPMode CheckpointsMode;
88 //////////////////////////////////////////////////////////////////////////////
90 // dispatching functions
93 // These functions dispatch to one or all registered wallets
96 void RegisterWallet(CWallet* pwalletIn)
99 LOCK(cs_setpwalletRegistered);
100 setpwalletRegistered.insert(pwalletIn);
104 void UnregisterWallet(CWallet* pwalletIn)
107 LOCK(cs_setpwalletRegistered);
108 setpwalletRegistered.erase(pwalletIn);
112 // check whether the passed transaction is from us
113 bool static IsFromMe(CTransaction& tx)
115 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
116 if (pwallet->IsFromMe(tx))
121 // get the wallet transaction with the given hash (if it exists)
122 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
124 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
125 if (pwallet->GetTransaction(hashTx,wtx))
130 // erases transaction with the given hash from all wallets
131 void static EraseFromWallets(uint256 hash)
133 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
134 pwallet->EraseFromWallet(hash);
137 // make sure all wallets know about the given transaction, in the given block
138 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
142 // ppcoin: wallets need to refund inputs when disconnecting coinstake
143 if (tx.IsCoinStake())
145 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
146 if (pwallet->IsFromMe(tx))
147 pwallet->DisableTransaction(tx);
152 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
153 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
156 // notify wallets about a new best chain
157 void static SetBestChain(const CBlockLocator& loc)
159 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
160 pwallet->SetBestChain(loc);
163 // notify wallets about an updated transaction
164 void static UpdatedTransaction(const uint256& hashTx)
166 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
167 pwallet->UpdatedTransaction(hashTx);
171 void static PrintWallets(const CBlock& block)
173 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
174 pwallet->PrintWallet(block);
177 // notify wallets about an incoming inventory (for request counts)
178 void static Inventory(const uint256& hash)
180 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
181 pwallet->Inventory(hash);
184 // ask wallets to resend their transactions
185 void ResendWalletTransactions()
187 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
188 pwallet->ResendWalletTransactions();
197 //////////////////////////////////////////////////////////////////////////////
199 // mapOrphanTransactions
202 bool AddOrphanTx(const CTransaction& tx)
204 uint256 hash = tx.GetHash();
205 if (mapOrphanTransactions.count(hash))
208 // Ignore big transactions, to avoid a
209 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
210 // large transaction with a missing parent then we assume
211 // it will rebroadcast it later, after the parent transaction(s)
212 // have been mined or received.
213 // 10,000 orphans, each of which is at most 5,000 bytes big is
214 // at most 500 megabytes of orphans:
216 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
220 printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
224 mapOrphanTransactions[hash] = tx;
225 BOOST_FOREACH(const CTxIn& txin, tx.vin)
226 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
228 printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
229 mapOrphanTransactions.size());
233 void static EraseOrphanTx(uint256 hash)
235 if (!mapOrphanTransactions.count(hash))
237 const CTransaction& tx = mapOrphanTransactions[hash];
238 BOOST_FOREACH(const CTxIn& txin, tx.vin)
240 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
241 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
242 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
244 mapOrphanTransactions.erase(hash);
247 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
249 unsigned int nEvicted = 0;
250 while (mapOrphanTransactions.size() > nMaxOrphans)
252 // Evict a random orphan:
253 uint256 randomhash = GetRandHash();
254 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
255 if (it == mapOrphanTransactions.end())
256 it = mapOrphanTransactions.begin();
257 EraseOrphanTx(it->first);
269 //////////////////////////////////////////////////////////////////////////////
271 // CTransaction and CTxIndex
274 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
277 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
279 if (!ReadFromDisk(txindexRet.pos))
281 if (prevout.n >= vout.size())
289 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
292 return ReadFromDisk(txdb, prevout, txindex);
295 bool CTransaction::ReadFromDisk(COutPoint prevout)
299 return ReadFromDisk(txdb, prevout, txindex);
302 bool CTransaction::IsStandard(string& strReason) const
304 if (nVersion > CTransaction::CURRENT_VERSION)
306 strReason = "version";
310 unsigned int nDataOut = 0;
311 txnouttype whichType;
312 BOOST_FOREACH(const CTxIn& txin, vin)
314 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
315 // keys. (remember the 520 byte limit on redeemScript size) That works
316 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
317 // bytes of scriptSig, which we round off to 1650 bytes for some minor
318 // future-proofing. That's also enough to spend a 20-of-20
319 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
320 // considered standard)
321 if (txin.scriptSig.size() > 1650)
323 strReason = "scriptsig-size";
326 if (!txin.scriptSig.IsPushOnly())
328 strReason = "scriptsig-not-pushonly";
331 if (!txin.scriptSig.HasCanonicalPushes()) {
332 strReason = "txin-scriptsig-not-canonicalpushes";
336 BOOST_FOREACH(const CTxOut& txout, vout) {
337 if (!::IsStandard(txout.scriptPubKey, whichType)) {
338 strReason = "scriptpubkey";
341 if (whichType == TX_NULL_DATA)
344 if (txout.nValue == 0) {
345 strReason = "txout-value=0";
348 if (!txout.scriptPubKey.HasCanonicalPushes()) {
349 strReason = "txout-scriptsig-not-canonicalpushes";
355 // only one OP_RETURN txout is permitted
357 strReason = "multi-op-return";
365 // Check transaction inputs, and make sure any
366 // pay-to-script-hash transactions are evaluating IsStandard scripts
368 // Why bother? To avoid denial-of-service attacks; an attacker
369 // can submit a standard HASH... OP_EQUAL transaction,
370 // which will get accepted into blocks. The redemption
371 // script can be anything; an attacker could use a very
372 // expensive-to-check-upon-redemption script like:
373 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
375 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
378 return true; // Coinbases don't use vin normally
380 for (unsigned int i = 0; i < vin.size(); i++)
382 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
384 vector<vector<unsigned char> > vSolutions;
385 txnouttype whichType;
386 // get the scriptPubKey corresponding to this input:
387 const CScript& prevScript = prev.scriptPubKey;
388 if (!Solver(prevScript, whichType, vSolutions))
390 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
391 if (nArgsExpected < 0)
394 // Transactions with extra stuff in their scriptSigs are
395 // non-standard. Note that this EvalScript() call will
396 // be quick, because if there are any operations
397 // beside "push data" in the scriptSig the
398 // IsStandard() call returns false
399 vector<vector<unsigned char> > stack;
400 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
403 if (whichType == TX_SCRIPTHASH)
407 CScript subscript(stack.back().begin(), stack.back().end());
408 vector<vector<unsigned char> > vSolutions2;
409 txnouttype whichType2;
410 if (!Solver(subscript, whichType2, vSolutions2))
412 if (whichType2 == TX_SCRIPTHASH)
416 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
419 nArgsExpected += tmpExpected;
422 if (stack.size() != (unsigned int)nArgsExpected)
430 CTransaction::GetLegacySigOpCount() const
432 unsigned int nSigOps = 0;
433 BOOST_FOREACH(const CTxIn& txin, vin)
435 nSigOps += txin.scriptSig.GetSigOpCount(false);
437 BOOST_FOREACH(const CTxOut& txout, vout)
439 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
445 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
457 // Load the block this tx is in
459 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
461 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
466 // Update the tx's hashBlock
467 hashBlock = pblock->GetHash();
469 // Locate the transaction
470 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
471 if (pblock->vtx[nIndex] == *(CTransaction*)this)
473 if (nIndex == (int)pblock->vtx.size())
475 vMerkleBranch.clear();
477 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
481 // Fill in merkle branch
482 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
485 // Is the tx in a block that's in the main chain
486 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
487 if (mi == mapBlockIndex.end())
489 CBlockIndex* pindex = (*mi).second;
490 if (!pindex || !pindex->IsInMainChain())
493 return pindexBest->nHeight - pindex->nHeight + 1;
502 bool CTransaction::CheckTransaction() const
504 // Basic checks that don't depend on any context
506 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
508 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
510 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
511 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
513 // Check for negative or overflow output values
514 int64_t nValueOut = 0;
515 for (unsigned int i = 0; i < vout.size(); i++)
517 const CTxOut& txout = vout[i];
518 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
519 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
521 if (txout.nValue < 0)
522 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
523 if (txout.nValue > MAX_MONEY)
524 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
525 nValueOut += txout.nValue;
526 if (!MoneyRange(nValueOut))
527 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
530 // Check for duplicate inputs
531 set<COutPoint> vInOutPoints;
532 BOOST_FOREACH(const CTxIn& txin, vin)
534 if (vInOutPoints.count(txin.prevout))
536 vInOutPoints.insert(txin.prevout);
541 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
542 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
546 BOOST_FOREACH(const CTxIn& txin, vin)
547 if (txin.prevout.IsNull())
548 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
554 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
556 int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
560 // Enforce 0.01 as minimum fee for old approach or coinstake
562 nMinRelayTxFee = CENT;
565 // Base fee is either nMinTxFee or nMinRelayTxFee
566 int64_t nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
568 unsigned int nNewBlockSize = nBlockSize + nBytes;
569 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
575 // Transactions under 1K are free
581 // Free transaction area
582 if (nNewBlockSize < 27000)
587 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
588 // each non empty output which is less than 0.01
590 // It's safe to ignore empty outputs here, because these inputs are allowed
591 // only for coinbase and coinstake transactions.
592 BOOST_FOREACH(const CTxOut& txout, vout)
593 if (txout.nValue < CENT && !txout.IsEmpty())
596 // Raise the price as the block approaches full
597 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
599 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
601 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
604 if (!MoneyRange(nMinFee))
611 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
612 bool* pfMissingInputs)
615 *pfMissingInputs = false;
617 if (!tx.CheckTransaction())
618 return error("CTxMemPool::accept() : CheckTransaction failed");
620 // Coinbase is only valid in a block, not as a loose transaction
622 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
624 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
625 if (tx.IsCoinStake())
626 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
628 // To help v0.1.5 clients who would see it as a negative number
629 if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
630 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
632 // Rather not work on nonstandard transactions (unless -testnet)
634 if (!fTestNet && !tx.IsStandard(strNonStd))
635 return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
637 // Do we already have it?
638 uint256 hash = tx.GetHash();
641 if (mapTx.count(hash))
645 if (txdb.ContainsTx(hash))
648 // Check for conflicts with in-memory transactions
649 CTransaction* ptxOld = NULL;
650 for (unsigned int i = 0; i < tx.vin.size(); i++)
652 COutPoint outpoint = tx.vin[i].prevout;
653 if (mapNextTx.count(outpoint))
655 // Disable replacement feature for now
658 // Allow replacing with a newer version of the same transaction
661 ptxOld = mapNextTx[outpoint].ptx;
662 if (ptxOld->IsFinal())
664 if (!tx.IsNewerThan(*ptxOld))
666 for (unsigned int i = 0; i < tx.vin.size(); i++)
668 COutPoint outpoint = tx.vin[i].prevout;
669 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
679 map<uint256, CTxIndex> mapUnused;
680 bool fInvalid = false;
681 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
684 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
686 *pfMissingInputs = true;
690 // Check for non-standard pay-to-script-hash in inputs
691 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
692 return error("CTxMemPool::accept() : nonstandard transaction input");
694 // Note: if you modify this code to accept non-standard transactions, then
695 // you should add code here to check that the transaction does a
696 // reasonable number of ECDSA signature verifications.
698 int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
699 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
701 // Don't accept it if it can't get into a block
702 int64_t txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
703 if (nFees < txMinFee)
704 return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
705 hash.ToString().c_str(),
708 // Continuously rate-limit free transactions
709 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
710 // be annoying or make others' transactions take longer to confirm.
711 if (nFees < MIN_RELAY_TX_FEE)
713 static CCriticalSection cs;
714 static double dFreeCount;
715 static int64_t nLastTime;
716 int64_t nNow = GetTime();
720 // Use an exponentially decaying ~10-minute window:
721 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
723 // -limitfreerelay unit is thousand-bytes-per-minute
724 // At default rate it would take over a month to fill 1GB
725 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
726 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
728 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
733 // Check against previous transactions
734 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
735 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, SIG_SWITCH_TIME < tx.nTime ? STRICT_FLAGS : SOFT_FLAGS))
737 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
741 // Store transaction in memory
746 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
749 addUnchecked(hash, tx);
752 ///// are we sure this is ok when loading transactions or restoring block txes
753 // If updated, erase old tx from wallet
755 EraseFromWallets(ptxOld->GetHash());
757 printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
758 hash.ToString().substr(0,10).c_str(),
763 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
765 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
768 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
770 // Add to memory pool without checking anything. Don't call this directly,
771 // call CTxMemPool::accept to properly check the transaction first.
774 for (unsigned int i = 0; i < tx.vin.size(); i++)
775 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
776 nTransactionsUpdated++;
782 bool CTxMemPool::remove(CTransaction &tx)
784 // Remove transaction from memory pool
787 uint256 hash = tx.GetHash();
788 if (mapTx.count(hash))
790 BOOST_FOREACH(const CTxIn& txin, tx.vin)
791 mapNextTx.erase(txin.prevout);
793 nTransactionsUpdated++;
799 void CTxMemPool::clear()
804 ++nTransactionsUpdated;
807 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
812 vtxid.reserve(mapTx.size());
813 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
814 vtxid.push_back((*mi).first);
820 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
822 if (hashBlock == 0 || nIndex == -1)
825 // Find the block it claims to be in
826 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
827 if (mi == mapBlockIndex.end())
829 CBlockIndex* pindex = (*mi).second;
830 if (!pindex || !pindex->IsInMainChain())
833 // Make sure the merkle branch connects to this block
834 if (!fMerkleVerified)
836 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
838 fMerkleVerified = true;
842 return pindexBest->nHeight - pindex->nHeight + 1;
846 int CMerkleTx::GetBlocksToMaturity() const
848 if (!(IsCoinBase() || IsCoinStake()))
850 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
854 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
858 if (!IsInMainChain() && !ClientConnectInputs())
860 return CTransaction::AcceptToMemoryPool(txdb, false);
864 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
868 bool CMerkleTx::AcceptToMemoryPool()
871 return AcceptToMemoryPool(txdb);
876 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
881 // Add previous supporting transactions first
882 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
884 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
886 uint256 hash = tx.GetHash();
887 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
888 tx.AcceptToMemoryPool(txdb, fCheckInputs);
891 return AcceptToMemoryPool(txdb, fCheckInputs);
896 bool CWalletTx::AcceptWalletTransaction()
899 return AcceptWalletTransaction(txdb);
902 int CTxIndex::GetDepthInMainChain() const
906 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
908 // Find the block in the index
909 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
910 if (mi == mapBlockIndex.end())
912 CBlockIndex* pindex = (*mi).second;
913 if (!pindex || !pindex->IsInMainChain())
915 return 1 + nBestHeight - pindex->nHeight;
918 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
919 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
925 if (mempool.exists(hash))
927 tx = mempool.lookup(hash);
933 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
936 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
937 hashBlock = block.GetHash();
951 //////////////////////////////////////////////////////////////////////////////
953 // CBlock and CBlockIndex
956 static CBlockIndex* pblockindexFBBHLast;
957 CBlockIndex* FindBlockByHeight(int nHeight)
959 CBlockIndex *pblockindex;
960 if (nHeight < nBestHeight / 2)
961 pblockindex = pindexGenesisBlock;
963 pblockindex = pindexBest;
964 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
965 pblockindex = pblockindexFBBHLast;
966 while (pblockindex->nHeight > nHeight)
967 pblockindex = pblockindex->pprev;
968 while (pblockindex->nHeight < nHeight)
969 pblockindex = pblockindex->pnext;
970 pblockindexFBBHLast = pblockindex;
974 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
976 if (!fReadTransactions)
978 *this = pindex->GetBlockHeader();
981 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
983 if (GetHash() != pindex->GetBlockHash())
984 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
988 uint256 static GetOrphanRoot(const CBlock* pblock)
990 // Work back to the first block in the orphan chain
991 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
992 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
993 return pblock->GetHash();
996 // ppcoin: find block wanted by given orphan block
997 uint256 WantedByOrphan(const CBlock* pblockOrphan)
999 // Work back to the first block in the orphan chain
1000 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
1001 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
1002 return pblockOrphan->hashPrevBlock;
1005 // select stake target limit according to hard-coded conditions
1006 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1008 if(fTestNet) // separate proof of stake target limit for testnet
1009 return bnProofOfStakeLimit;
1010 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1011 return bnProofOfStakeLimit;
1012 if(nHeight + 1 > 15000) // 24 bits since block 15000
1013 return bnProofOfStakeLegacyLimit;
1014 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1015 return bnProofOfStakeHardLimit;
1017 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1020 // miner's coin base reward based on nBits
1021 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees)
1023 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1026 bnTarget.SetCompact(nBits);
1027 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1028 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1030 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1031 // A reasonably continuous curve is used to avoid shock to market
1032 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1034 // Human readable form:
1036 // nSubsidy = 100 / (diff ^ 1/6)
1038 // Please note that we're using bisection to find an approximate solutuion
1039 CBigNum bnLowerBound = CENT;
1040 CBigNum bnUpperBound = bnSubsidyLimit;
1041 while (bnLowerBound + CENT <= bnUpperBound)
1043 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1044 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1045 bnUpperBound = bnMidValue;
1047 bnLowerBound = bnMidValue;
1050 int64_t nSubsidy = bnUpperBound.getuint64();
1052 nSubsidy = (nSubsidy / CENT) * CENT;
1053 if (fDebug && GetBoolArg("-printcreation"))
1054 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1056 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1059 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1060 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1062 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1064 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1066 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1068 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1070 bnTarget.SetCompact(nBits);
1071 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1072 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1074 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1076 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1077 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1078 bnMidPart, bnRewardPart;
1080 while (bnLowerBound + CENT <= bnUpperBound)
1082 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1083 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1086 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1088 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1090 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1093 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1094 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1099 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1101 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1103 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1106 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1107 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1110 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1111 bnUpperBound = bnMidValue;
1113 bnLowerBound = bnMidValue;
1116 nRewardCoinYear = bnUpperBound.getuint64();
1117 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1121 // Old creation amount per coin-year, 5% fixed stake mint rate
1122 nRewardCoinYear = 5 * CENT;
1126 return nRewardCoinYear;
1128 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1130 // Set reasonable reward limit for large inputs since 20 Oct 2013
1132 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1133 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1135 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1136 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1138 nSubsidy = min(nSubsidy, nSubsidyLimit);
1141 if (fDebug && GetBoolArg("-printcreation"))
1142 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1146 static const int64_t nTargetTimespan = 7 * 24 * 60 * 60; // one week
1148 // get proof of work blocks max spacing according to hard-coded conditions
1149 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1151 if(nTime > TARGETS_SWITCH_TIME)
1152 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1155 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1157 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1161 // maximum nBits value could possible be required nTime after
1163 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1166 bnResult.SetCompact(nBase);
1168 while (nTime > 0 && bnResult < bnTargetLimit)
1170 // Maximum 200% adjustment per day...
1172 nTime -= 24 * 60 * 60;
1174 if (bnResult > bnTargetLimit)
1175 bnResult = bnTargetLimit;
1176 return bnResult.GetCompact();
1180 // minimum amount of work that could possibly be required nTime after
1181 // minimum proof-of-work required was nBase
1183 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1185 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1189 // minimum amount of stake that could possibly be required nTime after
1190 // minimum proof-of-stake required was nBase
1192 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1194 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1198 // ppcoin: find last block index up to pindex
1199 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1201 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1202 pindex = pindex->pprev;
1206 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1208 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1210 if (pindexLast == NULL)
1211 return bnTargetLimit.GetCompact(); // genesis block
1213 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1214 if (pindexPrev->pprev == NULL)
1215 return bnTargetLimit.GetCompact(); // first block
1216 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1217 if (pindexPrevPrev->pprev == NULL)
1218 return bnTargetLimit.GetCompact(); // second block
1220 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1222 // ppcoin: target change every block
1223 // ppcoin: retarget with exponential moving toward target spacing
1225 bnNew.SetCompact(pindexPrev->nBits);
1226 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1227 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1228 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1229 bnNew /= ((nInterval + 1) * nTargetSpacing);
1231 if (bnNew > bnTargetLimit)
1232 bnNew = bnTargetLimit;
1234 return bnNew.GetCompact();
1237 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1240 bnTarget.SetCompact(nBits);
1243 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1244 return error("CheckProofOfWork() : nBits below minimum work");
1246 // Check proof of work matches claimed amount
1247 if (hash > bnTarget.getuint256())
1248 return error("CheckProofOfWork() : hash doesn't match nBits");
1253 // Return maximum amount of blocks that other nodes claim to have
1254 int GetNumBlocksOfPeers()
1256 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1259 bool IsInitialBlockDownload()
1261 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1263 static int64_t nLastUpdate;
1264 static CBlockIndex* pindexLastBest;
1265 int64_t nCurrentTime = GetTime();
1266 if (pindexBest != pindexLastBest)
1268 pindexLastBest = pindexBest;
1269 nLastUpdate = nCurrentTime;
1271 return (nCurrentTime - nLastUpdate < 10 &&
1272 pindexBest->GetBlockTime() < nCurrentTime - 24 * 60 * 60);
1275 void static InvalidChainFound(CBlockIndex* pindexNew)
1277 if (pindexNew->nChainTrust > nBestInvalidTrust)
1279 nBestInvalidTrust = pindexNew->nChainTrust;
1280 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1281 uiInterface.NotifyBlocksChanged();
1284 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1285 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1287 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1288 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1289 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1290 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1291 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1292 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1293 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1294 nBestBlockTrust.Get64(),
1295 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1299 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1301 nTime = max(GetBlockTime(), GetAdjustedTime());
1314 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1316 // Relinquish previous transactions' spent pointers
1319 BOOST_FOREACH(const CTxIn& txin, vin)
1321 COutPoint prevout = txin.prevout;
1323 // Get prev txindex from disk
1325 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1326 return error("DisconnectInputs() : ReadTxIndex failed");
1328 if (prevout.n >= txindex.vSpent.size())
1329 return error("DisconnectInputs() : prevout.n out of range");
1331 // Mark outpoint as not spent
1332 txindex.vSpent[prevout.n].SetNull();
1335 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1336 return error("DisconnectInputs() : UpdateTxIndex failed");
1340 // Remove transaction from index
1341 // This can fail if a duplicate of this transaction was in a chain that got
1342 // reorganized away. This is only possible if this transaction was completely
1343 // spent, so erasing it would be a no-op anyway.
1344 txdb.EraseTxIndex(*this);
1350 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1351 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1353 // FetchInputs can return false either because we just haven't seen some inputs
1354 // (in which case the transaction should be stored as an orphan)
1355 // or because the transaction is malformed (in which case the transaction should
1356 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1360 return true; // Coinbase transactions have no inputs to fetch.
1362 for (unsigned int i = 0; i < vin.size(); i++)
1364 COutPoint prevout = vin[i].prevout;
1365 if (inputsRet.count(prevout.hash))
1366 continue; // Got it already
1369 CTxIndex& txindex = inputsRet[prevout.hash].first;
1371 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1373 // Get txindex from current proposed changes
1374 txindex = mapTestPool.find(prevout.hash)->second;
1378 // Read txindex from txdb
1379 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1381 if (!fFound && (fBlock || fMiner))
1382 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());
1385 CTransaction& txPrev = inputsRet[prevout.hash].second;
1386 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1388 // Get prev tx from single transactions in memory
1391 if (!mempool.exists(prevout.hash))
1392 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());
1393 txPrev = mempool.lookup(prevout.hash);
1396 txindex.vSpent.resize(txPrev.vout.size());
1400 // Get prev tx from disk
1401 if (!txPrev.ReadFromDisk(txindex.pos))
1402 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1406 // Make sure all prevout.n indexes are valid:
1407 for (unsigned int i = 0; i < vin.size(); i++)
1409 const COutPoint prevout = vin[i].prevout;
1410 assert(inputsRet.count(prevout.hash) != 0);
1411 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1412 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1413 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1415 // Revisit this if/when transaction replacement is implemented and allows
1418 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()));
1425 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1427 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1428 if (mi == inputs.end())
1429 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1431 const CTransaction& txPrev = (mi->second).second;
1432 if (input.prevout.n >= txPrev.vout.size())
1433 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1435 return txPrev.vout[input.prevout.n];
1438 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1443 int64_t nResult = 0;
1444 for (unsigned int i = 0; i < vin.size(); i++)
1446 nResult += GetOutputFor(vin[i], inputs).nValue;
1452 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1457 unsigned int nSigOps = 0;
1458 for (unsigned int i = 0; i < vin.size(); i++)
1460 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1461 if (prevout.scriptPubKey.IsPayToScriptHash())
1462 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1467 bool CScriptCheck::operator()() const {
1468 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1469 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1470 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1474 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1476 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1479 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1480 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1482 // Take over previous transactions' spent pointers
1483 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1484 // fMiner is true when called from the internal bitcoin miner
1485 // ... both are false when called from CTransaction::AcceptToMemoryPool
1489 int64_t nValueIn = 0;
1491 for (unsigned int i = 0; i < vin.size(); i++)
1493 COutPoint prevout = vin[i].prevout;
1494 assert(inputs.count(prevout.hash) > 0);
1495 CTxIndex& txindex = inputs[prevout.hash].first;
1496 CTransaction& txPrev = inputs[prevout.hash].second;
1498 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1499 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()));
1501 // If prev is coinbase or coinstake, check that it's matured
1502 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1503 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1504 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1505 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1507 // ppcoin: check transaction timestamp
1508 if (txPrev.nTime > nTime)
1509 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1511 // Check for negative or overflow input values
1512 nValueIn += txPrev.vout[prevout.n].nValue;
1513 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1514 return DoS(100, error("ConnectInputs() : txin values out of range"));
1519 pvChecks->reserve(vin.size());
1521 // The first loop above does all the inexpensive checks.
1522 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1523 // Helps prevent CPU exhaustion attacks.
1524 for (unsigned int i = 0; i < vin.size(); i++)
1526 COutPoint prevout = vin[i].prevout;
1527 assert(inputs.count(prevout.hash) > 0);
1528 CTxIndex& txindex = inputs[prevout.hash].first;
1529 CTransaction& txPrev = inputs[prevout.hash].second;
1531 // Check for conflicts (double-spend)
1532 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1533 // for an attacker to attempt to split the network.
1534 if (!txindex.vSpent[prevout.n].IsNull())
1535 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());
1537 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1538 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1539 // still computed and checked, and any change will be caught at the next checkpoint.
1543 CScriptCheck check(txPrev, *this, i, flags, 0);
1546 pvChecks->push_back(CScriptCheck());
1547 check.swap(pvChecks->back());
1551 if (flags & STRICT_FLAGS)
1553 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1554 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1556 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1558 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1562 // Mark outpoints as spent
1563 txindex.vSpent[prevout.n] = posThisTx;
1566 if (fBlock || fMiner)
1568 mapTestPool[prevout.hash] = txindex;
1574 // ppcoin: coin stake tx earns reward instead of paying fee
1576 if (!GetCoinAge(txdb, nCoinAge))
1577 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1579 unsigned int nTxSize = (nTime > VALIDATION_SWITCH_TIME || fTestNet) ? GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION) : 0;
1581 int64_t nReward = GetValueOut() - nValueIn;
1582 int64_t nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1584 if (nReward > nCalculatedReward)
1585 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1589 if (nValueIn < GetValueOut())
1590 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1592 // Tally transaction fees
1593 int64_t nTxFee = nValueIn - GetValueOut();
1595 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1598 if (!MoneyRange(nFees))
1599 return DoS(100, error("ConnectInputs() : nFees out of range"));
1607 bool CTransaction::ClientConnectInputs()
1612 // Take over previous transactions' spent pointers
1615 int64_t nValueIn = 0;
1616 for (unsigned int i = 0; i < vin.size(); i++)
1618 // Get prev tx from single transactions in memory
1619 COutPoint prevout = vin[i].prevout;
1620 if (!mempool.exists(prevout.hash))
1622 CTransaction& txPrev = mempool.lookup(prevout.hash);
1624 if (prevout.n >= txPrev.vout.size())
1628 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1629 return error("ClientConnectInputs() : VerifySignature failed");
1631 ///// this is redundant with the mempool.mapNextTx stuff,
1632 ///// not sure which I want to get rid of
1633 ///// this has to go away now that posNext is gone
1634 // // Check for conflicts
1635 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1636 // return error("ConnectInputs() : prev tx already used");
1638 // // Flag outpoints as used
1639 // txPrev.vout[prevout.n].posNext = posThisTx;
1641 nValueIn += txPrev.vout[prevout.n].nValue;
1643 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1644 return error("ClientConnectInputs() : txin values out of range");
1646 if (GetValueOut() > nValueIn)
1656 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1658 // Disconnect in reverse order
1659 for (int i = vtx.size()-1; i >= 0; i--)
1660 if (!vtx[i].DisconnectInputs(txdb))
1663 // Update block index on disk without changing it in memory.
1664 // The memory index structure will be changed after the db commits.
1667 CDiskBlockIndex blockindexPrev(pindex->pprev);
1668 blockindexPrev.hashNext = 0;
1669 if (!txdb.WriteBlockIndex(blockindexPrev))
1670 return error("DisconnectBlock() : WriteBlockIndex failed");
1673 // ppcoin: clean up wallet after disconnecting coinstake
1674 BOOST_FOREACH(CTransaction& tx, vtx)
1675 SyncWithWallets(tx, this, false, false);
1680 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1682 void ThreadScriptCheck(void*) {
1683 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1684 RenameThread("novacoin-scriptch");
1685 scriptcheckqueue.Thread();
1686 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1689 void ThreadScriptCheckQuit() {
1690 scriptcheckqueue.Quit();
1693 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1695 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1696 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1699 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1700 // unless those are already completely spent.
1701 // If such overwrites are allowed, coinbases and transactions depending upon those
1702 // can be duplicated to remove the ability to spend the first instance -- even after
1703 // being sent to another address.
1704 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1705 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1706 // already refuses previously-known transaction ids entirely.
1707 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1708 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1709 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1710 // initial block download.
1711 bool fEnforceBIP30 = true; // Always active in NovaCoin
1712 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1714 //// issue here: it doesn't know the version
1715 unsigned int nTxPos;
1717 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1718 // 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
1721 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1723 map<uint256, CTxIndex> mapQueuedChanges;
1724 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1727 int64_t nValueIn = 0;
1728 int64_t nValueOut = 0;
1729 unsigned int nSigOps = 0;
1730 BOOST_FOREACH(CTransaction& tx, vtx)
1732 uint256 hashTx = tx.GetHash();
1734 if (fEnforceBIP30) {
1735 CTxIndex txindexOld;
1736 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1737 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1743 nSigOps += tx.GetLegacySigOpCount();
1744 if (nSigOps > MAX_BLOCK_SIGOPS)
1745 return DoS(100, error("ConnectBlock() : too many sigops"));
1747 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1749 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1751 MapPrevTx mapInputs;
1752 if (tx.IsCoinBase())
1753 nValueOut += tx.GetValueOut();
1757 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1760 // Add in sigops done by pay-to-script-hash inputs;
1761 // this is to prevent a "rogue miner" from creating
1762 // an incredibly-expensive-to-validate block.
1763 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1764 if (nSigOps > MAX_BLOCK_SIGOPS)
1765 return DoS(100, error("ConnectBlock() : too many sigops"));
1767 int64_t nTxValueIn = tx.GetValueIn(mapInputs);
1768 int64_t nTxValueOut = tx.GetValueOut();
1769 nValueIn += nTxValueIn;
1770 nValueOut += nTxValueOut;
1771 if (!tx.IsCoinStake())
1772 nFees += nTxValueIn - nTxValueOut;
1774 std::vector<CScriptCheck> vChecks;
1775 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, nScriptCheckThreads ? &vChecks : NULL))
1777 control.Add(vChecks);
1780 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1783 if (!control.Wait())
1784 return DoS(100, false);
1786 if (IsProofOfWork())
1788 int64_t nBlockReward = GetProofOfWorkReward(nBits, nFees);
1790 // Check coinbase reward
1791 if (vtx[0].GetValueOut() > nBlockReward)
1792 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1793 vtx[0].GetValueOut(),
1797 // track money supply and mint amount info
1798 pindex->nMint = nValueOut - nValueIn + nFees;
1799 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1800 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1801 return error("Connect() : WriteBlockIndex for pindex failed");
1803 // fees are not collected by proof-of-stake miners
1804 // fees are destroyed to compensate the entire network
1805 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1806 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
1811 // Write queued txindex changes
1812 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1814 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1815 return error("ConnectBlock() : UpdateTxIndex failed");
1818 // Update block index on disk without changing it in memory.
1819 // The memory index structure will be changed after the db commits.
1822 CDiskBlockIndex blockindexPrev(pindex->pprev);
1823 blockindexPrev.hashNext = pindex->GetBlockHash();
1824 if (!txdb.WriteBlockIndex(blockindexPrev))
1825 return error("ConnectBlock() : WriteBlockIndex failed");
1828 // Watch for transactions paying to me
1829 BOOST_FOREACH(CTransaction& tx, vtx)
1830 SyncWithWallets(tx, this, true);
1836 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1838 printf("REORGANIZE\n");
1841 CBlockIndex* pfork = pindexBest;
1842 CBlockIndex* plonger = pindexNew;
1843 while (pfork != plonger)
1845 while (plonger->nHeight > pfork->nHeight)
1846 if (!(plonger = plonger->pprev))
1847 return error("Reorganize() : plonger->pprev is null");
1848 if (pfork == plonger)
1850 if (!(pfork = pfork->pprev))
1851 return error("Reorganize() : pfork->pprev is null");
1854 // List of what to disconnect
1855 vector<CBlockIndex*> vDisconnect;
1856 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1857 vDisconnect.push_back(pindex);
1859 // List of what to connect
1860 vector<CBlockIndex*> vConnect;
1861 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1862 vConnect.push_back(pindex);
1863 reverse(vConnect.begin(), vConnect.end());
1865 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());
1866 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());
1868 // Disconnect shorter branch
1869 vector<CTransaction> vResurrect;
1870 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1873 if (!block.ReadFromDisk(pindex))
1874 return error("Reorganize() : ReadFromDisk for disconnect failed");
1875 if (!block.DisconnectBlock(txdb, pindex))
1876 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1878 // Queue memory transactions to resurrect
1879 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1880 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1881 vResurrect.push_back(tx);
1884 // Connect longer branch
1885 vector<CTransaction> vDelete;
1886 for (unsigned int i = 0; i < vConnect.size(); i++)
1888 CBlockIndex* pindex = vConnect[i];
1890 if (!block.ReadFromDisk(pindex))
1891 return error("Reorganize() : ReadFromDisk for connect failed");
1892 if (!block.ConnectBlock(txdb, pindex))
1895 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1898 // Queue memory transactions to delete
1899 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1900 vDelete.push_back(tx);
1902 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1903 return error("Reorganize() : WriteHashBestChain failed");
1905 // Make sure it's successfully written to disk before changing memory structure
1906 if (!txdb.TxnCommit())
1907 return error("Reorganize() : TxnCommit failed");
1909 // Disconnect shorter branch
1910 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1912 pindex->pprev->pnext = NULL;
1914 // Connect longer branch
1915 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1917 pindex->pprev->pnext = pindex;
1919 // Resurrect memory transactions that were in the disconnected branch
1920 BOOST_FOREACH(CTransaction& tx, vResurrect)
1921 tx.AcceptToMemoryPool(txdb, false);
1923 // Delete redundant memory transactions that are in the connected branch
1924 BOOST_FOREACH(CTransaction& tx, vDelete)
1927 printf("REORGANIZE: done\n");
1933 // Called from inside SetBestChain: attaches a block to the new best chain being built
1934 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1936 uint256 hash = GetHash();
1938 // Adding to current best branch
1939 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1942 InvalidChainFound(pindexNew);
1945 if (!txdb.TxnCommit())
1946 return error("SetBestChain() : TxnCommit failed");
1948 // Add to current best branch
1949 pindexNew->pprev->pnext = pindexNew;
1951 // Delete redundant memory transactions
1952 BOOST_FOREACH(CTransaction& tx, vtx)
1958 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1960 uint256 hash = GetHash();
1962 if (!txdb.TxnBegin())
1963 return error("SetBestChain() : TxnBegin failed");
1965 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1967 txdb.WriteHashBestChain(hash);
1968 if (!txdb.TxnCommit())
1969 return error("SetBestChain() : TxnCommit failed");
1970 pindexGenesisBlock = pindexNew;
1972 else if (hashPrevBlock == hashBestChain)
1974 if (!SetBestChainInner(txdb, pindexNew))
1975 return error("SetBestChain() : SetBestChainInner failed");
1979 // the first block in the new chain that will cause it to become the new best chain
1980 CBlockIndex *pindexIntermediate = pindexNew;
1982 // list of blocks that need to be connected afterwards
1983 std::vector<CBlockIndex*> vpindexSecondary;
1985 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1986 // Try to limit how much needs to be done inside
1987 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1989 vpindexSecondary.push_back(pindexIntermediate);
1990 pindexIntermediate = pindexIntermediate->pprev;
1993 if (!vpindexSecondary.empty())
1994 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
1996 // Switch to new best branch
1997 if (!Reorganize(txdb, pindexIntermediate))
2000 InvalidChainFound(pindexNew);
2001 return error("SetBestChain() : Reorganize failed");
2004 // Connect further blocks
2005 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
2008 if (!block.ReadFromDisk(pindex))
2010 printf("SetBestChain() : ReadFromDisk failed\n");
2013 if (!txdb.TxnBegin()) {
2014 printf("SetBestChain() : TxnBegin 2 failed\n");
2017 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
2018 if (!block.SetBestChainInner(txdb, pindex))
2023 // Update best block in wallet (so we can detect restored wallets)
2024 bool fIsInitialDownload = IsInitialBlockDownload();
2025 if (!fIsInitialDownload)
2027 const CBlockLocator locator(pindexNew);
2028 ::SetBestChain(locator);
2032 hashBestChain = hash;
2033 pindexBest = pindexNew;
2034 pblockindexFBBHLast = NULL;
2035 nBestHeight = pindexBest->nHeight;
2036 nBestChainTrust = pindexNew->nChainTrust;
2037 nTimeBestReceived = GetTime();
2038 nTransactionsUpdated++;
2040 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2042 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
2043 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2044 CBigNum(nBestChainTrust).ToString().c_str(),
2045 nBestBlockTrust.Get64(),
2046 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2048 // Check the version of the last 100 blocks to see if we need to upgrade:
2049 if (!fIsInitialDownload)
2052 const CBlockIndex* pindex = pindexBest;
2053 for (int i = 0; i < 100 && pindex != NULL; i++)
2055 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2057 pindex = pindex->pprev;
2060 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2061 if (nUpgraded > 100/2)
2062 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2063 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2066 std::string strCmd = GetArg("-blocknotify", "");
2068 if (!fIsInitialDownload && !strCmd.empty())
2070 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
2071 boost::thread t(runCommand, strCmd); // thread runs free
2077 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2078 // Only those coins meeting minimum age requirement counts. As those
2079 // transactions not in main chain are not currently indexed so we
2080 // might not find out about their coin age. Older transactions are
2081 // guaranteed to be in main chain by sync-checkpoint. This rule is
2082 // introduced to help nodes establish a consistent view of the coin
2083 // age (trust score) of competing branches.
2084 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2086 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2092 BOOST_FOREACH(const CTxIn& txin, vin)
2094 // First try finding the previous transaction in database
2095 CTransaction txPrev;
2097 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2098 continue; // previous transaction not in main chain
2099 if (nTime < txPrev.nTime)
2100 return false; // Transaction timestamp violation
2102 // Read block header
2104 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2105 return false; // unable to read block of previous transaction
2106 if (block.GetBlockTime() + nStakeMinAge > nTime)
2107 continue; // only count coins meeting min age requirement
2109 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
2110 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2112 if (fDebug && GetBoolArg("-printcoinage"))
2113 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2116 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
2117 if (fDebug && GetBoolArg("-printcoinage"))
2118 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2119 nCoinAge = bnCoinDay.getuint64();
2123 // ppcoin: total coin age spent in block, in the unit of coin-days.
2124 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2129 BOOST_FOREACH(const CTransaction& tx, vtx)
2131 uint64_t nTxCoinAge;
2132 if (tx.GetCoinAge(txdb, nTxCoinAge))
2133 nCoinAge += nTxCoinAge;
2138 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2140 if (fDebug && GetBoolArg("-printcoinage"))
2141 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2145 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2147 // Check for duplicate
2148 uint256 hash = GetHash();
2149 if (mapBlockIndex.count(hash))
2150 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2152 // Construct new block index object
2153 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
2155 return error("AddToBlockIndex() : new CBlockIndex failed");
2156 pindexNew->phashBlock = &hash;
2157 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2158 if (miPrev != mapBlockIndex.end())
2160 pindexNew->pprev = (*miPrev).second;
2161 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2164 // ppcoin: compute chain trust score
2165 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2167 // ppcoin: compute stake entropy bit for stake modifier
2168 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2169 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2171 // ppcoin: record proof-of-stake hash value
2172 if (pindexNew->IsProofOfStake())
2174 if (!mapProofOfStake.count(hash))
2175 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2176 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2179 // ppcoin: compute stake modifier
2180 uint64_t nStakeModifier = 0;
2181 bool fGeneratedStakeModifier = false;
2182 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2183 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2184 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2185 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2186 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2187 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2189 // Add to mapBlockIndex
2190 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2191 if (pindexNew->IsProofOfStake())
2192 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2193 pindexNew->phashBlock = &((*mi).first);
2195 // Write to disk block index
2197 if (!txdb.TxnBegin())
2199 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2200 if (!txdb.TxnCommit())
2204 if (pindexNew->nChainTrust > nBestChainTrust)
2205 if (!SetBestChain(txdb, pindexNew))
2208 if (pindexNew == pindexBest)
2210 // Notify UI to display prev block's coinbase if it was ours
2211 static uint256 hashPrevBestCoinBase;
2212 UpdatedTransaction(hashPrevBestCoinBase);
2213 hashPrevBestCoinBase = vtx[0].GetHash();
2216 static int8_t counter = 0;
2217 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2218 uiInterface.NotifyBlocksChanged();
2225 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2227 // These are checks that are independent of context
2228 // that can be verified before saving an orphan block.
2230 set<uint256> uniqueTx; // tx hashes
2231 unsigned int nSigOps = 0; // total sigops
2234 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2235 return DoS(100, error("CheckBlock() : size limits failed"));
2237 bool fProofOfStake = IsProofOfStake();
2239 // First transaction must be coinbase, the rest must not be
2240 if (!vtx[0].IsCoinBase())
2241 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2243 if (!vtx[0].CheckTransaction())
2244 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2246 uniqueTx.insert(vtx[0].GetHash());
2247 nSigOps += vtx[0].GetLegacySigOpCount();
2251 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2252 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2254 // nNonce must be zero for proof-of-stake blocks
2256 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2258 // Coinbase output should be empty if proof-of-stake block
2259 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2260 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2262 // Check coinstake timestamp
2263 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2264 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2266 // NovaCoin: check proof-of-stake block signature
2267 if (fCheckSig && !CheckBlockSignature())
2268 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2270 if (!vtx[1].CheckTransaction())
2271 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2273 uniqueTx.insert(vtx[1].GetHash());
2274 nSigOps += vtx[1].GetLegacySigOpCount();
2278 // Check proof of work matches claimed amount
2279 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2280 return DoS(50, error("CheckBlock() : proof of work failed"));
2283 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2284 return error("CheckBlock() : block timestamp too far in the future");
2286 // Check coinbase timestamp
2287 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2288 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2291 // Iterate all transactions starting from second for proof-of-stake block
2292 // or first for proof-of-work block
2293 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2295 const CTransaction& tx = vtx[i];
2297 // Reject coinbase transactions at non-zero index
2298 if (tx.IsCoinBase())
2299 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2301 // Reject coinstake transactions at index != 1
2302 if (tx.IsCoinStake())
2303 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2305 // Check transaction timestamp
2306 if (GetBlockTime() < (int64_t)tx.nTime)
2307 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2309 // Check transaction consistency
2310 if (!tx.CheckTransaction())
2311 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2313 // Add transaction hash into list of unique transaction IDs
2314 uniqueTx.insert(tx.GetHash());
2316 // Calculate sigops count
2317 nSigOps += tx.GetLegacySigOpCount();
2320 // Check for duplicate txids. This is caught by ConnectInputs(),
2321 // but catching it earlier avoids a potential DoS attack:
2322 if (uniqueTx.size() != vtx.size())
2323 return DoS(100, error("CheckBlock() : duplicate transaction"));
2325 // Reject block if validation would consume too much resources.
2326 if (nSigOps > MAX_BLOCK_SIGOPS)
2327 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2329 // Check merkle root
2330 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2331 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2336 bool CBlock::AcceptBlock()
2338 // Check for duplicate
2339 uint256 hash = GetHash();
2340 if (mapBlockIndex.count(hash))
2341 return error("AcceptBlock() : block already in mapBlockIndex");
2343 // Get prev block index
2344 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2345 if (mi == mapBlockIndex.end())
2346 return DoS(10, error("AcceptBlock() : prev block not found"));
2347 CBlockIndex* pindexPrev = (*mi).second;
2348 int nHeight = pindexPrev->nHeight+1;
2350 // Check proof-of-work or proof-of-stake
2351 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2352 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2354 // Check timestamp against prev
2355 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2356 return error("AcceptBlock() : block's timestamp is too early");
2358 // Check that all transactions are finalized
2359 BOOST_FOREACH(const CTransaction& tx, vtx)
2360 if (!tx.IsFinal(nHeight, GetBlockTime()))
2361 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2363 // Check that the block chain matches the known block chain up to a checkpoint
2364 if (!Checkpoints::CheckHardened(nHeight, hash))
2365 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2367 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2369 // Check that the block satisfies synchronized checkpoint
2370 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2371 return error("AcceptBlock() : rejected by synchronized checkpoint");
2373 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2374 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2376 // Enforce rule that the coinbase starts with serialized block height
2377 CScript expect = CScript() << nHeight;
2378 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2379 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2380 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2382 // Write block to history file
2383 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2384 return error("AcceptBlock() : out of disk space");
2385 unsigned int nFile = std::numeric_limits<unsigned int>::max();
2386 unsigned int nBlockPos = 0;
2387 if (!WriteToDisk(nFile, nBlockPos))
2388 return error("AcceptBlock() : WriteToDisk failed");
2389 if (!AddToBlockIndex(nFile, nBlockPos))
2390 return error("AcceptBlock() : AddToBlockIndex failed");
2392 // Relay inventory, but don't relay old inventory during initial block download
2393 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2394 if (hashBestChain == hash)
2397 BOOST_FOREACH(CNode* pnode, vNodes)
2398 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2399 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2402 // ppcoin: check pending sync-checkpoint
2403 Checkpoints::AcceptPendingSyncCheckpoint();
2408 uint256 CBlockIndex::GetBlockTrust() const
2411 bnTarget.SetCompact(nBits);
2417 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2418 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2422 // Calculate work amount for block
2423 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2425 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2426 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2428 // Return nPoWTrust for the first 12 blocks
2429 if (pprev == NULL || pprev->nHeight < 12)
2432 const CBlockIndex* currentIndex = pprev;
2434 if(IsProofOfStake())
2436 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2438 // Return 1/3 of score if parent block is not the PoW block
2439 if (!pprev->IsProofOfWork())
2440 return (bnNewTrust / 3).getuint256();
2444 // Check last 12 blocks type
2445 while (pprev->nHeight - currentIndex->nHeight < 12)
2447 if (currentIndex->IsProofOfWork())
2449 currentIndex = currentIndex->pprev;
2452 // Return 1/3 of score if less than 3 PoW blocks found
2454 return (bnNewTrust / 3).getuint256();
2456 return bnNewTrust.getuint256();
2460 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2462 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2463 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2464 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2468 // Check last 12 blocks type
2469 while (pprev->nHeight - currentIndex->nHeight < 12)
2471 if (currentIndex->IsProofOfStake())
2473 currentIndex = currentIndex->pprev;
2476 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2478 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2480 bnTarget.SetCompact(pprev->nBits);
2485 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2487 // Return nPoWTrust + full trust score for previous block nBits
2488 return nPoWTrust + bnNewTrust.getuint256();
2492 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2494 unsigned int nFound = 0;
2495 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2497 if (pstart->nVersion >= minVersion)
2499 pstart = pstart->pprev;
2501 return (nFound >= nRequired);
2504 bool static ReserealizeBlockSignature(CBlock* pblock)
2506 if (pblock->IsProofOfWork())
2508 pblock->vchBlockSig.clear();
2512 return CKey::ReserealizeSignature(pblock->vchBlockSig);
2515 bool static IsCanonicalBlockSignature(CBlock* pblock)
2517 if (pblock->IsProofOfWork())
2518 return pblock->vchBlockSig.empty();
2520 return IsDERSignature(pblock->vchBlockSig);
2523 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2525 // Check for duplicate
2526 uint256 hash = pblock->GetHash();
2527 if (mapBlockIndex.count(hash))
2528 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2529 if (mapOrphanBlocks.count(hash))
2530 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2532 // Check proof-of-stake
2533 // Limited duplicity on stake: prevents block flood attack
2534 // Duplicate stake allowed only when there is orphan child block
2535 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2536 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());
2538 // Strip the garbage from newly received blocks, if we found some
2539 if (!IsCanonicalBlockSignature(pblock)) {
2540 if (!ReserealizeBlockSignature(pblock))
2541 printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2544 // Preliminary checks
2545 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2546 return error("ProcessBlock() : CheckBlock FAILED");
2548 // ppcoin: verify hash target and signature of coinstake tx
2549 if (pblock->IsProofOfStake())
2551 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2552 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2554 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2555 return false; // do not error here as we expect this during initial block download
2557 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2558 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2561 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2562 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2564 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2565 int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2567 bnNewBlock.SetCompact(pblock->nBits);
2570 if (pblock->IsProofOfStake())
2571 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2573 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2575 if (bnNewBlock > bnRequired)
2578 pfrom->Misbehaving(100);
2579 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2583 // ppcoin: ask for pending sync-checkpoint if any
2584 if (!IsInitialBlockDownload())
2585 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2587 // If don't already have its previous block, shunt it off to holding area until we get it
2588 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2590 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2591 // ppcoin: check proof-of-stake
2592 if (pblock->IsProofOfStake())
2594 // Limited duplicity on stake: prevents block flood attack
2595 // Duplicate stake allowed only when there is orphan child block
2596 if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2597 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
2599 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2601 CBlock* pblock2 = new CBlock(*pblock);
2602 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2603 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2605 // Ask this guy to fill in what we're missing
2608 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2609 // ppcoin: getblocks may not obtain the ancestor block rejected
2610 // earlier by duplicate-stake check so we ask for it again directly
2611 if (!IsInitialBlockDownload())
2612 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2618 if (!pblock->AcceptBlock())
2619 return error("ProcessBlock() : AcceptBlock FAILED");
2621 // Recursively process any orphan blocks that depended on this one
2622 vector<uint256> vWorkQueue;
2623 vWorkQueue.push_back(hash);
2624 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2626 uint256 hashPrev = vWorkQueue[i];
2627 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2628 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2631 CBlock* pblockOrphan = (*mi).second;
2632 if (pblockOrphan->AcceptBlock())
2633 vWorkQueue.push_back(pblockOrphan->GetHash());
2634 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2635 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2636 delete pblockOrphan;
2638 mapOrphanBlocksByPrev.erase(hashPrev);
2641 printf("ProcessBlock: ACCEPTED\n");
2643 // ppcoin: if responsible for sync-checkpoint send it
2644 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2645 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2650 // ppcoin: check block signature
2651 bool CBlock::CheckBlockSignature() const
2653 if (vchBlockSig.empty())
2656 txnouttype whichType;
2657 vector<valtype> vSolutions;
2658 if (!Solver(vtx[1].vout[1].scriptPubKey, whichType, vSolutions))
2661 if (whichType == TX_PUBKEY)
2663 valtype& vchPubKey = vSolutions[0];
2665 if (!key.SetPubKey(vchPubKey))
2667 return key.Verify(GetHash(), vchBlockSig);
2673 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2675 uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2677 // Check for nMinDiskSpace bytes (currently 50MB)
2678 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2681 string strMessage = _("Warning: Disk space is low!");
2682 strMiscWarning = strMessage;
2683 printf("*** %s\n", strMessage.c_str());
2684 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2691 static filesystem::path BlockFilePath(unsigned int nFile)
2693 string strBlockFn = strprintf("blk%04u.dat", nFile);
2694 return GetDataDir() / strBlockFn;
2697 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2699 if ((nFile < 1) || (nFile == (unsigned int) -1))
2701 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2704 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2706 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2715 static unsigned int nCurrentBlockFile = 1;
2717 FILE* AppendBlockFile(unsigned int& nFileRet)
2722 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2725 if (fseek(file, 0, SEEK_END) != 0)
2727 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2728 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2730 nFileRet = nCurrentBlockFile;
2734 nCurrentBlockFile++;
2738 void UnloadBlockIndex()
2740 mapBlockIndex.clear();
2741 setStakeSeen.clear();
2742 pindexGenesisBlock = NULL;
2744 nBestChainTrust = 0;
2745 nBestInvalidTrust = 0;
2750 bool LoadBlockIndex(bool fAllowNew)
2754 pchMessageStart[0] = 0xcd;
2755 pchMessageStart[1] = 0xf2;
2756 pchMessageStart[2] = 0xc0;
2757 pchMessageStart[3] = 0xef;
2759 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2760 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2761 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2762 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2763 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2770 if (!txdb.LoadBlockIndex())
2774 // Init with genesis block
2776 if (mapBlockIndex.empty())
2785 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2786 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2787 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2789 // vMerkleTree: 4cb33b3b6a
2793 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2794 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2795 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2797 // vMerkleTree: 4cb33b3b6a
2799 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2801 txNew.nTime = 1360105017;
2802 txNew.vin.resize(1);
2803 txNew.vout.resize(1);
2804 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2805 txNew.vout[0].SetEmpty();
2807 block.vtx.push_back(txNew);
2808 block.hashPrevBlock = 0;
2809 block.hashMerkleRoot = block.BuildMerkleTree();
2811 block.nTime = 1360105017;
2812 block.nBits = bnProofOfWorkLimit.GetCompact();
2813 block.nNonce = !fTestNet ? 1575379 : 46534;
2816 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2818 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2819 assert(block.CheckBlock());
2821 // Start new block file
2823 unsigned int nBlockPos;
2824 if (!block.WriteToDisk(nFile, nBlockPos))
2825 return error("LoadBlockIndex() : writing genesis block to disk failed");
2826 if (!block.AddToBlockIndex(nFile, nBlockPos))
2827 return error("LoadBlockIndex() : genesis block not accepted");
2829 // initialize synchronized checkpoint
2830 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2831 return error("LoadBlockIndex() : failed to init sync checkpoint");
2833 // upgrade time set to zero if txdb initialized
2835 if (!txdb.WriteModifierUpgradeTime(0))
2836 return error("LoadBlockIndex() : failed to init upgrade info");
2837 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2843 string strPubKey = "";
2844 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2846 // write checkpoint master key to db
2848 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2849 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2850 if (!txdb.TxnCommit())
2851 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2852 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2853 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2856 // upgrade time set to zero if blocktreedb initialized
2857 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2859 if (nModifierUpgradeTime)
2860 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2862 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2866 nModifierUpgradeTime = GetTime();
2867 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2868 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2869 return error("LoadBlockIndex() : failed to write upgrade info");
2882 void PrintBlockTree()
2884 // pre-compute tree structure
2885 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2886 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2888 CBlockIndex* pindex = (*mi).second;
2889 mapNext[pindex->pprev].push_back(pindex);
2891 //while (rand() % 3 == 0)
2892 // mapNext[pindex->pprev].push_back(pindex);
2895 vector<pair<int, CBlockIndex*> > vStack;
2896 vStack.push_back(make_pair(0, pindexGenesisBlock));
2899 while (!vStack.empty())
2901 int nCol = vStack.back().first;
2902 CBlockIndex* pindex = vStack.back().second;
2905 // print split or gap
2906 if (nCol > nPrevCol)
2908 for (int i = 0; i < nCol-1; i++)
2912 else if (nCol < nPrevCol)
2914 for (int i = 0; i < nCol; i++)
2921 for (int i = 0; i < nCol; i++)
2926 block.ReadFromDisk(pindex);
2927 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
2931 block.GetHash().ToString().c_str(),
2933 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2934 FormatMoney(pindex->nMint).c_str(),
2937 PrintWallets(block);
2939 // put the main time-chain first
2940 vector<CBlockIndex*>& vNext = mapNext[pindex];
2941 for (unsigned int i = 0; i < vNext.size(); i++)
2943 if (vNext[i]->pnext)
2945 swap(vNext[0], vNext[i]);
2951 for (unsigned int i = 0; i < vNext.size(); i++)
2952 vStack.push_back(make_pair(nCol+i, vNext[i]));
2956 bool LoadExternalBlockFile(FILE* fileIn)
2958 int64_t nStart = GetTimeMillis();
2964 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2965 unsigned int nPos = 0;
2966 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2968 unsigned char pchData[65536];
2970 fseek(blkdat, nPos, SEEK_SET);
2971 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2974 nPos = (unsigned int)-1;
2977 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2980 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2982 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2985 nPos += ((unsigned char*)nFind - pchData) + 1;
2988 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2989 } while(!fRequestShutdown);
2990 if (nPos == (unsigned int)-1)
2992 fseek(blkdat, nPos, SEEK_SET);
2995 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2999 if (ProcessBlock(NULL,&block))
3007 catch (const std::exception&) {
3008 printf("%s() : Deserialize or I/O error caught during load\n",
3009 BOOST_CURRENT_FUNCTION);
3012 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3016 //////////////////////////////////////////////////////////////////////////////
3021 extern map<uint256, CAlert> mapAlerts;
3022 extern CCriticalSection cs_mapAlerts;
3024 string GetWarnings(string strFor)
3027 string strStatusBar;
3030 if (GetBoolArg("-testsafemode"))
3033 // Misc warnings like out of disk space and clock is wrong
3034 if (strMiscWarning != "")
3037 strStatusBar = strMiscWarning;
3040 // if detected unmet upgrade requirement enter safe mode
3041 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3042 if (IsFixedModifierInterval(nModifierUpgradeTime + 60*60*24)) // 1 day margin
3045 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3048 // if detected invalid checkpoint enter safe mode
3049 if (Checkpoints::hashInvalidCheckpoint != 0)
3052 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3058 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3060 const CAlert& alert = item.second;
3061 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3063 nPriority = alert.nPriority;
3064 strStatusBar = alert.strStatusBar;
3065 if (nPriority > 1000)
3066 strRPC = strStatusBar;
3071 if (strFor == "statusbar")
3072 return strStatusBar;
3073 else if (strFor == "rpc")
3075 assert(!"GetWarnings() : invalid parameter");
3086 //////////////////////////////////////////////////////////////////////////////
3092 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3098 bool txInMap = false;
3101 txInMap = (mempool.exists(inv.hash));
3104 mapOrphanTransactions.count(inv.hash) ||
3105 txdb.ContainsTx(inv.hash);
3109 return mapBlockIndex.count(inv.hash) ||
3110 mapOrphanBlocks.count(inv.hash);
3112 // Don't know what it is, just say we already got one
3119 // The message start string is designed to be unlikely to occur in normal data.
3120 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3121 // a large 4-byte int at any alignment.
3122 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3124 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3126 static map<CService, CPubKey> mapReuseKey;
3127 RandAddSeedPerfmon();
3129 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3130 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3132 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3136 if (strCommand == "version")
3138 // Each connection can only send one version message
3139 if (pfrom->nVersion != 0)
3141 pfrom->Misbehaving(1);
3148 uint64_t nNonce = 1;
3149 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3150 if (pfrom->nVersion < MIN_PROTO_VERSION)
3152 // Since February 20, 2012, the protocol is initiated at version 209,
3153 // and earlier versions are no longer supported
3154 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3155 pfrom->fDisconnect = true;
3159 if (pfrom->nVersion == 10300)
3160 pfrom->nVersion = 300;
3162 vRecv >> addrFrom >> nNonce;
3164 vRecv >> pfrom->strSubVer;
3166 vRecv >> pfrom->nStartingHeight;
3168 if (pfrom->fInbound && addrMe.IsRoutable())
3170 pfrom->addrLocal = addrMe;
3174 // Disconnect if we connected to ourself
3175 if (nNonce == nLocalHostNonce && nNonce > 1)
3177 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3178 pfrom->fDisconnect = true;
3182 if (pfrom->nVersion < 60010)
3184 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3185 pfrom->fDisconnect = true;
3189 // record my external IP reported by peer
3190 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3191 addrSeenByPeer = addrMe;
3193 // Be shy and don't send version until we hear
3194 if (pfrom->fInbound)
3195 pfrom->PushVersion();
3197 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3199 AddTimeData(pfrom->addr, nTime);
3202 pfrom->PushMessage("verack");
3203 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3205 if (!pfrom->fInbound)
3207 // Advertise our address
3208 if (!fNoListen && !IsInitialBlockDownload())
3210 CAddress addr = GetLocalAddress(&pfrom->addr);
3211 if (addr.IsRoutable())
3212 pfrom->PushAddress(addr);
3215 // Get recent addresses
3216 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3218 pfrom->PushMessage("getaddr");
3219 pfrom->fGetAddr = true;
3221 addrman.Good(pfrom->addr);
3223 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3225 addrman.Add(addrFrom, addrFrom);
3226 addrman.Good(addrFrom);
3230 // Ask the first connected node for block updates
3231 static int nAskedForBlocks = 0;
3232 if (!pfrom->fClient && !pfrom->fOneShot &&
3233 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3234 (pfrom->nVersion < NOBLKS_VERSION_START ||
3235 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3236 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3239 pfrom->PushGetBlocks(pindexBest, uint256(0));
3245 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3246 item.second.RelayTo(pfrom);
3249 // Relay sync-checkpoint
3251 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3252 if (!Checkpoints::checkpointMessage.IsNull())
3253 Checkpoints::checkpointMessage.RelayTo(pfrom);
3256 pfrom->fSuccessfullyConnected = true;
3258 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());
3260 cPeerBlockCounts.input(pfrom->nStartingHeight);
3262 // ppcoin: ask for pending sync-checkpoint if any
3263 if (!IsInitialBlockDownload())
3264 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3268 else if (pfrom->nVersion == 0)
3270 // Must have a version message before anything else
3271 pfrom->Misbehaving(1);
3276 else if (strCommand == "verack")
3278 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3282 else if (strCommand == "addr")
3284 vector<CAddress> vAddr;
3287 // Don't want addr from older versions unless seeding
3288 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3290 if (vAddr.size() > 1000)
3292 pfrom->Misbehaving(20);
3293 return error("message addr size() = %" PRIszu "", vAddr.size());
3296 // Store the new addresses
3297 vector<CAddress> vAddrOk;
3298 int64_t nNow = GetAdjustedTime();
3299 int64_t nSince = nNow - 10 * 60;
3300 BOOST_FOREACH(CAddress& addr, vAddr)
3304 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3305 addr.nTime = nNow - 5 * 24 * 60 * 60;
3306 pfrom->AddAddressKnown(addr);
3307 bool fReachable = IsReachable(addr);
3308 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3310 // Relay to a limited number of other nodes
3313 // Use deterministic randomness to send to the same nodes for 24 hours
3314 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3315 static uint256 hashSalt;
3317 hashSalt = GetRandHash();
3318 uint64_t hashAddr = addr.GetHash();
3319 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3320 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3321 multimap<uint256, CNode*> mapMix;
3322 BOOST_FOREACH(CNode* pnode, vNodes)
3324 if (pnode->nVersion < CADDR_TIME_VERSION)
3326 unsigned int nPointer;
3327 memcpy(&nPointer, &pnode, sizeof(nPointer));
3328 uint256 hashKey = hashRand ^ nPointer;
3329 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3330 mapMix.insert(make_pair(hashKey, pnode));
3332 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3333 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3334 ((*mi).second)->PushAddress(addr);
3337 // Do not store addresses outside our network
3339 vAddrOk.push_back(addr);
3341 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3342 if (vAddr.size() < 1000)
3343 pfrom->fGetAddr = false;
3344 if (pfrom->fOneShot)
3345 pfrom->fDisconnect = true;
3348 else if (strCommand == "inv")
3352 if (vInv.size() > MAX_INV_SZ)
3354 pfrom->Misbehaving(20);
3355 return error("message inv size() = %" PRIszu "", vInv.size());
3358 // find last block in inv vector
3359 unsigned int nLastBlock = (unsigned int)(-1);
3360 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3361 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3362 nLastBlock = vInv.size() - 1 - nInv;
3367 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3369 const CInv &inv = vInv[nInv];
3373 pfrom->AddInventoryKnown(inv);
3375 bool fAlreadyHave = AlreadyHave(txdb, inv);
3377 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3381 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3382 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3383 } else if (nInv == nLastBlock) {
3384 // In case we are on a very long side-chain, it is possible that we already have
3385 // the last block in an inv bundle sent in response to getblocks. Try to detect
3386 // this situation and push another getblocks to continue.
3387 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3389 printf("force request: %s\n", inv.ToString().c_str());
3392 // Track requests for our stuff
3393 Inventory(inv.hash);
3398 else if (strCommand == "getdata")
3402 if (vInv.size() > MAX_INV_SZ)
3404 pfrom->Misbehaving(20);
3405 return error("message getdata size() = %" PRIszu "", vInv.size());
3408 if (fDebugNet || (vInv.size() != 1))
3409 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3411 BOOST_FOREACH(const CInv& inv, vInv)
3415 if (fDebugNet || (vInv.size() == 1))
3416 printf("received getdata for: %s\n", inv.ToString().c_str());
3418 if (inv.type == MSG_BLOCK)
3420 // Send block from disk
3421 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3422 if (mi != mapBlockIndex.end())
3425 block.ReadFromDisk((*mi).second);
3426 pfrom->PushMessage("block", block);
3428 // Trigger them to send a getblocks request for the next batch of inventory
3429 if (inv.hash == pfrom->hashContinue)
3431 // ppcoin: send latest proof-of-work block to allow the
3432 // download node to accept as orphan (proof-of-stake
3433 // block might be rejected by stake connection check)
3435 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3436 pfrom->PushMessage("inv", vInv);
3437 pfrom->hashContinue = 0;
3441 else if (inv.IsKnownType())
3443 // Send stream from relay memory
3444 bool pushed = false;
3447 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3448 if (mi != mapRelay.end()) {
3449 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3453 if (!pushed && inv.type == MSG_TX) {
3455 if (mempool.exists(inv.hash)) {
3456 CTransaction tx = mempool.lookup(inv.hash);
3457 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3460 pfrom->PushMessage("tx", ss);
3465 // Track requests for our stuff
3466 Inventory(inv.hash);
3471 else if (strCommand == "getblocks")
3473 CBlockLocator locator;
3475 vRecv >> locator >> hashStop;
3477 // Find the last block the caller has in the main chain
3478 CBlockIndex* pindex = locator.GetBlockIndex();
3480 // Send the rest of the chain
3482 pindex = pindex->pnext;
3484 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3485 for (; pindex; pindex = pindex->pnext)
3487 if (pindex->GetBlockHash() == hashStop)
3489 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3490 // ppcoin: tell downloading node about the latest block if it's
3491 // without risk being rejected due to stake connection check
3492 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3493 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3496 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3499 // When this block is requested, we'll send an inv that'll make them
3500 // getblocks the next batch of inventory.
3501 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3502 pfrom->hashContinue = pindex->GetBlockHash();
3507 else if (strCommand == "checkpoint")
3509 CSyncCheckpoint checkpoint;
3510 vRecv >> checkpoint;
3512 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3515 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3517 BOOST_FOREACH(CNode* pnode, vNodes)
3518 checkpoint.RelayTo(pnode);
3522 else if (strCommand == "getheaders")
3524 CBlockLocator locator;
3526 vRecv >> locator >> hashStop;
3528 CBlockIndex* pindex = NULL;
3529 if (locator.IsNull())
3531 // If locator is null, return the hashStop block
3532 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3533 if (mi == mapBlockIndex.end())
3535 pindex = (*mi).second;
3539 // Find the last block the caller has in the main chain
3540 pindex = locator.GetBlockIndex();
3542 pindex = pindex->pnext;
3545 vector<CBlock> vHeaders;
3547 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3548 for (; pindex; pindex = pindex->pnext)
3550 vHeaders.push_back(pindex->GetBlockHeader());
3551 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3554 pfrom->PushMessage("headers", vHeaders);
3558 else if (strCommand == "tx")
3560 vector<uint256> vWorkQueue;
3561 vector<uint256> vEraseQueue;
3562 CDataStream vMsg(vRecv);
3567 CInv inv(MSG_TX, tx.GetHash());
3568 pfrom->AddInventoryKnown(inv);
3570 bool fMissingInputs = false;
3571 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3573 SyncWithWallets(tx, NULL, true);
3574 RelayTransaction(tx, inv.hash);
3575 mapAlreadyAskedFor.erase(inv);
3576 vWorkQueue.push_back(inv.hash);
3577 vEraseQueue.push_back(inv.hash);
3579 // Recursively process any orphan transactions that depended on this one
3580 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3582 uint256 hashPrev = vWorkQueue[i];
3583 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3584 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3587 const uint256& orphanTxHash = *mi;
3588 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3589 bool fMissingInputs2 = false;
3591 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3593 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3594 SyncWithWallets(tx, NULL, true);
3595 RelayTransaction(orphanTx, orphanTxHash);
3596 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3597 vWorkQueue.push_back(orphanTxHash);
3598 vEraseQueue.push_back(orphanTxHash);
3600 else if (!fMissingInputs2)
3603 vEraseQueue.push_back(orphanTxHash);
3604 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3609 BOOST_FOREACH(uint256 hash, vEraseQueue)
3610 EraseOrphanTx(hash);
3612 else if (fMissingInputs)
3616 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3617 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3619 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3621 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3625 else if (strCommand == "block")
3629 uint256 hashBlock = block.GetHash();
3631 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3634 CInv inv(MSG_BLOCK, hashBlock);
3635 pfrom->AddInventoryKnown(inv);
3637 if (ProcessBlock(pfrom, &block))
3638 mapAlreadyAskedFor.erase(inv);
3639 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3643 else if (strCommand == "getaddr")
3645 // Don't return addresses older than nCutOff timestamp
3646 int64_t nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3647 pfrom->vAddrToSend.clear();
3648 vector<CAddress> vAddr = addrman.GetAddr();
3649 BOOST_FOREACH(const CAddress &addr, vAddr)
3650 if(addr.nTime > nCutOff)
3651 pfrom->PushAddress(addr);
3655 else if (strCommand == "mempool")
3657 std::vector<uint256> vtxid;
3658 mempool.queryHashes(vtxid);
3660 for (unsigned int i = 0; i < vtxid.size(); i++) {
3661 CInv inv(MSG_TX, vtxid[i]);
3662 vInv.push_back(inv);
3663 if (i == (MAX_INV_SZ - 1))
3666 if (vInv.size() > 0)
3667 pfrom->PushMessage("inv", vInv);
3671 else if (strCommand == "checkorder")
3676 if (!GetBoolArg("-allowreceivebyip"))
3678 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3685 /// we have a chance to check the order here
3687 // Keep giving the same key to the same ip until they use it
3688 if (!mapReuseKey.count(pfrom->addr))
3689 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3691 // Send back approval of order and pubkey to use
3692 CScript scriptPubKey;
3693 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3694 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3698 else if (strCommand == "reply")
3703 CRequestTracker tracker;
3705 LOCK(pfrom->cs_mapRequests);
3706 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3707 if (mi != pfrom->mapRequests.end())
3709 tracker = (*mi).second;
3710 pfrom->mapRequests.erase(mi);
3713 if (!tracker.IsNull())
3714 tracker.fn(tracker.param1, vRecv);
3718 else if (strCommand == "ping")
3720 if (pfrom->nVersion > BIP0031_VERSION)
3724 // Echo the message back with the nonce. This allows for two useful features:
3726 // 1) A remote node can quickly check if the connection is operational
3727 // 2) Remote nodes can measure the latency of the network thread. If this node
3728 // is overloaded it won't respond to pings quickly and the remote node can
3729 // avoid sending us more work, like chain download requests.
3731 // The nonce stops the remote getting confused between different pings: without
3732 // it, if the remote node sends a ping once per second and this node takes 5
3733 // seconds to respond to each, the 5th ping the remote sends would appear to
3734 // return very quickly.
3735 pfrom->PushMessage("pong", nonce);
3740 else if (strCommand == "alert")
3745 uint256 alertHash = alert.GetHash();
3746 if (pfrom->setKnown.count(alertHash) == 0)
3748 if (alert.ProcessAlert())
3751 pfrom->setKnown.insert(alertHash);
3754 BOOST_FOREACH(CNode* pnode, vNodes)
3755 alert.RelayTo(pnode);
3759 // Small DoS penalty so peers that send us lots of
3760 // duplicate/expired/invalid-signature/whatever alerts
3761 // eventually get banned.
3762 // This isn't a Misbehaving(100) (immediate ban) because the
3763 // peer might be an older or different implementation with
3764 // a different signature key, etc.
3765 pfrom->Misbehaving(10);
3773 // Ignore unknown commands for extensibility
3777 // Update the last seen time for this node's address
3778 if (pfrom->fNetworkNode)
3779 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3780 AddressCurrentlyConnected(pfrom->addr);
3786 bool ProcessMessages(CNode* pfrom)
3788 CDataStream& vRecv = pfrom->vRecv;
3792 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3796 // (4) message start
3805 // Don't bother if send buffer is too full to respond anyway
3806 if (pfrom->vSend.size() >= SendBufferSize())
3809 // Scan for message start
3810 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3811 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3812 if (vRecv.end() - pstart < nHeaderSize)
3814 if ((int)vRecv.size() > nHeaderSize)
3816 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3817 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3821 if (pstart - vRecv.begin() > 0)
3822 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
3823 vRecv.erase(vRecv.begin(), pstart);
3826 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3831 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3834 string strCommand = hdr.GetCommand();
3837 unsigned int nMessageSize = hdr.nMessageSize;
3838 if (nMessageSize > MAX_SIZE)
3840 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3843 if (nMessageSize > vRecv.size())
3845 // Rewind and wait for rest of message
3846 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3851 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3852 unsigned int nChecksum = 0;
3853 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3854 if (nChecksum != hdr.nChecksum)
3856 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3857 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3861 // Copy message to its own buffer
3862 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3863 vRecv.ignore(nMessageSize);
3871 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3876 catch (std::ios_base::failure& e)
3878 if (strstr(e.what(), "end of data"))
3880 // Allow exceptions from under-length message on vRecv
3881 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());
3883 else if (strstr(e.what(), "size too large"))
3885 // Allow exceptions from over-long size
3886 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3890 PrintExceptionContinue(&e, "ProcessMessages()");
3893 catch (std::exception& e) {
3894 PrintExceptionContinue(&e, "ProcessMessages()");
3896 PrintExceptionContinue(NULL, "ProcessMessages()");
3900 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3908 bool SendMessages(CNode* pto, bool fSendTrickle)
3910 TRY_LOCK(cs_main, lockMain);
3912 // Don't send anything until we get their version message
3913 if (pto->nVersion == 0)
3916 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3918 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
3920 if (pto->nVersion > BIP0031_VERSION)
3921 pto->PushMessage("ping", nonce);
3923 pto->PushMessage("ping");
3927 if (pto->fStartSync) {
3928 pto->fStartSync = false;
3929 pto->PushGetBlocks(pindexBest, uint256(0));
3932 // Resend wallet transactions that haven't gotten in a block yet
3933 ResendWalletTransactions();
3935 // Address refresh broadcast
3936 static int64_t nLastRebroadcast;
3937 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > nBroadcastInterval))
3941 BOOST_FOREACH(CNode* pnode, vNodes)
3943 // Periodically clear setAddrKnown to allow refresh broadcasts
3944 if (nLastRebroadcast)
3945 pnode->setAddrKnown.clear();
3947 // Rebroadcast our address
3950 CAddress addr = GetLocalAddress(&pnode->addr);
3951 if (addr.IsRoutable())
3952 pnode->PushAddress(addr);
3956 nLastRebroadcast = GetTime();
3964 vector<CAddress> vAddr;
3965 vAddr.reserve(pto->vAddrToSend.size());
3966 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3968 // returns true if wasn't already contained in the set
3969 if (pto->setAddrKnown.insert(addr).second)
3971 vAddr.push_back(addr);
3972 // receiver rejects addr messages larger than 1000
3973 if (vAddr.size() >= 1000)
3975 pto->PushMessage("addr", vAddr);
3980 pto->vAddrToSend.clear();
3982 pto->PushMessage("addr", vAddr);
3987 // Message: inventory
3990 vector<CInv> vInvWait;
3992 LOCK(pto->cs_inventory);
3993 vInv.reserve(pto->vInventoryToSend.size());
3994 vInvWait.reserve(pto->vInventoryToSend.size());
3995 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3997 if (pto->setInventoryKnown.count(inv))
4000 // trickle out tx inv to protect privacy
4001 if (inv.type == MSG_TX && !fSendTrickle)
4003 // 1/4 of tx invs blast to all immediately
4004 static uint256 hashSalt;
4006 hashSalt = GetRandHash();
4007 uint256 hashRand = inv.hash ^ hashSalt;
4008 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4009 bool fTrickleWait = ((hashRand & 3) != 0);
4011 // always trickle our own transactions
4015 if (GetTransaction(inv.hash, wtx))
4017 fTrickleWait = true;
4022 vInvWait.push_back(inv);
4027 // returns true if wasn't already contained in the set
4028 if (pto->setInventoryKnown.insert(inv).second)
4030 vInv.push_back(inv);
4031 if (vInv.size() >= 1000)
4033 pto->PushMessage("inv", vInv);
4038 pto->vInventoryToSend = vInvWait;
4041 pto->PushMessage("inv", vInv);
4047 vector<CInv> vGetData;
4048 int64_t nNow = GetTime() * 1000000;
4050 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4052 const CInv& inv = (*pto->mapAskFor.begin()).second;
4053 if (!AlreadyHave(txdb, inv))
4056 printf("sending getdata: %s\n", inv.ToString().c_str());
4057 vGetData.push_back(inv);
4058 if (vGetData.size() >= 1000)
4060 pto->PushMessage("getdata", vGetData);
4063 mapAlreadyAskedFor[inv] = nNow;
4065 pto->mapAskFor.erase(pto->mapAskFor.begin());
4067 if (!vGetData.empty())
4068 pto->PushMessage("getdata", vGetData);
4081 std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4082 for (; it1 != mapBlockIndex.end(); it1++)
4083 delete (*it1).second;
4084 mapBlockIndex.clear();
4087 std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4088 for (; it2 != mapOrphanBlocks.end(); it2++)
4089 delete (*it2).second;
4090 mapOrphanBlocks.clear();
4092 // orphan transactions
4094 } instance_of_cmaincleanup;