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_TX_FEE;
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);
154 // Preloaded coins cache invalidation
155 fCoinsDataActual = false;
158 // notify wallets about a new best chain
159 void static SetBestChain(const CBlockLocator& loc)
161 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
162 pwallet->SetBestChain(loc);
165 // notify wallets about an updated transaction
166 void static UpdatedTransaction(const uint256& hashTx)
168 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
169 pwallet->UpdatedTransaction(hashTx);
173 void static PrintWallets(const CBlock& block)
175 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
176 pwallet->PrintWallet(block);
179 // notify wallets about an incoming inventory (for request counts)
180 void static Inventory(const uint256& hash)
182 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
183 pwallet->Inventory(hash);
186 // ask wallets to resend their transactions
187 void ResendWalletTransactions()
189 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
190 pwallet->ResendWalletTransactions();
199 //////////////////////////////////////////////////////////////////////////////
201 // mapOrphanTransactions
204 bool AddOrphanTx(const CTransaction& tx)
206 uint256 hash = tx.GetHash();
207 if (mapOrphanTransactions.count(hash))
210 // Ignore big transactions, to avoid a
211 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
212 // large transaction with a missing parent then we assume
213 // it will rebroadcast it later, after the parent transaction(s)
214 // have been mined or received.
215 // 10,000 orphans, each of which is at most 5,000 bytes big is
216 // at most 500 megabytes of orphans:
218 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
222 printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
226 mapOrphanTransactions[hash] = tx;
227 BOOST_FOREACH(const CTxIn& txin, tx.vin)
228 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
230 printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
231 mapOrphanTransactions.size());
235 void static EraseOrphanTx(uint256 hash)
237 if (!mapOrphanTransactions.count(hash))
239 const CTransaction& tx = mapOrphanTransactions[hash];
240 BOOST_FOREACH(const CTxIn& txin, tx.vin)
242 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
243 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
244 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
246 mapOrphanTransactions.erase(hash);
249 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
251 unsigned int nEvicted = 0;
252 while (mapOrphanTransactions.size() > nMaxOrphans)
254 // Evict a random orphan:
255 uint256 randomhash = GetRandHash();
256 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
257 if (it == mapOrphanTransactions.end())
258 it = mapOrphanTransactions.begin();
259 EraseOrphanTx(it->first);
271 //////////////////////////////////////////////////////////////////////////////
273 // CTransaction and CTxIndex
276 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
279 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
281 if (!ReadFromDisk(txindexRet.pos))
283 if (prevout.n >= vout.size())
291 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
294 return ReadFromDisk(txdb, prevout, txindex);
297 bool CTransaction::ReadFromDisk(COutPoint prevout)
301 return ReadFromDisk(txdb, prevout, txindex);
304 bool CTransaction::IsStandard(string& strReason) const
306 if (nVersion > CTransaction::CURRENT_VERSION)
308 strReason = "version";
312 unsigned int nDataOut = 0;
313 txnouttype whichType;
314 BOOST_FOREACH(const CTxIn& txin, vin)
316 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
317 // keys. (remember the 520 byte limit on redeemScript size) That works
318 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
319 // bytes of scriptSig, which we round off to 1650 bytes for some minor
320 // future-proofing. That's also enough to spend a 20-of-20
321 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
322 // considered standard)
323 if (txin.scriptSig.size() > 1650)
325 strReason = "scriptsig-size";
328 if (!txin.scriptSig.IsPushOnly())
330 strReason = "scriptsig-not-pushonly";
333 if (!txin.scriptSig.HasCanonicalPushes()) {
334 strReason = "txin-scriptsig-not-canonicalpushes";
338 BOOST_FOREACH(const CTxOut& txout, vout) {
339 if (!::IsStandard(txout.scriptPubKey, whichType)) {
340 strReason = "scriptpubkey";
343 if (whichType == TX_NULL_DATA)
346 if (txout.nValue == 0) {
347 strReason = "txout-value=0";
350 if (!txout.scriptPubKey.HasCanonicalPushes()) {
351 strReason = "txout-scriptsig-not-canonicalpushes";
357 // only one OP_RETURN txout is permitted
359 strReason = "multi-op-return";
367 // Check transaction inputs, and make sure any
368 // pay-to-script-hash transactions are evaluating IsStandard scripts
370 // Why bother? To avoid denial-of-service attacks; an attacker
371 // can submit a standard HASH... OP_EQUAL transaction,
372 // which will get accepted into blocks. The redemption
373 // script can be anything; an attacker could use a very
374 // expensive-to-check-upon-redemption script like:
375 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
377 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
380 return true; // Coinbases don't use vin normally
382 for (unsigned int i = 0; i < vin.size(); i++)
384 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
386 vector<vector<unsigned char> > vSolutions;
387 txnouttype whichType;
388 // get the scriptPubKey corresponding to this input:
389 const CScript& prevScript = prev.scriptPubKey;
390 if (!Solver(prevScript, whichType, vSolutions))
392 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
393 if (nArgsExpected < 0)
396 // Transactions with extra stuff in their scriptSigs are
397 // non-standard. Note that this EvalScript() call will
398 // be quick, because if there are any operations
399 // beside "push data" in the scriptSig the
400 // IsStandard() call returns false
401 vector<vector<unsigned char> > stack;
402 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
405 if (whichType == TX_SCRIPTHASH)
409 CScript subscript(stack.back().begin(), stack.back().end());
410 vector<vector<unsigned char> > vSolutions2;
411 txnouttype whichType2;
412 if (!Solver(subscript, whichType2, vSolutions2))
414 if (whichType2 == TX_SCRIPTHASH)
418 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
421 nArgsExpected += tmpExpected;
424 if (stack.size() != (unsigned int)nArgsExpected)
432 CTransaction::GetLegacySigOpCount() const
434 unsigned int nSigOps = 0;
435 BOOST_FOREACH(const CTxIn& txin, vin)
437 nSigOps += txin.scriptSig.GetSigOpCount(false);
439 BOOST_FOREACH(const CTxOut& txout, vout)
441 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
447 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
459 // Load the block this tx is in
461 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
463 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
468 // Update the tx's hashBlock
469 hashBlock = pblock->GetHash();
471 // Locate the transaction
472 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
473 if (pblock->vtx[nIndex] == *(CTransaction*)this)
475 if (nIndex == (int)pblock->vtx.size())
477 vMerkleBranch.clear();
479 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
483 // Fill in merkle branch
484 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
487 // Is the tx in a block that's in the main chain
488 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
489 if (mi == mapBlockIndex.end())
491 CBlockIndex* pindex = (*mi).second;
492 if (!pindex || !pindex->IsInMainChain())
495 return pindexBest->nHeight - pindex->nHeight + 1;
504 bool CTransaction::CheckTransaction() const
506 // Basic checks that don't depend on any context
508 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
510 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
512 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
513 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
515 // Check for negative or overflow output values
516 int64_t nValueOut = 0;
517 for (unsigned int i = 0; i < vout.size(); i++)
519 const CTxOut& txout = vout[i];
520 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
521 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
523 if (txout.nValue < 0)
524 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
525 if (txout.nValue > MAX_MONEY)
526 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
527 nValueOut += txout.nValue;
528 if (!MoneyRange(nValueOut))
529 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
532 // Check for duplicate inputs
533 set<COutPoint> vInOutPoints;
534 BOOST_FOREACH(const CTxIn& txin, vin)
536 if (vInOutPoints.count(txin.prevout))
538 vInOutPoints.insert(txin.prevout);
543 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
544 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
548 BOOST_FOREACH(const CTxIn& txin, vin)
549 if (txin.prevout.IsNull())
550 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
556 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
558 int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
562 // Enforce 0.01 as minimum fee for old approach or coinstake
564 nMinRelayTxFee = CENT;
567 // Base fee is either nMinTxFee or nMinRelayTxFee
568 int64_t nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
570 unsigned int nNewBlockSize = nBlockSize + nBytes;
571 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
577 // Transactions under 1K are free
583 // Free transaction area
584 if (nNewBlockSize < 27000)
589 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
590 // each non empty output which is less than 0.01
592 // It's safe to ignore empty outputs here, because these inputs are allowed
593 // only for coinbase and coinstake transactions.
594 BOOST_FOREACH(const CTxOut& txout, vout)
595 if (txout.nValue < CENT && !txout.IsEmpty())
598 // Raise the price as the block approaches full
599 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
601 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
603 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
606 if (!MoneyRange(nMinFee))
613 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
614 bool* pfMissingInputs)
617 *pfMissingInputs = false;
619 if (!tx.CheckTransaction())
620 return error("CTxMemPool::accept() : CheckTransaction failed");
622 // Coinbase is only valid in a block, not as a loose transaction
624 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
626 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
627 if (tx.IsCoinStake())
628 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
630 // To help v0.1.5 clients who would see it as a negative number
631 if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
632 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
634 // Rather not work on nonstandard transactions (unless -testnet)
636 if (!fTestNet && !tx.IsStandard(strNonStd))
637 return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
639 // Do we already have it?
640 uint256 hash = tx.GetHash();
643 if (mapTx.count(hash))
647 if (txdb.ContainsTx(hash))
650 // Check for conflicts with in-memory transactions
651 CTransaction* ptxOld = NULL;
652 for (unsigned int i = 0; i < tx.vin.size(); i++)
654 COutPoint outpoint = tx.vin[i].prevout;
655 if (mapNextTx.count(outpoint))
657 // Disable replacement feature for now
660 // Allow replacing with a newer version of the same transaction
663 ptxOld = mapNextTx[outpoint].ptx;
664 if (ptxOld->IsFinal())
666 if (!tx.IsNewerThan(*ptxOld))
668 for (unsigned int i = 0; i < tx.vin.size(); i++)
670 COutPoint outpoint = tx.vin[i].prevout;
671 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
681 map<uint256, CTxIndex> mapUnused;
682 bool fInvalid = false;
683 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
686 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
688 *pfMissingInputs = true;
692 // Check for non-standard pay-to-script-hash in inputs
693 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
694 return error("CTxMemPool::accept() : nonstandard transaction input");
696 // Note: if you modify this code to accept non-standard transactions, then
697 // you should add code here to check that the transaction does a
698 // reasonable number of ECDSA signature verifications.
700 int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
701 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
703 // Don't accept it if it can't get into a block
704 int64_t txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
705 if (nFees < txMinFee)
706 return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
707 hash.ToString().c_str(),
710 // Continuously rate-limit free transactions
711 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
712 // be annoying or make others' transactions take longer to confirm.
713 if (nFees < MIN_RELAY_TX_FEE)
715 static CCriticalSection cs;
716 static double dFreeCount;
717 static int64_t nLastTime;
718 int64_t nNow = GetTime();
722 // Use an exponentially decaying ~10-minute window:
723 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
725 // -limitfreerelay unit is thousand-bytes-per-minute
726 // At default rate it would take over a month to fill 1GB
727 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
728 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
730 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
735 // Check against previous transactions
736 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
737 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, SIG_SWITCH_TIME < tx.nTime ? STRICT_FLAGS : SOFT_FLAGS))
739 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
743 // Store transaction in memory
748 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
751 addUnchecked(hash, tx);
754 ///// are we sure this is ok when loading transactions or restoring block txes
755 // If updated, erase old tx from wallet
757 EraseFromWallets(ptxOld->GetHash());
759 printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
760 hash.ToString().substr(0,10).c_str(),
765 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
767 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
770 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
772 // Add to memory pool without checking anything. Don't call this directly,
773 // call CTxMemPool::accept to properly check the transaction first.
776 for (unsigned int i = 0; i < tx.vin.size(); i++)
777 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
778 nTransactionsUpdated++;
784 bool CTxMemPool::remove(CTransaction &tx)
786 // Remove transaction from memory pool
789 uint256 hash = tx.GetHash();
790 if (mapTx.count(hash))
792 BOOST_FOREACH(const CTxIn& txin, tx.vin)
793 mapNextTx.erase(txin.prevout);
795 nTransactionsUpdated++;
801 void CTxMemPool::clear()
806 ++nTransactionsUpdated;
809 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
814 vtxid.reserve(mapTx.size());
815 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
816 vtxid.push_back((*mi).first);
822 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
824 if (hashBlock == 0 || nIndex == -1)
827 // Find the block it claims to be in
828 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
829 if (mi == mapBlockIndex.end())
831 CBlockIndex* pindex = (*mi).second;
832 if (!pindex || !pindex->IsInMainChain())
835 // Make sure the merkle branch connects to this block
836 if (!fMerkleVerified)
838 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
840 fMerkleVerified = true;
844 return pindexBest->nHeight - pindex->nHeight + 1;
848 int CMerkleTx::GetBlocksToMaturity() const
850 if (!(IsCoinBase() || IsCoinStake()))
852 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
856 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
860 if (!IsInMainChain() && !ClientConnectInputs())
862 return CTransaction::AcceptToMemoryPool(txdb, false);
866 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
870 bool CMerkleTx::AcceptToMemoryPool()
873 return AcceptToMemoryPool(txdb);
878 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
883 // Add previous supporting transactions first
884 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
886 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
888 uint256 hash = tx.GetHash();
889 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
890 tx.AcceptToMemoryPool(txdb, fCheckInputs);
893 return AcceptToMemoryPool(txdb, fCheckInputs);
898 bool CWalletTx::AcceptWalletTransaction()
901 return AcceptWalletTransaction(txdb);
904 int CTxIndex::GetDepthInMainChain() const
908 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
910 // Find the block in the index
911 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
912 if (mi == mapBlockIndex.end())
914 CBlockIndex* pindex = (*mi).second;
915 if (!pindex || !pindex->IsInMainChain())
917 return 1 + nBestHeight - pindex->nHeight;
920 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
921 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
927 if (mempool.exists(hash))
929 tx = mempool.lookup(hash);
935 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
938 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
939 hashBlock = block.GetHash();
953 //////////////////////////////////////////////////////////////////////////////
955 // CBlock and CBlockIndex
958 static CBlockIndex* pblockindexFBBHLast;
959 CBlockIndex* FindBlockByHeight(int nHeight)
961 CBlockIndex *pblockindex;
962 if (nHeight < nBestHeight / 2)
963 pblockindex = pindexGenesisBlock;
965 pblockindex = pindexBest;
966 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
967 pblockindex = pblockindexFBBHLast;
968 while (pblockindex->nHeight > nHeight)
969 pblockindex = pblockindex->pprev;
970 while (pblockindex->nHeight < nHeight)
971 pblockindex = pblockindex->pnext;
972 pblockindexFBBHLast = pblockindex;
976 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
978 if (!fReadTransactions)
980 *this = pindex->GetBlockHeader();
983 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
985 if (GetHash() != pindex->GetBlockHash())
986 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
990 uint256 static GetOrphanRoot(const CBlock* pblock)
992 // Work back to the first block in the orphan chain
993 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
994 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
995 return pblock->GetHash();
998 // ppcoin: find block wanted by given orphan block
999 uint256 WantedByOrphan(const CBlock* pblockOrphan)
1001 // Work back to the first block in the orphan chain
1002 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
1003 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
1004 return pblockOrphan->hashPrevBlock;
1007 // select stake target limit according to hard-coded conditions
1008 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1010 if(fTestNet) // separate proof of stake target limit for testnet
1011 return bnProofOfStakeLimit;
1012 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1013 return bnProofOfStakeLimit;
1014 if(nHeight + 1 > 15000) // 24 bits since block 15000
1015 return bnProofOfStakeLegacyLimit;
1016 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1017 return bnProofOfStakeHardLimit;
1019 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1022 // miner's coin base reward based on nBits
1023 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees)
1025 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1028 bnTarget.SetCompact(nBits);
1029 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1030 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1032 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1033 // A reasonably continuous curve is used to avoid shock to market
1034 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1036 // Human readable form:
1038 // nSubsidy = 100 / (diff ^ 1/6)
1039 CBigNum bnLowerBound = CENT;
1040 CBigNum bnUpperBound = bnSubsidyLimit;
1041 while (bnLowerBound + CENT <= bnUpperBound)
1043 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1044 if (fDebug && GetBoolArg("-printcreation"))
1045 printf("GetProofOfWorkReward() : lower=%" PRId64 " upper=%" PRId64 " mid=%" PRId64 "\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1046 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1047 bnUpperBound = bnMidValue;
1049 bnLowerBound = bnMidValue;
1052 int64_t nSubsidy = bnUpperBound.getuint64();
1054 nSubsidy = (nSubsidy / CENT) * CENT;
1055 if (fDebug && GetBoolArg("-printcreation"))
1056 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1058 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1061 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1062 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1064 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1066 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1068 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1070 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1072 bnTarget.SetCompact(nBits);
1073 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1074 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1076 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1078 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1079 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1080 bnMidPart, bnRewardPart;
1082 while (bnLowerBound + CENT <= bnUpperBound)
1084 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1085 if (fDebug && GetBoolArg("-printcreation"))
1086 printf("GetProofOfStakeReward() : lower=%" PRId64 " upper=%" PRId64 " mid=%" PRId64 "\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1088 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1091 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1093 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1095 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1098 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1099 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1104 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1106 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1108 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1111 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1112 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1115 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1116 bnUpperBound = bnMidValue;
1118 bnLowerBound = bnMidValue;
1121 nRewardCoinYear = bnUpperBound.getuint64();
1122 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1126 // Old creation amount per coin-year, 5% fixed stake mint rate
1127 nRewardCoinYear = 5 * CENT;
1131 return nRewardCoinYear;
1133 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1135 // Set reasonable reward limit for large inputs since 20 Oct 2013
1137 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1138 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1140 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1141 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1143 nSubsidy = min(nSubsidy, nSubsidyLimit);
1146 if (fDebug && GetBoolArg("-printcreation"))
1147 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1151 static const int64_t nTargetTimespan = 7 * 24 * 60 * 60; // one week
1153 // get proof of work blocks max spacing according to hard-coded conditions
1154 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1156 if(nTime > TARGETS_SWITCH_TIME)
1157 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1160 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1162 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1166 // maximum nBits value could possible be required nTime after
1168 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1171 bnResult.SetCompact(nBase);
1173 while (nTime > 0 && bnResult < bnTargetLimit)
1175 // Maximum 200% adjustment per day...
1177 nTime -= 24 * 60 * 60;
1179 if (bnResult > bnTargetLimit)
1180 bnResult = bnTargetLimit;
1181 return bnResult.GetCompact();
1185 // minimum amount of work that could possibly be required nTime after
1186 // minimum proof-of-work required was nBase
1188 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1190 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1194 // minimum amount of stake that could possibly be required nTime after
1195 // minimum proof-of-stake required was nBase
1197 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1199 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1203 // ppcoin: find last block index up to pindex
1204 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1206 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1207 pindex = pindex->pprev;
1211 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1213 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1215 if (pindexLast == NULL)
1216 return bnTargetLimit.GetCompact(); // genesis block
1218 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1219 if (pindexPrev->pprev == NULL)
1220 return bnTargetLimit.GetCompact(); // first block
1221 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1222 if (pindexPrevPrev->pprev == NULL)
1223 return bnTargetLimit.GetCompact(); // second block
1225 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1227 // ppcoin: target change every block
1228 // ppcoin: retarget with exponential moving toward target spacing
1230 bnNew.SetCompact(pindexPrev->nBits);
1231 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1232 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1233 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1234 bnNew /= ((nInterval + 1) * nTargetSpacing);
1236 if (bnNew > bnTargetLimit)
1237 bnNew = bnTargetLimit;
1239 return bnNew.GetCompact();
1242 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1245 bnTarget.SetCompact(nBits);
1248 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1249 return error("CheckProofOfWork() : nBits below minimum work");
1251 // Check proof of work matches claimed amount
1252 if (hash > bnTarget.getuint256())
1253 return error("CheckProofOfWork() : hash doesn't match nBits");
1258 // Return maximum amount of blocks that other nodes claim to have
1259 int GetNumBlocksOfPeers()
1261 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1264 bool IsInitialBlockDownload()
1266 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1268 static int64_t nLastUpdate;
1269 static CBlockIndex* pindexLastBest;
1270 int64_t nCurrentTime = GetTime();
1271 if (pindexBest != pindexLastBest)
1273 pindexLastBest = pindexBest;
1274 nLastUpdate = nCurrentTime;
1276 return (nCurrentTime - nLastUpdate < 10 &&
1277 pindexBest->GetBlockTime() < nCurrentTime - 24 * 60 * 60);
1280 void static InvalidChainFound(CBlockIndex* pindexNew)
1282 if (pindexNew->nChainTrust > nBestInvalidTrust)
1284 nBestInvalidTrust = pindexNew->nChainTrust;
1285 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1286 uiInterface.NotifyBlocksChanged();
1289 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1290 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1292 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1293 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1294 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1295 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1296 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1297 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1298 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1299 nBestBlockTrust.Get64(),
1300 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1304 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1306 nTime = max(GetBlockTime(), GetAdjustedTime());
1319 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1321 // Relinquish previous transactions' spent pointers
1324 BOOST_FOREACH(const CTxIn& txin, vin)
1326 COutPoint prevout = txin.prevout;
1328 // Get prev txindex from disk
1330 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1331 return error("DisconnectInputs() : ReadTxIndex failed");
1333 if (prevout.n >= txindex.vSpent.size())
1334 return error("DisconnectInputs() : prevout.n out of range");
1336 // Mark outpoint as not spent
1337 txindex.vSpent[prevout.n].SetNull();
1340 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1341 return error("DisconnectInputs() : UpdateTxIndex failed");
1345 // Remove transaction from index
1346 // This can fail if a duplicate of this transaction was in a chain that got
1347 // reorganized away. This is only possible if this transaction was completely
1348 // spent, so erasing it would be a no-op anyway.
1349 txdb.EraseTxIndex(*this);
1355 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1356 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1358 // FetchInputs can return false either because we just haven't seen some inputs
1359 // (in which case the transaction should be stored as an orphan)
1360 // or because the transaction is malformed (in which case the transaction should
1361 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1365 return true; // Coinbase transactions have no inputs to fetch.
1367 for (unsigned int i = 0; i < vin.size(); i++)
1369 COutPoint prevout = vin[i].prevout;
1370 if (inputsRet.count(prevout.hash))
1371 continue; // Got it already
1374 CTxIndex& txindex = inputsRet[prevout.hash].first;
1376 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1378 // Get txindex from current proposed changes
1379 txindex = mapTestPool.find(prevout.hash)->second;
1383 // Read txindex from txdb
1384 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1386 if (!fFound && (fBlock || fMiner))
1387 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());
1390 CTransaction& txPrev = inputsRet[prevout.hash].second;
1391 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1393 // Get prev tx from single transactions in memory
1396 if (!mempool.exists(prevout.hash))
1397 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());
1398 txPrev = mempool.lookup(prevout.hash);
1401 txindex.vSpent.resize(txPrev.vout.size());
1405 // Get prev tx from disk
1406 if (!txPrev.ReadFromDisk(txindex.pos))
1407 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1411 // Make sure all prevout.n indexes are valid:
1412 for (unsigned int i = 0; i < vin.size(); i++)
1414 const COutPoint prevout = vin[i].prevout;
1415 assert(inputsRet.count(prevout.hash) != 0);
1416 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1417 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1418 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1420 // Revisit this if/when transaction replacement is implemented and allows
1423 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()));
1430 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1432 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1433 if (mi == inputs.end())
1434 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1436 const CTransaction& txPrev = (mi->second).second;
1437 if (input.prevout.n >= txPrev.vout.size())
1438 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1440 return txPrev.vout[input.prevout.n];
1443 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1448 int64_t nResult = 0;
1449 for (unsigned int i = 0; i < vin.size(); i++)
1451 nResult += GetOutputFor(vin[i], inputs).nValue;
1457 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1462 unsigned int nSigOps = 0;
1463 for (unsigned int i = 0; i < vin.size(); i++)
1465 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1466 if (prevout.scriptPubKey.IsPayToScriptHash())
1467 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1472 bool CScriptCheck::operator()() const {
1473 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1474 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1475 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1479 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1481 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1484 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1485 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1487 // Take over previous transactions' spent pointers
1488 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1489 // fMiner is true when called from the internal bitcoin miner
1490 // ... both are false when called from CTransaction::AcceptToMemoryPool
1494 int64_t nValueIn = 0;
1496 for (unsigned int i = 0; i < vin.size(); i++)
1498 COutPoint prevout = vin[i].prevout;
1499 assert(inputs.count(prevout.hash) > 0);
1500 CTxIndex& txindex = inputs[prevout.hash].first;
1501 CTransaction& txPrev = inputs[prevout.hash].second;
1503 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1504 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()));
1506 // If prev is coinbase or coinstake, check that it's matured
1507 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1508 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1509 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1510 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1512 // ppcoin: check transaction timestamp
1513 if (txPrev.nTime > nTime)
1514 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1516 // Check for negative or overflow input values
1517 nValueIn += txPrev.vout[prevout.n].nValue;
1518 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1519 return DoS(100, error("ConnectInputs() : txin values out of range"));
1524 pvChecks->reserve(vin.size());
1526 // The first loop above does all the inexpensive checks.
1527 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1528 // Helps prevent CPU exhaustion attacks.
1529 for (unsigned int i = 0; i < vin.size(); i++)
1531 COutPoint prevout = vin[i].prevout;
1532 assert(inputs.count(prevout.hash) > 0);
1533 CTxIndex& txindex = inputs[prevout.hash].first;
1534 CTransaction& txPrev = inputs[prevout.hash].second;
1536 // Check for conflicts (double-spend)
1537 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1538 // for an attacker to attempt to split the network.
1539 if (!txindex.vSpent[prevout.n].IsNull())
1540 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());
1542 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1543 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1544 // still computed and checked, and any change will be caught at the next checkpoint.
1548 CScriptCheck check(txPrev, *this, i, flags, 0);
1551 pvChecks->push_back(CScriptCheck());
1552 check.swap(pvChecks->back());
1556 if (flags & STRICT_FLAGS)
1558 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1559 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1561 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1563 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1567 // Mark outpoints as spent
1568 txindex.vSpent[prevout.n] = posThisTx;
1571 if (fBlock || fMiner)
1573 mapTestPool[prevout.hash] = txindex;
1579 // ppcoin: coin stake tx earns reward instead of paying fee
1581 if (!GetCoinAge(txdb, nCoinAge))
1582 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1584 unsigned int nTxSize = (nTime > VALIDATION_SWITCH_TIME || fTestNet) ? GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION) : 0;
1586 int64_t nReward = GetValueOut() - nValueIn;
1587 int64_t nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1589 if (nReward > nCalculatedReward)
1590 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1594 if (nValueIn < GetValueOut())
1595 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1597 // Tally transaction fees
1598 int64_t nTxFee = nValueIn - GetValueOut();
1600 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1603 if (!MoneyRange(nFees))
1604 return DoS(100, error("ConnectInputs() : nFees out of range"));
1612 bool CTransaction::ClientConnectInputs()
1617 // Take over previous transactions' spent pointers
1620 int64_t nValueIn = 0;
1621 for (unsigned int i = 0; i < vin.size(); i++)
1623 // Get prev tx from single transactions in memory
1624 COutPoint prevout = vin[i].prevout;
1625 if (!mempool.exists(prevout.hash))
1627 CTransaction& txPrev = mempool.lookup(prevout.hash);
1629 if (prevout.n >= txPrev.vout.size())
1633 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1634 return error("ClientConnectInputs() : VerifySignature failed");
1636 ///// this is redundant with the mempool.mapNextTx stuff,
1637 ///// not sure which I want to get rid of
1638 ///// this has to go away now that posNext is gone
1639 // // Check for conflicts
1640 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1641 // return error("ConnectInputs() : prev tx already used");
1643 // // Flag outpoints as used
1644 // txPrev.vout[prevout.n].posNext = posThisTx;
1646 nValueIn += txPrev.vout[prevout.n].nValue;
1648 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1649 return error("ClientConnectInputs() : txin values out of range");
1651 if (GetValueOut() > nValueIn)
1661 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1663 // Disconnect in reverse order
1664 for (int i = vtx.size()-1; i >= 0; i--)
1665 if (!vtx[i].DisconnectInputs(txdb))
1668 // Update block index on disk without changing it in memory.
1669 // The memory index structure will be changed after the db commits.
1672 CDiskBlockIndex blockindexPrev(pindex->pprev);
1673 blockindexPrev.hashNext = 0;
1674 if (!txdb.WriteBlockIndex(blockindexPrev))
1675 return error("DisconnectBlock() : WriteBlockIndex failed");
1678 // ppcoin: clean up wallet after disconnecting coinstake
1679 BOOST_FOREACH(CTransaction& tx, vtx)
1680 SyncWithWallets(tx, this, false, false);
1685 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1687 void ThreadScriptCheck(void*) {
1688 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1689 RenameThread("novacoin-scriptch");
1690 scriptcheckqueue.Thread();
1691 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1694 void ThreadScriptCheckQuit() {
1695 scriptcheckqueue.Quit();
1698 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1700 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1701 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1704 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1705 // unless those are already completely spent.
1706 // If such overwrites are allowed, coinbases and transactions depending upon those
1707 // can be duplicated to remove the ability to spend the first instance -- even after
1708 // being sent to another address.
1709 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1710 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1711 // already refuses previously-known transaction ids entirely.
1712 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1713 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1714 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1715 // initial block download.
1716 bool fEnforceBIP30 = true; // Always active in NovaCoin
1717 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1719 //// issue here: it doesn't know the version
1720 unsigned int nTxPos;
1722 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1723 // 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
1726 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1728 map<uint256, CTxIndex> mapQueuedChanges;
1729 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1732 int64_t nValueIn = 0;
1733 int64_t nValueOut = 0;
1734 unsigned int nSigOps = 0;
1735 BOOST_FOREACH(CTransaction& tx, vtx)
1737 uint256 hashTx = tx.GetHash();
1739 if (fEnforceBIP30) {
1740 CTxIndex txindexOld;
1741 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1742 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1748 nSigOps += tx.GetLegacySigOpCount();
1749 if (nSigOps > MAX_BLOCK_SIGOPS)
1750 return DoS(100, error("ConnectBlock() : too many sigops"));
1752 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1754 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1756 MapPrevTx mapInputs;
1757 if (tx.IsCoinBase())
1758 nValueOut += tx.GetValueOut();
1762 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1765 // Add in sigops done by pay-to-script-hash inputs;
1766 // this is to prevent a "rogue miner" from creating
1767 // an incredibly-expensive-to-validate block.
1768 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1769 if (nSigOps > MAX_BLOCK_SIGOPS)
1770 return DoS(100, error("ConnectBlock() : too many sigops"));
1772 int64_t nTxValueIn = tx.GetValueIn(mapInputs);
1773 int64_t nTxValueOut = tx.GetValueOut();
1774 nValueIn += nTxValueIn;
1775 nValueOut += nTxValueOut;
1776 if (!tx.IsCoinStake())
1777 nFees += nTxValueIn - nTxValueOut;
1779 std::vector<CScriptCheck> vChecks;
1780 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, nScriptCheckThreads ? &vChecks : NULL))
1782 control.Add(vChecks);
1785 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1788 if (!control.Wait())
1789 return DoS(100, false);
1791 if (IsProofOfWork())
1793 int64_t nBlockReward = GetProofOfWorkReward(nBits, nFees);
1795 // Check coinbase reward
1796 if (vtx[0].GetValueOut() > nBlockReward)
1797 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1798 vtx[0].GetValueOut(),
1802 // track money supply and mint amount info
1803 pindex->nMint = nValueOut - nValueIn + nFees;
1804 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1805 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1806 return error("Connect() : WriteBlockIndex for pindex failed");
1808 // fees are not collected by proof-of-stake miners
1809 // fees are destroyed to compensate the entire network
1810 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1811 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
1816 // Write queued txindex changes
1817 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1819 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1820 return error("ConnectBlock() : UpdateTxIndex failed");
1823 // Update block index on disk without changing it in memory.
1824 // The memory index structure will be changed after the db commits.
1827 CDiskBlockIndex blockindexPrev(pindex->pprev);
1828 blockindexPrev.hashNext = pindex->GetBlockHash();
1829 if (!txdb.WriteBlockIndex(blockindexPrev))
1830 return error("ConnectBlock() : WriteBlockIndex failed");
1833 // Watch for transactions paying to me
1834 BOOST_FOREACH(CTransaction& tx, vtx)
1835 SyncWithWallets(tx, this, true);
1841 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1843 printf("REORGANIZE\n");
1846 CBlockIndex* pfork = pindexBest;
1847 CBlockIndex* plonger = pindexNew;
1848 while (pfork != plonger)
1850 while (plonger->nHeight > pfork->nHeight)
1851 if (!(plonger = plonger->pprev))
1852 return error("Reorganize() : plonger->pprev is null");
1853 if (pfork == plonger)
1855 if (!(pfork = pfork->pprev))
1856 return error("Reorganize() : pfork->pprev is null");
1859 // List of what to disconnect
1860 vector<CBlockIndex*> vDisconnect;
1861 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1862 vDisconnect.push_back(pindex);
1864 // List of what to connect
1865 vector<CBlockIndex*> vConnect;
1866 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1867 vConnect.push_back(pindex);
1868 reverse(vConnect.begin(), vConnect.end());
1870 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());
1871 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());
1873 // Disconnect shorter branch
1874 vector<CTransaction> vResurrect;
1875 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1878 if (!block.ReadFromDisk(pindex))
1879 return error("Reorganize() : ReadFromDisk for disconnect failed");
1880 if (!block.DisconnectBlock(txdb, pindex))
1881 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1883 // Queue memory transactions to resurrect
1884 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1885 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1886 vResurrect.push_back(tx);
1889 // Connect longer branch
1890 vector<CTransaction> vDelete;
1891 for (unsigned int i = 0; i < vConnect.size(); i++)
1893 CBlockIndex* pindex = vConnect[i];
1895 if (!block.ReadFromDisk(pindex))
1896 return error("Reorganize() : ReadFromDisk for connect failed");
1897 if (!block.ConnectBlock(txdb, pindex))
1900 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1903 // Queue memory transactions to delete
1904 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1905 vDelete.push_back(tx);
1907 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1908 return error("Reorganize() : WriteHashBestChain failed");
1910 // Make sure it's successfully written to disk before changing memory structure
1911 if (!txdb.TxnCommit())
1912 return error("Reorganize() : TxnCommit failed");
1914 // Disconnect shorter branch
1915 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1917 pindex->pprev->pnext = NULL;
1919 // Connect longer branch
1920 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1922 pindex->pprev->pnext = pindex;
1924 // Resurrect memory transactions that were in the disconnected branch
1925 BOOST_FOREACH(CTransaction& tx, vResurrect)
1926 tx.AcceptToMemoryPool(txdb, false);
1928 // Delete redundant memory transactions that are in the connected branch
1929 BOOST_FOREACH(CTransaction& tx, vDelete)
1932 printf("REORGANIZE: done\n");
1938 // Called from inside SetBestChain: attaches a block to the new best chain being built
1939 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1941 uint256 hash = GetHash();
1943 // Adding to current best branch
1944 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1947 InvalidChainFound(pindexNew);
1950 if (!txdb.TxnCommit())
1951 return error("SetBestChain() : TxnCommit failed");
1953 // Add to current best branch
1954 pindexNew->pprev->pnext = pindexNew;
1956 // Delete redundant memory transactions
1957 BOOST_FOREACH(CTransaction& tx, vtx)
1963 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1965 uint256 hash = GetHash();
1967 if (!txdb.TxnBegin())
1968 return error("SetBestChain() : TxnBegin failed");
1970 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1972 txdb.WriteHashBestChain(hash);
1973 if (!txdb.TxnCommit())
1974 return error("SetBestChain() : TxnCommit failed");
1975 pindexGenesisBlock = pindexNew;
1977 else if (hashPrevBlock == hashBestChain)
1979 if (!SetBestChainInner(txdb, pindexNew))
1980 return error("SetBestChain() : SetBestChainInner failed");
1984 // the first block in the new chain that will cause it to become the new best chain
1985 CBlockIndex *pindexIntermediate = pindexNew;
1987 // list of blocks that need to be connected afterwards
1988 std::vector<CBlockIndex*> vpindexSecondary;
1990 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1991 // Try to limit how much needs to be done inside
1992 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1994 vpindexSecondary.push_back(pindexIntermediate);
1995 pindexIntermediate = pindexIntermediate->pprev;
1998 if (!vpindexSecondary.empty())
1999 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
2001 // Switch to new best branch
2002 if (!Reorganize(txdb, pindexIntermediate))
2005 InvalidChainFound(pindexNew);
2006 return error("SetBestChain() : Reorganize failed");
2009 // Connect further blocks
2010 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
2013 if (!block.ReadFromDisk(pindex))
2015 printf("SetBestChain() : ReadFromDisk failed\n");
2018 if (!txdb.TxnBegin()) {
2019 printf("SetBestChain() : TxnBegin 2 failed\n");
2022 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
2023 if (!block.SetBestChainInner(txdb, pindex))
2028 // Update best block in wallet (so we can detect restored wallets)
2029 bool fIsInitialDownload = IsInitialBlockDownload();
2030 if (!fIsInitialDownload)
2032 const CBlockLocator locator(pindexNew);
2033 ::SetBestChain(locator);
2037 hashBestChain = hash;
2038 pindexBest = pindexNew;
2039 pblockindexFBBHLast = NULL;
2040 nBestHeight = pindexBest->nHeight;
2041 nBestChainTrust = pindexNew->nChainTrust;
2042 nTimeBestReceived = GetTime();
2043 nTransactionsUpdated++;
2045 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2047 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
2048 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2049 CBigNum(nBestChainTrust).ToString().c_str(),
2050 nBestBlockTrust.Get64(),
2051 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2053 // Check the version of the last 100 blocks to see if we need to upgrade:
2054 if (!fIsInitialDownload)
2057 const CBlockIndex* pindex = pindexBest;
2058 for (int i = 0; i < 100 && pindex != NULL; i++)
2060 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2062 pindex = pindex->pprev;
2065 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2066 if (nUpgraded > 100/2)
2067 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2068 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2071 std::string strCmd = GetArg("-blocknotify", "");
2073 if (!fIsInitialDownload && !strCmd.empty())
2075 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
2076 boost::thread t(runCommand, strCmd); // thread runs free
2082 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2083 // Only those coins meeting minimum age requirement counts. As those
2084 // transactions not in main chain are not currently indexed so we
2085 // might not find out about their coin age. Older transactions are
2086 // guaranteed to be in main chain by sync-checkpoint. This rule is
2087 // introduced to help nodes establish a consistent view of the coin
2088 // age (trust score) of competing branches.
2089 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2091 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2097 BOOST_FOREACH(const CTxIn& txin, vin)
2099 // First try finding the previous transaction in database
2100 CTransaction txPrev;
2102 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2103 continue; // previous transaction not in main chain
2104 if (nTime < txPrev.nTime)
2105 return false; // Transaction timestamp violation
2107 // Read block header
2109 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2110 return false; // unable to read block of previous transaction
2111 if (block.GetBlockTime() + nStakeMinAge > nTime)
2112 continue; // only count coins meeting min age requirement
2114 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
2115 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2117 if (fDebug && GetBoolArg("-printcoinage"))
2118 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2121 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
2122 if (fDebug && GetBoolArg("-printcoinage"))
2123 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2124 nCoinAge = bnCoinDay.getuint64();
2128 // ppcoin: total coin age spent in block, in the unit of coin-days.
2129 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2134 BOOST_FOREACH(const CTransaction& tx, vtx)
2136 uint64_t nTxCoinAge;
2137 if (tx.GetCoinAge(txdb, nTxCoinAge))
2138 nCoinAge += nTxCoinAge;
2143 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2145 if (fDebug && GetBoolArg("-printcoinage"))
2146 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2150 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2152 // Check for duplicate
2153 uint256 hash = GetHash();
2154 if (mapBlockIndex.count(hash))
2155 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2157 // Construct new block index object
2158 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
2160 return error("AddToBlockIndex() : new CBlockIndex failed");
2161 pindexNew->phashBlock = &hash;
2162 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2163 if (miPrev != mapBlockIndex.end())
2165 pindexNew->pprev = (*miPrev).second;
2166 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2169 // ppcoin: compute chain trust score
2170 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2172 // ppcoin: compute stake entropy bit for stake modifier
2173 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2174 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2176 // ppcoin: record proof-of-stake hash value
2177 if (pindexNew->IsProofOfStake())
2179 if (!mapProofOfStake.count(hash))
2180 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2181 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2184 // ppcoin: compute stake modifier
2185 uint64_t nStakeModifier = 0;
2186 bool fGeneratedStakeModifier = false;
2187 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2188 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2189 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2190 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2191 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2192 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2194 // Add to mapBlockIndex
2195 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2196 if (pindexNew->IsProofOfStake())
2197 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2198 pindexNew->phashBlock = &((*mi).first);
2200 // Write to disk block index
2202 if (!txdb.TxnBegin())
2204 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2205 if (!txdb.TxnCommit())
2209 if (pindexNew->nChainTrust > nBestChainTrust)
2210 if (!SetBestChain(txdb, pindexNew))
2213 if (pindexNew == pindexBest)
2215 // Notify UI to display prev block's coinbase if it was ours
2216 static uint256 hashPrevBestCoinBase;
2217 UpdatedTransaction(hashPrevBestCoinBase);
2218 hashPrevBestCoinBase = vtx[0].GetHash();
2221 static int8_t counter = 0;
2222 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2223 uiInterface.NotifyBlocksChanged();
2230 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2232 // These are checks that are independent of context
2233 // that can be verified before saving an orphan block.
2235 set<uint256> uniqueTx; // tx hashes
2236 unsigned int nSigOps = 0; // total sigops
2239 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2240 return DoS(100, error("CheckBlock() : size limits failed"));
2242 bool fProofOfStake = IsProofOfStake();
2244 // First transaction must be coinbase, the rest must not be
2245 if (!vtx[0].IsCoinBase())
2246 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2248 if (!vtx[0].CheckTransaction())
2249 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2251 uniqueTx.insert(vtx[0].GetHash());
2252 nSigOps += vtx[0].GetLegacySigOpCount();
2256 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2257 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2259 // nNonce must be zero for proof-of-stake blocks
2261 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2263 // Coinbase output should be empty if proof-of-stake block
2264 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2265 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2267 // Check coinstake timestamp
2268 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2269 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2271 // NovaCoin: check proof-of-stake block signature
2272 if (fCheckSig && !CheckBlockSignature())
2273 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2275 if (!vtx[1].CheckTransaction())
2276 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2278 uniqueTx.insert(vtx[1].GetHash());
2279 nSigOps += vtx[1].GetLegacySigOpCount();
2283 // Check proof of work matches claimed amount
2284 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2285 return DoS(50, error("CheckBlock() : proof of work failed"));
2288 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2289 return error("CheckBlock() : block timestamp too far in the future");
2291 // Check coinbase timestamp
2292 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2293 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2296 // Iterate all transactions starting from second for proof-of-stake block
2297 // or first for proof-of-work block
2298 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2300 const CTransaction& tx = vtx[i];
2302 // Reject coinbase transactions at non-zero index
2303 if (tx.IsCoinBase())
2304 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2306 // Reject coinstake transactions at index != 1
2307 if (tx.IsCoinStake())
2308 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2310 // Check transaction timestamp
2311 if (GetBlockTime() < (int64_t)tx.nTime)
2312 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2314 // Check transaction consistency
2315 if (!tx.CheckTransaction())
2316 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2318 // Add transaction hash into list of unique transaction IDs
2319 uniqueTx.insert(tx.GetHash());
2321 // Calculate sigops count
2322 nSigOps += tx.GetLegacySigOpCount();
2325 // Check for duplicate txids. This is caught by ConnectInputs(),
2326 // but catching it earlier avoids a potential DoS attack:
2327 if (uniqueTx.size() != vtx.size())
2328 return DoS(100, error("CheckBlock() : duplicate transaction"));
2330 // Reject block if validation would consume too much resources.
2331 if (nSigOps > MAX_BLOCK_SIGOPS)
2332 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2334 // Check merkle root
2335 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2336 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2341 bool CBlock::AcceptBlock()
2343 // Check for duplicate
2344 uint256 hash = GetHash();
2345 if (mapBlockIndex.count(hash))
2346 return error("AcceptBlock() : block already in mapBlockIndex");
2348 // Get prev block index
2349 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2350 if (mi == mapBlockIndex.end())
2351 return DoS(10, error("AcceptBlock() : prev block not found"));
2352 CBlockIndex* pindexPrev = (*mi).second;
2353 int nHeight = pindexPrev->nHeight+1;
2355 // Check proof-of-work or proof-of-stake
2356 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2357 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2359 // Check timestamp against prev
2360 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2361 return error("AcceptBlock() : block's timestamp is too early");
2363 // Check that all transactions are finalized
2364 BOOST_FOREACH(const CTransaction& tx, vtx)
2365 if (!tx.IsFinal(nHeight, GetBlockTime()))
2366 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2368 // Check that the block chain matches the known block chain up to a checkpoint
2369 if (!Checkpoints::CheckHardened(nHeight, hash))
2370 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2372 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2374 // Check that the block satisfies synchronized checkpoint
2375 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2376 return error("AcceptBlock() : rejected by synchronized checkpoint");
2378 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2379 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2381 // Enforce rule that the coinbase starts with serialized block height
2382 CScript expect = CScript() << nHeight;
2383 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2384 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2385 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2387 // Write block to history file
2388 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2389 return error("AcceptBlock() : out of disk space");
2390 unsigned int nFile = -1;
2391 unsigned int nBlockPos = 0;
2392 if (!WriteToDisk(nFile, nBlockPos))
2393 return error("AcceptBlock() : WriteToDisk failed");
2394 if (!AddToBlockIndex(nFile, nBlockPos))
2395 return error("AcceptBlock() : AddToBlockIndex failed");
2397 // Relay inventory, but don't relay old inventory during initial block download
2398 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2399 if (hashBestChain == hash)
2402 BOOST_FOREACH(CNode* pnode, vNodes)
2403 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2404 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2407 // ppcoin: check pending sync-checkpoint
2408 Checkpoints::AcceptPendingSyncCheckpoint();
2413 uint256 CBlockIndex::GetBlockTrust() const
2416 bnTarget.SetCompact(nBits);
2422 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2423 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2427 // Calculate work amount for block
2428 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2430 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2431 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2433 // Return nPoWTrust for the first 12 blocks
2434 if (pprev == NULL || pprev->nHeight < 12)
2437 const CBlockIndex* currentIndex = pprev;
2439 if(IsProofOfStake())
2441 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2443 // Return 1/3 of score if parent block is not the PoW block
2444 if (!pprev->IsProofOfWork())
2445 return (bnNewTrust / 3).getuint256();
2449 // Check last 12 blocks type
2450 while (pprev->nHeight - currentIndex->nHeight < 12)
2452 if (currentIndex->IsProofOfWork())
2454 currentIndex = currentIndex->pprev;
2457 // Return 1/3 of score if less than 3 PoW blocks found
2459 return (bnNewTrust / 3).getuint256();
2461 return bnNewTrust.getuint256();
2465 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2467 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2468 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2469 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2473 // Check last 12 blocks type
2474 while (pprev->nHeight - currentIndex->nHeight < 12)
2476 if (currentIndex->IsProofOfStake())
2478 currentIndex = currentIndex->pprev;
2481 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2483 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2485 bnTarget.SetCompact(pprev->nBits);
2490 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2492 // Return nPoWTrust + full trust score for previous block nBits
2493 return nPoWTrust + bnNewTrust.getuint256();
2497 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2499 unsigned int nFound = 0;
2500 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2502 if (pstart->nVersion >= minVersion)
2504 pstart = pstart->pprev;
2506 return (nFound >= nRequired);
2509 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2511 // Check for duplicate
2512 uint256 hash = pblock->GetHash();
2513 if (mapBlockIndex.count(hash))
2514 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2515 if (mapOrphanBlocks.count(hash))
2516 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2518 // ppcoin: check proof-of-stake
2519 // Limited duplicity on stake: prevents block flood attack
2520 // Duplicate stake allowed only when there is orphan child block
2521 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2522 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());
2524 // Preliminary checks
2525 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2526 return error("ProcessBlock() : CheckBlock FAILED");
2528 // ppcoin: verify hash target and signature of coinstake tx
2529 if (pblock->IsProofOfStake())
2531 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2532 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2534 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2535 return false; // do not error here as we expect this during initial block download
2537 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2538 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2541 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2542 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2544 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2545 int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2547 bnNewBlock.SetCompact(pblock->nBits);
2550 if (pblock->IsProofOfStake())
2551 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2553 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2555 if (bnNewBlock > bnRequired)
2558 pfrom->Misbehaving(100);
2559 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2563 // ppcoin: ask for pending sync-checkpoint if any
2564 if (!IsInitialBlockDownload())
2565 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2567 // If don't already have its previous block, shunt it off to holding area until we get it
2568 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2570 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2571 CBlock* pblock2 = new CBlock(*pblock);
2572 // ppcoin: check proof-of-stake
2573 if (pblock2->IsProofOfStake())
2575 // Limited duplicity on stake: prevents block flood attack
2576 // Duplicate stake allowed only when there is orphan child block
2577 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2578 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock2->GetProofOfStake().first.ToString().c_str(), pblock2->GetProofOfStake().second, hash.ToString().c_str());
2580 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2582 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2583 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2585 // Ask this guy to fill in what we're missing
2588 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2589 // ppcoin: getblocks may not obtain the ancestor block rejected
2590 // earlier by duplicate-stake check so we ask for it again directly
2591 if (!IsInitialBlockDownload())
2592 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2598 if (!pblock->AcceptBlock())
2599 return error("ProcessBlock() : AcceptBlock FAILED");
2601 // Recursively process any orphan blocks that depended on this one
2602 vector<uint256> vWorkQueue;
2603 vWorkQueue.push_back(hash);
2604 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2606 uint256 hashPrev = vWorkQueue[i];
2607 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2608 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2611 CBlock* pblockOrphan = (*mi).second;
2612 if (pblockOrphan->AcceptBlock())
2613 vWorkQueue.push_back(pblockOrphan->GetHash());
2614 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2615 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2616 delete pblockOrphan;
2618 mapOrphanBlocksByPrev.erase(hashPrev);
2621 printf("ProcessBlock: ACCEPTED\n");
2623 // ppcoin: if responsible for sync-checkpoint send it
2624 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2625 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2630 // novacoin: attempt to generate suitable proof-of-stake
2631 bool CBlock::SignBlock(CWallet& wallet)
2633 // if we are trying to sign
2634 // something except proof-of-stake block template
2635 if (!vtx[0].vout[0].IsEmpty())
2638 // if we are trying to sign
2639 // a complete proof-of-stake block
2640 if (IsProofOfStake())
2643 static uint32_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2646 CTransaction txCoinStake;
2647 uint32_t nSearchTime = txCoinStake.nTime; // search to current time
2649 if (nSearchTime > nLastCoinStakeSearchTime)
2651 if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2653 if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2655 // make sure coinstake would meet timestamp protocol
2656 // as it would be the same as the block timestamp
2657 vtx[0].nTime = nTime = txCoinStake.nTime;
2658 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2659 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2661 // we have to make sure that we have no future timestamps in
2662 // our transactions set
2663 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2664 if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2666 vtx.insert(vtx.begin() + 1, txCoinStake);
2667 hashMerkleRoot = BuildMerkleTree();
2669 // append a signature to our block
2670 return key.Sign(GetHash(), vchBlockSig);
2673 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2674 nLastCoinStakeSearchTime = nSearchTime;
2680 // ppcoin: check block signature
2681 bool CBlock::CheckBlockSignature() const
2683 if (IsProofOfWork())
2686 vector<valtype> vSolutions;
2687 txnouttype whichType;
2689 const CTxOut& txout = vtx[1].vout[1];
2691 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2693 if (whichType == TX_PUBKEY)
2695 valtype& vchPubKey = vSolutions[0];
2697 if (!key.SetPubKey(vchPubKey))
2699 if (vchBlockSig.empty())
2701 return key.Verify(GetHash(), vchBlockSig);
2706 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2708 uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2710 // Check for nMinDiskSpace bytes (currently 50MB)
2711 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2714 string strMessage = _("Warning: Disk space is low!");
2715 strMiscWarning = strMessage;
2716 printf("*** %s\n", strMessage.c_str());
2717 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2724 static filesystem::path BlockFilePath(unsigned int nFile)
2726 string strBlockFn = strprintf("blk%04u.dat", nFile);
2727 return GetDataDir() / strBlockFn;
2730 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2732 if ((nFile < 1) || (nFile == (unsigned int) -1))
2734 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2737 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2739 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2748 static unsigned int nCurrentBlockFile = 1;
2750 FILE* AppendBlockFile(unsigned int& nFileRet)
2755 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2758 if (fseek(file, 0, SEEK_END) != 0)
2760 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2761 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2763 nFileRet = nCurrentBlockFile;
2767 nCurrentBlockFile++;
2771 void UnloadBlockIndex()
2773 mapBlockIndex.clear();
2774 setStakeSeen.clear();
2775 pindexGenesisBlock = NULL;
2777 nBestChainTrust = 0;
2778 nBestInvalidTrust = 0;
2783 bool LoadBlockIndex(bool fAllowNew)
2787 pchMessageStart[0] = 0xcd;
2788 pchMessageStart[1] = 0xf2;
2789 pchMessageStart[2] = 0xc0;
2790 pchMessageStart[3] = 0xef;
2792 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2793 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2794 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2795 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2796 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2803 if (!txdb.LoadBlockIndex())
2807 // Init with genesis block
2809 if (mapBlockIndex.empty())
2818 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2819 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2820 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2822 // vMerkleTree: 4cb33b3b6a
2826 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2827 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2828 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2830 // vMerkleTree: 4cb33b3b6a
2832 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2834 txNew.nTime = 1360105017;
2835 txNew.vin.resize(1);
2836 txNew.vout.resize(1);
2837 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2838 txNew.vout[0].SetEmpty();
2840 block.vtx.push_back(txNew);
2841 block.hashPrevBlock = 0;
2842 block.hashMerkleRoot = block.BuildMerkleTree();
2844 block.nTime = 1360105017;
2845 block.nBits = bnProofOfWorkLimit.GetCompact();
2846 block.nNonce = !fTestNet ? 1575379 : 46534;
2849 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2851 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2852 assert(block.CheckBlock());
2854 // Start new block file
2856 unsigned int nBlockPos;
2857 if (!block.WriteToDisk(nFile, nBlockPos))
2858 return error("LoadBlockIndex() : writing genesis block to disk failed");
2859 if (!block.AddToBlockIndex(nFile, nBlockPos))
2860 return error("LoadBlockIndex() : genesis block not accepted");
2862 // initialize synchronized checkpoint
2863 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2864 return error("LoadBlockIndex() : failed to init sync checkpoint");
2866 // upgrade time set to zero if txdb initialized
2868 if (!txdb.WriteModifierUpgradeTime(0))
2869 return error("LoadBlockIndex() : failed to init upgrade info");
2870 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2876 string strPubKey = "";
2877 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2879 // write checkpoint master key to db
2881 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2882 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2883 if (!txdb.TxnCommit())
2884 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2885 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2886 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2889 // upgrade time set to zero if blocktreedb initialized
2890 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2892 if (nModifierUpgradeTime)
2893 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2895 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2899 nModifierUpgradeTime = GetTime();
2900 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2901 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2902 return error("LoadBlockIndex() : failed to write upgrade info");
2915 void PrintBlockTree()
2917 // pre-compute tree structure
2918 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2919 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2921 CBlockIndex* pindex = (*mi).second;
2922 mapNext[pindex->pprev].push_back(pindex);
2924 //while (rand() % 3 == 0)
2925 // mapNext[pindex->pprev].push_back(pindex);
2928 vector<pair<int, CBlockIndex*> > vStack;
2929 vStack.push_back(make_pair(0, pindexGenesisBlock));
2932 while (!vStack.empty())
2934 int nCol = vStack.back().first;
2935 CBlockIndex* pindex = vStack.back().second;
2938 // print split or gap
2939 if (nCol > nPrevCol)
2941 for (int i = 0; i < nCol-1; i++)
2945 else if (nCol < nPrevCol)
2947 for (int i = 0; i < nCol; i++)
2954 for (int i = 0; i < nCol; i++)
2959 block.ReadFromDisk(pindex);
2960 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
2964 block.GetHash().ToString().c_str(),
2966 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2967 FormatMoney(pindex->nMint).c_str(),
2970 PrintWallets(block);
2972 // put the main time-chain first
2973 vector<CBlockIndex*>& vNext = mapNext[pindex];
2974 for (unsigned int i = 0; i < vNext.size(); i++)
2976 if (vNext[i]->pnext)
2978 swap(vNext[0], vNext[i]);
2984 for (unsigned int i = 0; i < vNext.size(); i++)
2985 vStack.push_back(make_pair(nCol+i, vNext[i]));
2989 bool LoadExternalBlockFile(FILE* fileIn)
2991 int64_t nStart = GetTimeMillis();
2997 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2998 unsigned int nPos = 0;
2999 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
3001 unsigned char pchData[65536];
3003 fseek(blkdat, nPos, SEEK_SET);
3004 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
3007 nPos = (unsigned int)-1;
3010 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
3013 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
3015 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
3018 nPos += ((unsigned char*)nFind - pchData) + 1;
3021 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
3022 } while(!fRequestShutdown);
3023 if (nPos == (unsigned int)-1)
3025 fseek(blkdat, nPos, SEEK_SET);
3028 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
3032 if (ProcessBlock(NULL,&block))
3040 catch (std::exception &e) {
3041 printf("%s() : Deserialize or I/O error caught during load\n",
3042 BOOST_CURRENT_FUNCTION);
3045 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3049 //////////////////////////////////////////////////////////////////////////////
3054 extern map<uint256, CAlert> mapAlerts;
3055 extern CCriticalSection cs_mapAlerts;
3057 string GetWarnings(string strFor)
3060 string strStatusBar;
3063 if (GetBoolArg("-testsafemode"))
3066 // Misc warnings like out of disk space and clock is wrong
3067 if (strMiscWarning != "")
3070 strStatusBar = strMiscWarning;
3073 // if detected unmet upgrade requirement enter safe mode
3074 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3075 if (IsFixedModifierInterval(nModifierUpgradeTime + 60*60*24)) // 1 day margin
3078 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3081 // if detected invalid checkpoint enter safe mode
3082 if (Checkpoints::hashInvalidCheckpoint != 0)
3085 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3091 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3093 const CAlert& alert = item.second;
3094 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3096 nPriority = alert.nPriority;
3097 strStatusBar = alert.strStatusBar;
3098 if (nPriority > 1000)
3099 strRPC = strStatusBar;
3104 if (strFor == "statusbar")
3105 return strStatusBar;
3106 else if (strFor == "rpc")
3108 assert(!"GetWarnings() : invalid parameter");
3119 //////////////////////////////////////////////////////////////////////////////
3125 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3131 bool txInMap = false;
3134 txInMap = (mempool.exists(inv.hash));
3137 mapOrphanTransactions.count(inv.hash) ||
3138 txdb.ContainsTx(inv.hash);
3142 return mapBlockIndex.count(inv.hash) ||
3143 mapOrphanBlocks.count(inv.hash);
3145 // Don't know what it is, just say we already got one
3152 // The message start string is designed to be unlikely to occur in normal data.
3153 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3154 // a large 4-byte int at any alignment.
3155 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3157 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3159 static map<CService, CPubKey> mapReuseKey;
3160 RandAddSeedPerfmon();
3162 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3163 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3165 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3169 if (strCommand == "version")
3171 // Each connection can only send one version message
3172 if (pfrom->nVersion != 0)
3174 pfrom->Misbehaving(1);
3181 uint64_t nNonce = 1;
3182 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3183 if (pfrom->nVersion < MIN_PROTO_VERSION)
3185 // Since February 20, 2012, the protocol is initiated at version 209,
3186 // and earlier versions are no longer supported
3187 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3188 pfrom->fDisconnect = true;
3192 if (pfrom->nVersion == 10300)
3193 pfrom->nVersion = 300;
3195 vRecv >> addrFrom >> nNonce;
3197 vRecv >> pfrom->strSubVer;
3199 vRecv >> pfrom->nStartingHeight;
3201 if (pfrom->fInbound && addrMe.IsRoutable())
3203 pfrom->addrLocal = addrMe;
3207 // Disconnect if we connected to ourself
3208 if (nNonce == nLocalHostNonce && nNonce > 1)
3210 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3211 pfrom->fDisconnect = true;
3215 if (pfrom->nVersion < 60010)
3217 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3218 pfrom->fDisconnect = true;
3222 // record my external IP reported by peer
3223 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3224 addrSeenByPeer = addrMe;
3226 // Be shy and don't send version until we hear
3227 if (pfrom->fInbound)
3228 pfrom->PushVersion();
3230 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3232 AddTimeData(pfrom->addr, nTime);
3235 pfrom->PushMessage("verack");
3236 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3238 if (!pfrom->fInbound)
3240 // Advertise our address
3241 if (!fNoListen && !IsInitialBlockDownload())
3243 CAddress addr = GetLocalAddress(&pfrom->addr);
3244 if (addr.IsRoutable())
3245 pfrom->PushAddress(addr);
3248 // Get recent addresses
3249 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3251 pfrom->PushMessage("getaddr");
3252 pfrom->fGetAddr = true;
3254 addrman.Good(pfrom->addr);
3256 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3258 addrman.Add(addrFrom, addrFrom);
3259 addrman.Good(addrFrom);
3263 // Ask the first connected node for block updates
3264 static int nAskedForBlocks = 0;
3265 if (!pfrom->fClient && !pfrom->fOneShot &&
3266 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3267 (pfrom->nVersion < NOBLKS_VERSION_START ||
3268 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3269 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3272 pfrom->PushGetBlocks(pindexBest, uint256(0));
3278 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3279 item.second.RelayTo(pfrom);
3282 // Relay sync-checkpoint
3284 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3285 if (!Checkpoints::checkpointMessage.IsNull())
3286 Checkpoints::checkpointMessage.RelayTo(pfrom);
3289 pfrom->fSuccessfullyConnected = true;
3291 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());
3293 cPeerBlockCounts.input(pfrom->nStartingHeight);
3295 // ppcoin: ask for pending sync-checkpoint if any
3296 if (!IsInitialBlockDownload())
3297 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3301 else if (pfrom->nVersion == 0)
3303 // Must have a version message before anything else
3304 pfrom->Misbehaving(1);
3309 else if (strCommand == "verack")
3311 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3315 else if (strCommand == "addr")
3317 vector<CAddress> vAddr;
3320 // Don't want addr from older versions unless seeding
3321 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3323 if (vAddr.size() > 1000)
3325 pfrom->Misbehaving(20);
3326 return error("message addr size() = %" PRIszu "", vAddr.size());
3329 // Store the new addresses
3330 vector<CAddress> vAddrOk;
3331 int64_t nNow = GetAdjustedTime();
3332 int64_t nSince = nNow - 10 * 60;
3333 BOOST_FOREACH(CAddress& addr, vAddr)
3337 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3338 addr.nTime = nNow - 5 * 24 * 60 * 60;
3339 pfrom->AddAddressKnown(addr);
3340 bool fReachable = IsReachable(addr);
3341 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3343 // Relay to a limited number of other nodes
3346 // Use deterministic randomness to send to the same nodes for 24 hours
3347 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3348 static uint256 hashSalt;
3350 hashSalt = GetRandHash();
3351 uint64_t hashAddr = addr.GetHash();
3352 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3353 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3354 multimap<uint256, CNode*> mapMix;
3355 BOOST_FOREACH(CNode* pnode, vNodes)
3357 if (pnode->nVersion < CADDR_TIME_VERSION)
3359 unsigned int nPointer;
3360 memcpy(&nPointer, &pnode, sizeof(nPointer));
3361 uint256 hashKey = hashRand ^ nPointer;
3362 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3363 mapMix.insert(make_pair(hashKey, pnode));
3365 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3366 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3367 ((*mi).second)->PushAddress(addr);
3370 // Do not store addresses outside our network
3372 vAddrOk.push_back(addr);
3374 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3375 if (vAddr.size() < 1000)
3376 pfrom->fGetAddr = false;
3377 if (pfrom->fOneShot)
3378 pfrom->fDisconnect = true;
3381 else if (strCommand == "inv")
3385 if (vInv.size() > MAX_INV_SZ)
3387 pfrom->Misbehaving(20);
3388 return error("message inv size() = %" PRIszu "", vInv.size());
3391 // find last block in inv vector
3392 unsigned int nLastBlock = (unsigned int)(-1);
3393 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3394 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3395 nLastBlock = vInv.size() - 1 - nInv;
3400 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3402 const CInv &inv = vInv[nInv];
3406 pfrom->AddInventoryKnown(inv);
3408 bool fAlreadyHave = AlreadyHave(txdb, inv);
3410 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3414 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3415 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3416 } else if (nInv == nLastBlock) {
3417 // In case we are on a very long side-chain, it is possible that we already have
3418 // the last block in an inv bundle sent in response to getblocks. Try to detect
3419 // this situation and push another getblocks to continue.
3420 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3422 printf("force request: %s\n", inv.ToString().c_str());
3425 // Track requests for our stuff
3426 Inventory(inv.hash);
3431 else if (strCommand == "getdata")
3435 if (vInv.size() > MAX_INV_SZ)
3437 pfrom->Misbehaving(20);
3438 return error("message getdata size() = %" PRIszu "", vInv.size());
3441 if (fDebugNet || (vInv.size() != 1))
3442 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3444 BOOST_FOREACH(const CInv& inv, vInv)
3448 if (fDebugNet || (vInv.size() == 1))
3449 printf("received getdata for: %s\n", inv.ToString().c_str());
3451 if (inv.type == MSG_BLOCK)
3453 // Send block from disk
3454 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3455 if (mi != mapBlockIndex.end())
3458 block.ReadFromDisk((*mi).second);
3459 pfrom->PushMessage("block", block);
3461 // Trigger them to send a getblocks request for the next batch of inventory
3462 if (inv.hash == pfrom->hashContinue)
3464 // ppcoin: send latest proof-of-work block to allow the
3465 // download node to accept as orphan (proof-of-stake
3466 // block might be rejected by stake connection check)
3468 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3469 pfrom->PushMessage("inv", vInv);
3470 pfrom->hashContinue = 0;
3474 else if (inv.IsKnownType())
3476 // Send stream from relay memory
3477 bool pushed = false;
3480 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3481 if (mi != mapRelay.end()) {
3482 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3486 if (!pushed && inv.type == MSG_TX) {
3488 if (mempool.exists(inv.hash)) {
3489 CTransaction tx = mempool.lookup(inv.hash);
3490 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3493 pfrom->PushMessage("tx", ss);
3498 // Track requests for our stuff
3499 Inventory(inv.hash);
3504 else if (strCommand == "getblocks")
3506 CBlockLocator locator;
3508 vRecv >> locator >> hashStop;
3510 // Find the last block the caller has in the main chain
3511 CBlockIndex* pindex = locator.GetBlockIndex();
3513 // Send the rest of the chain
3515 pindex = pindex->pnext;
3517 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3518 for (; pindex; pindex = pindex->pnext)
3520 if (pindex->GetBlockHash() == hashStop)
3522 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3523 // ppcoin: tell downloading node about the latest block if it's
3524 // without risk being rejected due to stake connection check
3525 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3526 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3529 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3532 // When this block is requested, we'll send an inv that'll make them
3533 // getblocks the next batch of inventory.
3534 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3535 pfrom->hashContinue = pindex->GetBlockHash();
3540 else if (strCommand == "checkpoint")
3542 CSyncCheckpoint checkpoint;
3543 vRecv >> checkpoint;
3545 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3548 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3550 BOOST_FOREACH(CNode* pnode, vNodes)
3551 checkpoint.RelayTo(pnode);
3555 else if (strCommand == "getheaders")
3557 CBlockLocator locator;
3559 vRecv >> locator >> hashStop;
3561 CBlockIndex* pindex = NULL;
3562 if (locator.IsNull())
3564 // If locator is null, return the hashStop block
3565 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3566 if (mi == mapBlockIndex.end())
3568 pindex = (*mi).second;
3572 // Find the last block the caller has in the main chain
3573 pindex = locator.GetBlockIndex();
3575 pindex = pindex->pnext;
3578 vector<CBlock> vHeaders;
3580 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3581 for (; pindex; pindex = pindex->pnext)
3583 vHeaders.push_back(pindex->GetBlockHeader());
3584 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3587 pfrom->PushMessage("headers", vHeaders);
3591 else if (strCommand == "tx")
3593 vector<uint256> vWorkQueue;
3594 vector<uint256> vEraseQueue;
3595 CDataStream vMsg(vRecv);
3600 CInv inv(MSG_TX, tx.GetHash());
3601 pfrom->AddInventoryKnown(inv);
3603 bool fMissingInputs = false;
3604 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3606 SyncWithWallets(tx, NULL, true);
3607 RelayTransaction(tx, inv.hash);
3608 mapAlreadyAskedFor.erase(inv);
3609 vWorkQueue.push_back(inv.hash);
3610 vEraseQueue.push_back(inv.hash);
3612 // Recursively process any orphan transactions that depended on this one
3613 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3615 uint256 hashPrev = vWorkQueue[i];
3616 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3617 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3620 const uint256& orphanTxHash = *mi;
3621 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3622 bool fMissingInputs2 = false;
3624 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3626 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3627 SyncWithWallets(tx, NULL, true);
3628 RelayTransaction(orphanTx, orphanTxHash);
3629 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3630 vWorkQueue.push_back(orphanTxHash);
3631 vEraseQueue.push_back(orphanTxHash);
3633 else if (!fMissingInputs2)
3636 vEraseQueue.push_back(orphanTxHash);
3637 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3642 BOOST_FOREACH(uint256 hash, vEraseQueue)
3643 EraseOrphanTx(hash);
3645 else if (fMissingInputs)
3649 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3650 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3652 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3654 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3658 else if (strCommand == "block")
3662 uint256 hashBlock = block.GetHash();
3664 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3667 CInv inv(MSG_BLOCK, hashBlock);
3668 pfrom->AddInventoryKnown(inv);
3670 if (ProcessBlock(pfrom, &block))
3671 mapAlreadyAskedFor.erase(inv);
3672 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3676 else if (strCommand == "getaddr")
3678 // Don't return addresses older than nCutOff timestamp
3679 int64_t nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3680 pfrom->vAddrToSend.clear();
3681 vector<CAddress> vAddr = addrman.GetAddr();
3682 BOOST_FOREACH(const CAddress &addr, vAddr)
3683 if(addr.nTime > nCutOff)
3684 pfrom->PushAddress(addr);
3688 else if (strCommand == "mempool")
3690 std::vector<uint256> vtxid;
3691 mempool.queryHashes(vtxid);
3693 for (unsigned int i = 0; i < vtxid.size(); i++) {
3694 CInv inv(MSG_TX, vtxid[i]);
3695 vInv.push_back(inv);
3696 if (i == (MAX_INV_SZ - 1))
3699 if (vInv.size() > 0)
3700 pfrom->PushMessage("inv", vInv);
3704 else if (strCommand == "checkorder")
3709 if (!GetBoolArg("-allowreceivebyip"))
3711 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3718 /// we have a chance to check the order here
3720 // Keep giving the same key to the same ip until they use it
3721 if (!mapReuseKey.count(pfrom->addr))
3722 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3724 // Send back approval of order and pubkey to use
3725 CScript scriptPubKey;
3726 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3727 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3731 else if (strCommand == "reply")
3736 CRequestTracker tracker;
3738 LOCK(pfrom->cs_mapRequests);
3739 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3740 if (mi != pfrom->mapRequests.end())
3742 tracker = (*mi).second;
3743 pfrom->mapRequests.erase(mi);
3746 if (!tracker.IsNull())
3747 tracker.fn(tracker.param1, vRecv);
3751 else if (strCommand == "ping")
3753 if (pfrom->nVersion > BIP0031_VERSION)
3757 // Echo the message back with the nonce. This allows for two useful features:
3759 // 1) A remote node can quickly check if the connection is operational
3760 // 2) Remote nodes can measure the latency of the network thread. If this node
3761 // is overloaded it won't respond to pings quickly and the remote node can
3762 // avoid sending us more work, like chain download requests.
3764 // The nonce stops the remote getting confused between different pings: without
3765 // it, if the remote node sends a ping once per second and this node takes 5
3766 // seconds to respond to each, the 5th ping the remote sends would appear to
3767 // return very quickly.
3768 pfrom->PushMessage("pong", nonce);
3773 else if (strCommand == "alert")
3778 uint256 alertHash = alert.GetHash();
3779 if (pfrom->setKnown.count(alertHash) == 0)
3781 if (alert.ProcessAlert())
3784 pfrom->setKnown.insert(alertHash);
3787 BOOST_FOREACH(CNode* pnode, vNodes)
3788 alert.RelayTo(pnode);
3792 // Small DoS penalty so peers that send us lots of
3793 // duplicate/expired/invalid-signature/whatever alerts
3794 // eventually get banned.
3795 // This isn't a Misbehaving(100) (immediate ban) because the
3796 // peer might be an older or different implementation with
3797 // a different signature key, etc.
3798 pfrom->Misbehaving(10);
3806 // Ignore unknown commands for extensibility
3810 // Update the last seen time for this node's address
3811 if (pfrom->fNetworkNode)
3812 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3813 AddressCurrentlyConnected(pfrom->addr);
3819 bool ProcessMessages(CNode* pfrom)
3821 CDataStream& vRecv = pfrom->vRecv;
3825 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3829 // (4) message start
3838 // Don't bother if send buffer is too full to respond anyway
3839 if (pfrom->vSend.size() >= SendBufferSize())
3842 // Scan for message start
3843 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3844 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3845 if (vRecv.end() - pstart < nHeaderSize)
3847 if ((int)vRecv.size() > nHeaderSize)
3849 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3850 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3854 if (pstart - vRecv.begin() > 0)
3855 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
3856 vRecv.erase(vRecv.begin(), pstart);
3859 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3864 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3867 string strCommand = hdr.GetCommand();
3870 unsigned int nMessageSize = hdr.nMessageSize;
3871 if (nMessageSize > MAX_SIZE)
3873 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3876 if (nMessageSize > vRecv.size())
3878 // Rewind and wait for rest of message
3879 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3884 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3885 unsigned int nChecksum = 0;
3886 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3887 if (nChecksum != hdr.nChecksum)
3889 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3890 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3894 // Copy message to its own buffer
3895 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3896 vRecv.ignore(nMessageSize);
3904 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3909 catch (std::ios_base::failure& e)
3911 if (strstr(e.what(), "end of data"))
3913 // Allow exceptions from under-length message on vRecv
3914 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());
3916 else if (strstr(e.what(), "size too large"))
3918 // Allow exceptions from over-long size
3919 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3923 PrintExceptionContinue(&e, "ProcessMessages()");
3926 catch (std::exception& e) {
3927 PrintExceptionContinue(&e, "ProcessMessages()");
3929 PrintExceptionContinue(NULL, "ProcessMessages()");
3933 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3941 bool SendMessages(CNode* pto, bool fSendTrickle)
3943 TRY_LOCK(cs_main, lockMain);
3945 // Don't send anything until we get their version message
3946 if (pto->nVersion == 0)
3949 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3951 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
3953 if (pto->nVersion > BIP0031_VERSION)
3954 pto->PushMessage("ping", nonce);
3956 pto->PushMessage("ping");
3960 if (pto->fStartSync) {
3961 pto->fStartSync = false;
3962 pto->PushGetBlocks(pindexBest, uint256(0));
3965 // Resend wallet transactions that haven't gotten in a block yet
3966 ResendWalletTransactions();
3968 // Address refresh broadcast
3969 static int64_t nLastRebroadcast;
3970 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > nBroadcastInterval))
3974 BOOST_FOREACH(CNode* pnode, vNodes)
3976 // Periodically clear setAddrKnown to allow refresh broadcasts
3977 if (nLastRebroadcast)
3978 pnode->setAddrKnown.clear();
3980 // Rebroadcast our address
3983 CAddress addr = GetLocalAddress(&pnode->addr);
3984 if (addr.IsRoutable())
3985 pnode->PushAddress(addr);
3989 nLastRebroadcast = GetTime();
3997 vector<CAddress> vAddr;
3998 vAddr.reserve(pto->vAddrToSend.size());
3999 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4001 // returns true if wasn't already contained in the set
4002 if (pto->setAddrKnown.insert(addr).second)
4004 vAddr.push_back(addr);
4005 // receiver rejects addr messages larger than 1000
4006 if (vAddr.size() >= 1000)
4008 pto->PushMessage("addr", vAddr);
4013 pto->vAddrToSend.clear();
4015 pto->PushMessage("addr", vAddr);
4020 // Message: inventory
4023 vector<CInv> vInvWait;
4025 LOCK(pto->cs_inventory);
4026 vInv.reserve(pto->vInventoryToSend.size());
4027 vInvWait.reserve(pto->vInventoryToSend.size());
4028 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4030 if (pto->setInventoryKnown.count(inv))
4033 // trickle out tx inv to protect privacy
4034 if (inv.type == MSG_TX && !fSendTrickle)
4036 // 1/4 of tx invs blast to all immediately
4037 static uint256 hashSalt;
4039 hashSalt = GetRandHash();
4040 uint256 hashRand = inv.hash ^ hashSalt;
4041 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4042 bool fTrickleWait = ((hashRand & 3) != 0);
4044 // always trickle our own transactions
4048 if (GetTransaction(inv.hash, wtx))
4050 fTrickleWait = true;
4055 vInvWait.push_back(inv);
4060 // returns true if wasn't already contained in the set
4061 if (pto->setInventoryKnown.insert(inv).second)
4063 vInv.push_back(inv);
4064 if (vInv.size() >= 1000)
4066 pto->PushMessage("inv", vInv);
4071 pto->vInventoryToSend = vInvWait;
4074 pto->PushMessage("inv", vInv);
4080 vector<CInv> vGetData;
4081 int64_t nNow = GetTime() * 1000000;
4083 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4085 const CInv& inv = (*pto->mapAskFor.begin()).second;
4086 if (!AlreadyHave(txdb, inv))
4089 printf("sending getdata: %s\n", inv.ToString().c_str());
4090 vGetData.push_back(inv);
4091 if (vGetData.size() >= 1000)
4093 pto->PushMessage("getdata", vGetData);
4096 mapAlreadyAskedFor[inv] = nNow;
4098 pto->mapAskFor.erase(pto->mapAskFor.begin());
4100 if (!vGetData.empty())
4101 pto->PushMessage("getdata", vGetData);