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"
9 #include "txdb-leveldb.h"
11 #include "interface.h"
12 #include "checkqueue.h"
14 #include <boost/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
24 CCriticalSection cs_setpwalletRegistered;
25 set<CWallet*> setpwalletRegistered;
27 CCriticalSection cs_main;
30 unsigned int nTransactionsUpdated = 0;
32 map<uint256, CBlockIndex*> mapBlockIndex;
33 set<pair<COutPoint, unsigned int> > setStakeSeen;
35 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
36 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
37 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
38 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
39 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
41 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
43 unsigned int nStakeMinAge = 30 * nOneDay; // 30 days as zero time weight
44 unsigned int nStakeMaxAge = 90 * nOneDay; // 90 days as full weight
45 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
46 unsigned int nModifierInterval = 6 * nOneHour; // time to elapse before new modifier is computed
48 int nCoinbaseMaturity = 500;
50 CBlockIndex* pindexGenesisBlock = NULL;
53 uint256 nBestChainTrust = 0;
54 uint256 nBestInvalidTrust = 0;
56 uint256 hashBestChain = 0;
57 CBlockIndex* pindexBest = NULL;
58 int64_t nTimeBestReceived = 0;
59 int nScriptCheckThreads = 0;
61 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
63 map<uint256, CBlock*> mapOrphanBlocks;
64 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
65 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
66 map<uint256, uint256> mapProofOfStake;
68 map<uint256, CTransaction> mapOrphanTransactions;
69 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
71 // Constant stuff for coinbase transactions we create:
72 CScript COINBASE_FLAGS;
74 const string strMessageMagic = "NovaCoin Signed Message:\n";
77 int64_t nTransactionFee = MIN_TX_FEE;
78 int64_t nMinimumInputValue = MIN_TXOUT_AMOUNT;
80 // Ping and address broadcast intervals
81 int64_t nPingInterval = 30 * 60;
83 extern enum Checkpoints::CPMode CheckpointsMode;
85 //////////////////////////////////////////////////////////////////////////////
87 // dispatching functions
90 // These functions dispatch to one or all registered wallets
93 void RegisterWallet(CWallet* pwalletIn)
96 LOCK(cs_setpwalletRegistered);
97 setpwalletRegistered.insert(pwalletIn);
101 void UnregisterWallet(CWallet* pwalletIn)
104 LOCK(cs_setpwalletRegistered);
105 setpwalletRegistered.erase(pwalletIn);
109 // check whether the passed transaction is from us
110 bool static IsFromMe(CTransaction& tx)
112 for (CWallet* pwallet : setpwalletRegistered)
113 if (pwallet->IsFromMe(tx))
118 // erases transaction with the given hash from all wallets
119 void static EraseFromWallets(uint256 hash)
121 for (CWallet* pwallet : setpwalletRegistered)
122 pwallet->EraseFromWallet(hash);
125 // make sure all wallets know about the given transaction, in the given block
126 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
130 // wallets need to refund inputs when disconnecting coinstake
131 if (tx.IsCoinStake())
133 for (CWallet* pwallet : setpwalletRegistered)
134 if (pwallet->IsFromMe(tx))
135 pwallet->DisableTransaction(tx);
140 for (CWallet* pwallet : setpwalletRegistered)
141 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
144 // notify wallets about a new best chain
145 void static SetBestChain(const CBlockLocator& loc)
147 for (CWallet* pwallet : setpwalletRegistered)
148 pwallet->SetBestChain(loc);
151 // notify wallets about an updated transaction
152 void static UpdatedTransaction(const uint256& hashTx)
154 for (CWallet* pwallet : setpwalletRegistered)
155 pwallet->UpdatedTransaction(hashTx);
159 void static PrintWallets(const CBlock& block)
161 for (CWallet* pwallet : setpwalletRegistered)
162 pwallet->PrintWallet(block);
165 // notify wallets about an incoming inventory (for request counts)
166 void static Inventory(const uint256& hash)
168 for (CWallet* pwallet : setpwalletRegistered)
169 pwallet->Inventory(hash);
172 // ask wallets to resend their transactions
173 void ResendWalletTransactions(bool fForceResend)
175 for (CWallet* pwallet : setpwalletRegistered)
176 pwallet->ResendWalletTransactions(fForceResend);
185 //////////////////////////////////////////////////////////////////////////////
187 // mapOrphanTransactions
190 bool AddOrphanTx(const CTransaction& tx)
192 uint256 hash = tx.GetHash();
193 if (mapOrphanTransactions.count(hash))
196 // Ignore big transactions, to avoid a
197 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
198 // large transaction with a missing parent then we assume
199 // it will rebroadcast it later, after the parent transaction(s)
200 // have been mined or received.
201 // 10,000 orphans, each of which is at most 5,000 bytes big is
202 // at most 500 megabytes of orphans:
204 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
208 printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
212 mapOrphanTransactions[hash] = tx;
213 for (const CTxIn& txin : tx.vin)
214 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
216 printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
217 mapOrphanTransactions.size());
221 void static EraseOrphanTx(uint256 hash)
223 if (!mapOrphanTransactions.count(hash))
225 const CTransaction& tx = mapOrphanTransactions[hash];
226 for (const CTxIn& txin : tx.vin)
228 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
229 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
230 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
232 mapOrphanTransactions.erase(hash);
235 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
237 unsigned int nEvicted = 0;
238 while (mapOrphanTransactions.size() > nMaxOrphans)
240 // Evict a random orphan:
241 uint256 randomhash = GetRandHash();
242 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
243 if (it == mapOrphanTransactions.end())
244 it = mapOrphanTransactions.begin();
245 EraseOrphanTx(it->first);
257 //////////////////////////////////////////////////////////////////////////////
259 // CTransaction and CTxIndex
262 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
265 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
267 if (!ReadFromDisk(txindexRet.pos))
269 if (prevout.n >= vout.size())
277 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
280 return ReadFromDisk(txdb, prevout, txindex);
283 bool CTransaction::ReadFromDisk(COutPoint prevout)
287 return ReadFromDisk(txdb, prevout, txindex);
290 bool CTransaction::IsStandard(string& strReason) const
292 if (nVersion > CTransaction::CURRENT_VERSION)
294 strReason = "version";
298 unsigned int nDataOut = 0;
299 txnouttype whichType;
300 for (const CTxIn& txin : vin)
302 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
303 // keys. (remember the 520 byte limit on redeemScript size) That works
304 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
305 // bytes of scriptSig, which we round off to 1650 bytes for some minor
306 // future-proofing. That's also enough to spend a 20-of-20
307 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
308 // considered standard)
309 if (txin.scriptSig.size() > 1650)
311 strReason = "scriptsig-size";
314 if (!txin.scriptSig.IsPushOnly())
316 strReason = "scriptsig-not-pushonly";
319 if (!txin.scriptSig.HasCanonicalPushes()) {
320 strReason = "txin-scriptsig-not-canonicalpushes";
324 for (const CTxOut& txout : vout) {
325 if (!::IsStandard(txout.scriptPubKey, whichType)) {
326 strReason = "scriptpubkey";
329 if (whichType == TX_NULL_DATA)
332 if (txout.nValue == 0) {
333 strReason = "txout-value=0";
336 if (!txout.scriptPubKey.HasCanonicalPushes()) {
337 strReason = "txout-scriptsig-not-canonicalpushes";
343 // only one OP_RETURN txout is permitted
345 strReason = "multi-op-return";
353 // Check transaction inputs, and make sure any
354 // pay-to-script-hash transactions are evaluating IsStandard scripts
356 // Why bother? To avoid denial-of-service attacks; an attacker
357 // can submit a standard HASH... OP_EQUAL transaction,
358 // which will get accepted into blocks. The redemption
359 // script can be anything; an attacker could use a very
360 // expensive-to-check-upon-redemption script like:
361 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
363 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
366 return true; // Coinbases don't use vin normally
368 for (unsigned int i = 0; i < vin.size(); i++)
370 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
372 vector<vector<unsigned char> > vSolutions;
373 txnouttype whichType;
374 // get the scriptPubKey corresponding to this input:
375 const CScript& prevScript = prev.scriptPubKey;
376 if (!Solver(prevScript, whichType, vSolutions))
378 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
379 if (nArgsExpected < 0)
382 // Transactions with extra stuff in their scriptSigs are
383 // non-standard. Note that this EvalScript() call will
384 // be quick, because if there are any operations
385 // beside "push data" in the scriptSig the
386 // IsStandard() call returns false
387 vector<vector<unsigned char> > stack;
388 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
391 if (whichType == TX_SCRIPTHASH)
395 CScript subscript(stack.back().begin(), stack.back().end());
396 vector<vector<unsigned char> > vSolutions2;
397 txnouttype whichType2;
398 if (!Solver(subscript, whichType2, vSolutions2))
400 if (whichType2 == TX_SCRIPTHASH)
404 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
407 nArgsExpected += tmpExpected;
410 if (stack.size() != (unsigned int)nArgsExpected)
418 CTransaction::GetLegacySigOpCount() const
420 unsigned int nSigOps = 0;
423 // Coinbase scriptsigs are never executed, so there is
424 // no sense in calculation of sigops.
425 for (const CTxIn& txin : vin)
427 nSigOps += txin.scriptSig.GetSigOpCount(false);
430 for (const CTxOut& txout : vout)
432 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
437 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
450 // Load the block this tx is in
452 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
454 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
459 // Update the tx's hashBlock
460 hashBlock = pblock->GetHash();
462 // Locate the transaction
463 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
464 if (pblock->vtx[nIndex] == *(CTransaction*)this)
466 if (nIndex == (int)pblock->vtx.size())
468 vMerkleBranch.clear();
470 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
474 // Fill in merkle branch
475 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
478 // Is the tx in a block that's in the main chain
479 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
480 if (mi == mapBlockIndex.end())
482 const CBlockIndex* pindex = (*mi).second;
483 if (!pindex || !pindex->IsInMainChain())
486 return pindexBest->nHeight - pindex->nHeight + 1;
489 bool CTransaction::CheckTransaction() const
491 // Basic checks that don't depend on any context
493 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
495 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
497 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
498 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
500 // Check for negative or overflow output values
501 int64_t nValueOut = 0;
502 for (unsigned int i = 0; i < vout.size(); i++)
504 const CTxOut& txout = vout[i];
505 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
506 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
508 if (txout.nValue < 0)
509 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
510 if (txout.nValue > MAX_MONEY)
511 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
512 nValueOut += txout.nValue;
513 if (!MoneyRange(nValueOut))
514 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
517 // Check for duplicate inputs
518 set<COutPoint> vInOutPoints;
519 for (const CTxIn& txin : vin)
521 if (vInOutPoints.count(txin.prevout))
523 vInOutPoints.insert(txin.prevout);
528 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
529 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
533 for (const CTxIn& txin : vin)
534 if (txin.prevout.IsNull())
535 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
541 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
543 int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
547 // Enforce 0.01 as minimum fee for coinstake
549 nMinRelayTxFee = CENT;
552 // Base fee is either nMinTxFee or nMinRelayTxFee
553 int64_t nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
555 unsigned int nNewBlockSize = nBlockSize + nBytes;
556 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
562 // Transactions under 1K are free
568 // Free transaction area
569 if (nNewBlockSize < 27000)
574 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
575 // each non empty output which is less than 0.01
577 // It's safe to ignore empty outputs here, because these inputs are allowed
578 // only for coinbase and coinstake transactions.
579 for (const CTxOut& txout : vout)
580 if (txout.nValue < CENT && !txout.IsEmpty())
583 // Raise the price as the block approaches full
584 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
586 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
588 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
591 if (!MoneyRange(nMinFee))
598 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
599 bool* pfMissingInputs)
602 *pfMissingInputs = false;
604 // Time (prevent mempool memory exhaustion attack)
605 if (tx.nTime > FutureDrift(GetAdjustedTime()))
606 return tx.DoS(10, error("CTxMemPool::accept() : transaction timestamp is too far in the future"));
608 if (!tx.CheckTransaction())
609 return error("CTxMemPool::accept() : CheckTransaction failed");
611 // Coinbase is only valid in a block, not as a loose transaction
613 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
615 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
616 if (tx.IsCoinStake())
617 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
619 // To help v0.1.5 clients who would see it as a negative number
620 if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
621 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
623 // Rather not work on nonstandard transactions (unless -testnet)
625 if (!fTestNet && !tx.IsStandard(strNonStd))
626 return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
628 // Do we already have it?
629 uint256 hash = tx.GetHash();
632 if (mapTx.count(hash))
636 if (txdb.ContainsTx(hash))
639 // Check for conflicts with in-memory transactions
640 CTransaction* ptxOld = NULL;
641 for (unsigned int i = 0; i < tx.vin.size(); i++)
643 COutPoint outpoint = tx.vin[i].prevout;
644 if (mapNextTx.count(outpoint))
646 // Disable replacement feature for now
649 // Allow replacing with a newer version of the same transaction
652 ptxOld = mapNextTx[outpoint].ptx;
653 if (ptxOld->IsFinal())
655 if (!tx.IsNewerThan(*ptxOld))
657 for (unsigned int i = 0; i < tx.vin.size(); i++)
659 COutPoint outpoint = tx.vin[i].prevout;
660 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
670 map<uint256, CTxIndex> mapUnused;
671 bool fInvalid = false;
672 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
675 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
677 *pfMissingInputs = true;
681 // Check for non-standard pay-to-script-hash in inputs
682 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
683 return error("CTxMemPool::accept() : nonstandard transaction input");
685 // Note: if you modify this code to accept non-standard transactions, then
686 // you should add code here to check that the transaction does a
687 // reasonable number of ECDSA signature verifications.
689 int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
690 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
692 // Don't accept it if it can't get into a block
693 int64_t txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
694 if (nFees < txMinFee)
695 return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
696 hash.ToString().c_str(),
699 // Continuously rate-limit free transactions
700 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
701 // be annoying or make others' transactions take longer to confirm.
702 if (nFees < MIN_RELAY_TX_FEE)
704 static CCriticalSection cs;
705 static double dFreeCount;
706 static int64_t nLastTime;
707 int64_t nNow = GetTime();
711 // Use an exponentially decaying ~10-minute window:
712 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
714 // -limitfreerelay unit is thousand-bytes-per-minute
715 // At default rate it would take over a month to fill 1GB
716 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
717 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
719 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
724 // Check against previous transactions
725 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
726 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, STRICT_FLAGS))
728 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
732 // Store transaction in memory
737 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
740 addUnchecked(hash, tx);
743 ///// are we sure this is ok when loading transactions or restoring block txes
744 // If updated, erase old tx from wallet
746 EraseFromWallets(ptxOld->GetHash());
748 printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
749 hash.ToString().substr(0,10).c_str(),
754 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
756 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
759 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
761 // Add to memory pool without checking anything. Don't call this directly,
762 // call CTxMemPool::accept to properly check the transaction first.
765 for (unsigned int i = 0; i < tx.vin.size(); i++)
766 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
767 nTransactionsUpdated++;
773 bool CTxMemPool::remove(CTransaction &tx)
775 // Remove transaction from memory pool
778 uint256 hash = tx.GetHash();
779 if (mapTx.count(hash))
781 for (const CTxIn& txin : tx.vin)
782 mapNextTx.erase(txin.prevout);
784 nTransactionsUpdated++;
790 void CTxMemPool::clear()
795 ++nTransactionsUpdated;
798 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
803 vtxid.reserve(mapTx.size());
804 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
805 vtxid.push_back((*mi).first);
811 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
813 if (hashBlock == 0 || nIndex == -1)
816 // Find the block it claims to be in
817 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
818 if (mi == mapBlockIndex.end())
820 CBlockIndex* pindex = (*mi).second;
821 if (!pindex || !pindex->IsInMainChain())
824 // Make sure the merkle branch connects to this block
825 if (!fMerkleVerified)
827 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
829 fMerkleVerified = true;
833 return pindexBest->nHeight - pindex->nHeight + 1;
837 int CMerkleTx::GetBlocksToMaturity() const
839 if (!(IsCoinBase() || IsCoinStake()))
841 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
845 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
849 if (!IsInMainChain() && !ClientConnectInputs())
851 return CTransaction::AcceptToMemoryPool(txdb, false);
855 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
859 bool CMerkleTx::AcceptToMemoryPool()
862 return AcceptToMemoryPool(txdb);
867 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
872 // Add previous supporting transactions first
873 for (CMerkleTx& tx : vtxPrev)
875 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
877 uint256 hash = tx.GetHash();
878 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
879 tx.AcceptToMemoryPool(txdb, fCheckInputs);
882 return AcceptToMemoryPool(txdb, fCheckInputs);
887 bool CWalletTx::AcceptWalletTransaction()
890 return AcceptWalletTransaction(txdb);
893 int CTxIndex::GetDepthInMainChain() const
897 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
899 // Find the block in the index
900 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
901 if (mi == mapBlockIndex.end())
903 CBlockIndex* pindex = (*mi).second;
904 if (!pindex || !pindex->IsInMainChain())
906 return 1 + nBestHeight - pindex->nHeight;
909 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
910 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
916 if (mempool.exists(hash))
918 tx = mempool.lookup(hash);
924 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
927 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
928 hashBlock = block.GetHash();
942 //////////////////////////////////////////////////////////////////////////////
944 // CBlock and CBlockIndex
947 static CBlockIndex* pblockindexFBBHLast;
948 CBlockIndex* FindBlockByHeight(int nHeight)
950 CBlockIndex *pblockindex;
951 if (nHeight < nBestHeight / 2)
952 pblockindex = pindexGenesisBlock;
954 pblockindex = pindexBest;
955 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
956 pblockindex = pblockindexFBBHLast;
957 while (pblockindex->nHeight > nHeight)
958 pblockindex = pblockindex->pprev;
959 while (pblockindex->nHeight < nHeight)
960 pblockindex = pblockindex->pnext;
961 pblockindexFBBHLast = pblockindex;
965 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
967 if (!fReadTransactions)
969 *this = pindex->GetBlockHeader();
972 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
974 if (GetHash() != pindex->GetBlockHash())
975 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
979 uint256 static GetOrphanRoot(const CBlock* pblock)
981 // Work back to the first block in the orphan chain
982 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
983 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
984 return pblock->GetHash();
987 // ppcoin: find block wanted by given orphan block
988 uint256 WantedByOrphan(const CBlock* pblockOrphan)
990 // Work back to the first block in the orphan chain
991 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
992 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
993 return pblockOrphan->hashPrevBlock;
996 // select stake target limit according to hard-coded conditions
997 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
999 if(fTestNet) // separate proof of stake target limit for testnet
1000 return bnProofOfStakeLimit;
1001 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1002 return bnProofOfStakeLimit;
1003 if(nHeight + 1 > 15000) // 24 bits since block 15000
1004 return bnProofOfStakeLegacyLimit;
1005 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1006 return bnProofOfStakeHardLimit;
1008 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1011 // miner's coin base reward based on nBits
1012 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees)
1014 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1017 bnTarget.SetCompact(nBits);
1018 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1019 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1021 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1022 // A reasonably continuous curve is used to avoid shock to market
1023 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1025 // Human readable form:
1027 // nSubsidy = 100 / (diff ^ 1/6)
1029 // Please note that we're using bisection to find an approximate solutuion
1030 CBigNum bnLowerBound = CENT;
1031 CBigNum bnUpperBound = bnSubsidyLimit;
1032 while (bnLowerBound + CENT <= bnUpperBound)
1034 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1035 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1036 bnUpperBound = bnMidValue;
1038 bnLowerBound = bnMidValue;
1041 int64_t nSubsidy = bnUpperBound.getuint64();
1043 nSubsidy = (nSubsidy / CENT) * CENT;
1044 if (fDebug && GetBoolArg("-printcreation"))
1045 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1047 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1050 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1051 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1053 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1055 // Stage 2 of emission process is mostly PoS-based.
1057 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1059 bnTarget.SetCompact(nBits);
1060 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1061 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1063 // A reasonably continuous curve is used to avoid shock to market
1065 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1066 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1067 bnMidPart, bnRewardPart;
1069 while (bnLowerBound + CENT <= bnUpperBound)
1071 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1074 // Reward for coin-year is cut in half every 8x multiply of PoS difficulty
1076 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1078 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1081 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1082 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1084 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1085 bnUpperBound = bnMidValue;
1087 bnLowerBound = bnMidValue;
1090 nRewardCoinYear = bnUpperBound.getuint64();
1091 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1094 return nRewardCoinYear;
1096 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1098 // Set reasonable reward limit for large inputs
1100 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1102 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1103 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1105 nSubsidy = min(nSubsidy, nSubsidyLimit);
1107 if (fDebug && GetBoolArg("-printcreation"))
1108 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1113 static const int64_t nTargetTimespan = 7 * nOneDay; // one week
1115 // get proof of work blocks max spacing according to hard-coded conditions
1116 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1118 if(nTime > TARGETS_SWITCH_TIME)
1119 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1122 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1124 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1128 // maximum nBits value could possible be required nTime after
1130 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1133 bnResult.SetCompact(nBase);
1135 while (nTime > 0 && bnResult < bnTargetLimit)
1137 // Maximum 200% adjustment per day...
1141 if (bnResult > bnTargetLimit)
1142 bnResult = bnTargetLimit;
1143 return bnResult.GetCompact();
1147 // minimum amount of work that could possibly be required nTime after
1148 // minimum proof-of-work required was nBase
1150 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1152 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1156 // minimum amount of stake that could possibly be required nTime after
1157 // minimum proof-of-stake required was nBase
1159 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1161 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1165 // ppcoin: find last block index up to pindex
1166 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1168 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1169 pindex = pindex->pprev;
1173 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1175 if (pindexLast == NULL)
1176 return bnProofOfWorkLimit.GetCompact(); // genesis block
1178 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1180 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1181 if (pindexPrev->pprev == NULL)
1182 return bnTargetLimit.GetCompact(); // first block
1183 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1184 if (pindexPrevPrev->pprev == NULL)
1185 return bnTargetLimit.GetCompact(); // second block
1187 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1189 // ppcoin: target change every block
1190 // ppcoin: retarget with exponential moving toward target spacing
1192 bnNew.SetCompact(pindexPrev->nBits);
1193 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1194 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1195 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1196 bnNew /= ((nInterval + 1) * nTargetSpacing);
1198 if (bnNew > bnTargetLimit)
1199 bnNew = bnTargetLimit;
1201 return bnNew.GetCompact();
1204 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1207 bnTarget.SetCompact(nBits);
1210 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1211 return error("CheckProofOfWork() : nBits below minimum work");
1213 // Check proof of work matches claimed amount
1214 if (hash > bnTarget.getuint256())
1215 return error("CheckProofOfWork() : hash doesn't match nBits");
1220 // Return maximum amount of blocks that other nodes claim to have
1221 int GetNumBlocksOfPeers()
1223 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1226 bool IsInitialBlockDownload()
1228 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1230 static int64_t nLastUpdate;
1231 static CBlockIndex* pindexLastBest;
1232 int64_t nCurrentTime = GetTime();
1233 if (pindexBest != pindexLastBest)
1235 pindexLastBest = pindexBest;
1236 nLastUpdate = nCurrentTime;
1238 return (nCurrentTime - nLastUpdate < 10 &&
1239 pindexBest->GetBlockTime() < nCurrentTime - nOneDay);
1242 void static InvalidChainFound(CBlockIndex* pindexNew)
1244 if (pindexNew->nChainTrust > nBestInvalidTrust)
1246 nBestInvalidTrust = pindexNew->nChainTrust;
1247 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1248 uiInterface.NotifyBlocksChanged();
1251 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1252 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1254 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1255 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1256 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1257 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1258 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1259 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1260 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1261 nBestBlockTrust.Get64(),
1262 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1266 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1268 nTime = max(GetBlockTime(), GetAdjustedTime());
1281 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1283 // Relinquish previous transactions' spent pointers
1286 for (const CTxIn& txin : vin)
1288 COutPoint prevout = txin.prevout;
1290 // Get prev txindex from disk
1292 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1293 return error("DisconnectInputs() : ReadTxIndex failed");
1295 if (prevout.n >= txindex.vSpent.size())
1296 return error("DisconnectInputs() : prevout.n out of range");
1298 // Mark outpoint as not spent
1299 txindex.vSpent[prevout.n].SetNull();
1302 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1303 return error("DisconnectInputs() : UpdateTxIndex failed");
1307 // Remove transaction from index
1308 // This can fail if a duplicate of this transaction was in a chain that got
1309 // reorganized away. This is only possible if this transaction was completely
1310 // spent, so erasing it would be a no-op anyway.
1311 txdb.EraseTxIndex(*this);
1317 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1318 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1320 // FetchInputs can return false either because we just haven't seen some inputs
1321 // (in which case the transaction should be stored as an orphan)
1322 // or because the transaction is malformed (in which case the transaction should
1323 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1327 return true; // Coinbase transactions have no inputs to fetch.
1329 for (unsigned int i = 0; i < vin.size(); i++)
1331 COutPoint prevout = vin[i].prevout;
1332 if (inputsRet.count(prevout.hash))
1333 continue; // Got it already
1336 CTxIndex& txindex = inputsRet[prevout.hash].first;
1338 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1340 // Get txindex from current proposed changes
1341 txindex = mapTestPool.find(prevout.hash)->second;
1345 // Read txindex from txdb
1346 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1348 if (!fFound && (fBlock || fMiner))
1349 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());
1352 CTransaction& txPrev = inputsRet[prevout.hash].second;
1353 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1355 // Get prev tx from single transactions in memory
1358 if (!mempool.exists(prevout.hash))
1359 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());
1360 txPrev = mempool.lookup(prevout.hash);
1363 txindex.vSpent.resize(txPrev.vout.size());
1367 // Get prev tx from disk
1368 if (!txPrev.ReadFromDisk(txindex.pos))
1369 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1373 // Make sure all prevout.n indexes are valid:
1374 for (unsigned int i = 0; i < vin.size(); i++)
1376 const COutPoint prevout = vin[i].prevout;
1377 assert(inputsRet.count(prevout.hash) != 0);
1378 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1379 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1380 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1382 // Revisit this if/when transaction replacement is implemented and allows
1385 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()));
1392 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1394 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1395 if (mi == inputs.end())
1396 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1398 const CTransaction& txPrev = (mi->second).second;
1399 if (input.prevout.n >= txPrev.vout.size())
1400 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1402 return txPrev.vout[input.prevout.n];
1405 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1410 int64_t nResult = 0;
1411 for (unsigned int i = 0; i < vin.size(); i++)
1413 nResult += GetOutputFor(vin[i], inputs).nValue;
1419 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1424 unsigned int nSigOps = 0;
1425 for (unsigned int i = 0; i < vin.size(); i++)
1427 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1428 if (prevout.scriptPubKey.IsPayToScriptHash())
1429 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1434 bool CScriptCheck::operator()() const {
1435 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1436 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1437 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1441 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1443 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1446 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1447 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1449 // Take over previous transactions' spent pointers
1450 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1451 // fMiner is true when called from the internal bitcoin miner
1452 // ... both are false when called from CTransaction::AcceptToMemoryPool
1456 int64_t nValueIn = 0;
1458 for (unsigned int i = 0; i < vin.size(); i++)
1460 COutPoint prevout = vin[i].prevout;
1461 assert(inputs.count(prevout.hash) > 0);
1462 CTxIndex& txindex = inputs[prevout.hash].first;
1463 CTransaction& txPrev = inputs[prevout.hash].second;
1465 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1466 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()));
1468 // If prev is coinbase or coinstake, check that it's matured
1469 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1470 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1471 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1472 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1474 // ppcoin: check transaction timestamp
1475 if (txPrev.nTime > nTime)
1476 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1478 // Check for negative or overflow input values
1479 nValueIn += txPrev.vout[prevout.n].nValue;
1480 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1481 return DoS(100, error("ConnectInputs() : txin values out of range"));
1486 pvChecks->reserve(vin.size());
1488 // The first loop above does all the inexpensive checks.
1489 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1490 // Helps prevent CPU exhaustion attacks.
1491 for (unsigned int i = 0; i < vin.size(); i++)
1493 COutPoint prevout = vin[i].prevout;
1494 assert(inputs.count(prevout.hash) > 0);
1495 CTxIndex& txindex = inputs[prevout.hash].first;
1496 CTransaction& txPrev = inputs[prevout.hash].second;
1498 // Check for conflicts (double-spend)
1499 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1500 // for an attacker to attempt to split the network.
1501 if (!txindex.vSpent[prevout.n].IsNull())
1502 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());
1504 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1505 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1506 // still computed and checked, and any change will be caught at the next checkpoint.
1510 CScriptCheck check(txPrev, *this, i, flags, 0);
1513 pvChecks->push_back(CScriptCheck());
1514 check.swap(pvChecks->back());
1518 if (flags & STRICT_FLAGS)
1520 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1521 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1523 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1525 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1529 // Mark outpoints as spent
1530 txindex.vSpent[prevout.n] = posThisTx;
1533 if (fBlock || fMiner)
1535 mapTestPool[prevout.hash] = txindex;
1541 if (nTime > Checkpoints::GetLastCheckpointTime())
1543 unsigned int nTxSize = GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
1545 // coin stake tx earns reward instead of paying fee
1547 if (!GetCoinAge(txdb, nCoinAge))
1548 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1550 int64_t nReward = GetValueOut() - nValueIn;
1551 int64_t nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1553 if (nReward > nCalculatedReward)
1554 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1559 if (nValueIn < GetValueOut())
1560 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1562 // Tally transaction fees
1563 int64_t nTxFee = nValueIn - GetValueOut();
1565 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1568 if (!MoneyRange(nFees))
1569 return DoS(100, error("ConnectInputs() : nFees out of range"));
1577 bool CTransaction::ClientConnectInputs()
1582 // Take over previous transactions' spent pointers
1585 int64_t nValueIn = 0;
1586 for (unsigned int i = 0; i < vin.size(); i++)
1588 // Get prev tx from single transactions in memory
1589 COutPoint prevout = vin[i].prevout;
1590 if (!mempool.exists(prevout.hash))
1592 CTransaction& txPrev = mempool.lookup(prevout.hash);
1594 if (prevout.n >= txPrev.vout.size())
1598 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1599 return error("ClientConnectInputs() : VerifySignature failed");
1601 ///// this is redundant with the mempool.mapNextTx stuff,
1602 ///// not sure which I want to get rid of
1603 ///// this has to go away now that posNext is gone
1604 // // Check for conflicts
1605 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1606 // return error("ConnectInputs() : prev tx already used");
1608 // // Flag outpoints as used
1609 // txPrev.vout[prevout.n].posNext = posThisTx;
1611 nValueIn += txPrev.vout[prevout.n].nValue;
1613 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1614 return error("ClientConnectInputs() : txin values out of range");
1616 if (GetValueOut() > nValueIn)
1626 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1628 // Disconnect in reverse order
1629 for (int i = vtx.size()-1; i >= 0; i--)
1630 if (!vtx[i].DisconnectInputs(txdb))
1633 // Update block index on disk without changing it in memory.
1634 // The memory index structure will be changed after the db commits.
1637 CDiskBlockIndex blockindexPrev(pindex->pprev);
1638 blockindexPrev.hashNext = 0;
1639 if (!txdb.WriteBlockIndex(blockindexPrev))
1640 return error("DisconnectBlock() : WriteBlockIndex failed");
1643 // ppcoin: clean up wallet after disconnecting coinstake
1644 for (CTransaction& tx : vtx)
1645 SyncWithWallets(tx, this, false, false);
1650 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1652 void ThreadScriptCheck(void*) {
1653 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1654 RenameThread("novacoin-scriptch");
1655 scriptcheckqueue.Thread();
1656 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1659 void ThreadScriptCheckQuit() {
1660 scriptcheckqueue.Quit();
1663 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1665 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1666 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1669 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1670 // unless those are already completely spent.
1671 // If such overwrites are allowed, coinbases and transactions depending upon those
1672 // can be duplicated to remove the ability to spend the first instance -- even after
1673 // being sent to another address.
1674 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1675 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1676 // already refuses previously-known transaction ids entirely.
1677 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1678 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1679 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1680 // initial block download.
1681 bool fEnforceBIP30 = true; // Always active in NovaCoin
1682 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1684 //// issue here: it doesn't know the version
1685 unsigned int nTxPos;
1687 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1688 // 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
1691 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1693 map<uint256, CTxIndex> mapQueuedChanges;
1694 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1697 int64_t nValueIn = 0;
1698 int64_t nValueOut = 0;
1699 unsigned int nSigOps = 0;
1700 for (CTransaction& tx : vtx)
1702 uint256 hashTx = tx.GetHash();
1704 if (fEnforceBIP30) {
1705 CTxIndex txindexOld;
1706 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1707 for (CDiskTxPos &pos : txindexOld.vSpent)
1713 nSigOps += tx.GetLegacySigOpCount();
1714 if (nSigOps > MAX_BLOCK_SIGOPS)
1715 return DoS(100, error("ConnectBlock() : too many sigops"));
1717 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1719 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1721 MapPrevTx mapInputs;
1722 if (tx.IsCoinBase())
1723 nValueOut += tx.GetValueOut();
1727 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1730 // Add in sigops done by pay-to-script-hash inputs;
1731 // this is to prevent a "rogue miner" from creating
1732 // an incredibly-expensive-to-validate block.
1733 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1734 if (nSigOps > MAX_BLOCK_SIGOPS)
1735 return DoS(100, error("ConnectBlock() : too many sigops"));
1737 int64_t nTxValueIn = tx.GetValueIn(mapInputs);
1738 int64_t nTxValueOut = tx.GetValueOut();
1739 nValueIn += nTxValueIn;
1740 nValueOut += nTxValueOut;
1741 if (!tx.IsCoinStake())
1742 nFees += nTxValueIn - nTxValueOut;
1744 unsigned int nFlags = SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH;
1746 if (tx.nTime >= CHECKLOCKTIMEVERIFY_SWITCH_TIME) {
1747 nFlags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1750 if (tx.nTime >= CHECKSEQUENCEVERIFY_SWITCH_TIME) {
1751 nFlags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1754 std::vector<CScriptCheck> vChecks;
1755 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, nFlags, nScriptCheckThreads ? &vChecks : NULL))
1757 control.Add(vChecks);
1760 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1763 if (!control.Wait())
1764 return DoS(100, false);
1766 if (IsProofOfWork())
1768 int64_t nBlockReward = GetProofOfWorkReward(nBits, nFees);
1770 // Check coinbase reward
1771 if (vtx[0].GetValueOut() > nBlockReward)
1772 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1773 vtx[0].GetValueOut(),
1777 // track money supply and mint amount info
1778 pindex->nMint = nValueOut - nValueIn + nFees;
1779 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1780 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1781 return error("Connect() : WriteBlockIndex for pindex failed");
1783 // fees are not collected by proof-of-stake miners
1784 // fees are destroyed to compensate the entire network
1785 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1786 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
1791 // Write queued txindex changes
1792 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1794 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1795 return error("ConnectBlock() : UpdateTxIndex failed");
1798 // Update block index on disk without changing it in memory.
1799 // The memory index structure will be changed after the db commits.
1802 CDiskBlockIndex blockindexPrev(pindex->pprev);
1803 blockindexPrev.hashNext = pindex->GetBlockHash();
1804 if (!txdb.WriteBlockIndex(blockindexPrev))
1805 return error("ConnectBlock() : WriteBlockIndex failed");
1808 // Watch for transactions paying to me
1809 for (CTransaction& tx : vtx)
1810 SyncWithWallets(tx, this, true);
1816 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1818 printf("REORGANIZE\n");
1821 CBlockIndex* pfork = pindexBest;
1822 CBlockIndex* plonger = pindexNew;
1823 while (pfork != plonger)
1825 while (plonger->nHeight > pfork->nHeight)
1826 if ((plonger = plonger->pprev) == NULL)
1827 return error("Reorganize() : plonger->pprev is null");
1828 if (pfork == plonger)
1830 if ((pfork = pfork->pprev) == NULL)
1831 return error("Reorganize() : pfork->pprev is null");
1834 // List of what to disconnect
1835 vector<CBlockIndex*> vDisconnect;
1836 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1837 vDisconnect.push_back(pindex);
1839 // List of what to connect
1840 vector<CBlockIndex*> vConnect;
1841 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1842 vConnect.push_back(pindex);
1843 reverse(vConnect.begin(), vConnect.end());
1845 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());
1846 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());
1848 // Disconnect shorter branch
1849 vector<CTransaction> vResurrect;
1850 for (CBlockIndex* pindex : vDisconnect)
1853 if (!block.ReadFromDisk(pindex))
1854 return error("Reorganize() : ReadFromDisk for disconnect failed");
1855 if (!block.DisconnectBlock(txdb, pindex))
1856 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1858 // Queue memory transactions to resurrect
1859 for (const CTransaction& tx : block.vtx)
1860 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1861 vResurrect.push_back(tx);
1864 // Connect longer branch
1865 vector<CTransaction> vDelete;
1866 for (unsigned int i = 0; i < vConnect.size(); i++)
1868 CBlockIndex* pindex = vConnect[i];
1870 if (!block.ReadFromDisk(pindex))
1871 return error("Reorganize() : ReadFromDisk for connect failed");
1872 if (!block.ConnectBlock(txdb, pindex))
1875 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1878 // Queue memory transactions to delete
1879 for (const CTransaction& tx : block.vtx)
1880 vDelete.push_back(tx);
1882 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1883 return error("Reorganize() : WriteHashBestChain failed");
1885 // Make sure it's successfully written to disk before changing memory structure
1886 if (!txdb.TxnCommit())
1887 return error("Reorganize() : TxnCommit failed");
1889 // Disconnect shorter branch
1890 for (CBlockIndex* pindex : vDisconnect)
1892 pindex->pprev->pnext = NULL;
1894 // Connect longer branch
1895 for (CBlockIndex* pindex : vConnect)
1897 pindex->pprev->pnext = pindex;
1899 // Resurrect memory transactions that were in the disconnected branch
1900 for (CTransaction& tx : vResurrect)
1901 tx.AcceptToMemoryPool(txdb, false);
1903 // Delete redundant memory transactions that are in the connected branch
1904 for (CTransaction& tx : vDelete)
1907 printf("REORGANIZE: done\n");
1913 // Called from inside SetBestChain: attaches a block to the new best chain being built
1914 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1916 uint256 hash = GetHash();
1918 // Adding to current best branch
1919 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1922 InvalidChainFound(pindexNew);
1925 if (!txdb.TxnCommit())
1926 return error("SetBestChain() : TxnCommit failed");
1928 // Add to current best branch
1929 pindexNew->pprev->pnext = pindexNew;
1931 // Delete redundant memory transactions
1932 for (CTransaction& tx : vtx)
1938 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1940 uint256 hash = GetHash();
1942 if (!txdb.TxnBegin())
1943 return error("SetBestChain() : TxnBegin failed");
1945 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1947 txdb.WriteHashBestChain(hash);
1948 if (!txdb.TxnCommit())
1949 return error("SetBestChain() : TxnCommit failed");
1950 pindexGenesisBlock = pindexNew;
1952 else if (hashPrevBlock == hashBestChain)
1954 if (!SetBestChainInner(txdb, pindexNew))
1955 return error("SetBestChain() : SetBestChainInner failed");
1959 // the first block in the new chain that will cause it to become the new best chain
1960 CBlockIndex *pindexIntermediate = pindexNew;
1962 // list of blocks that need to be connected afterwards
1963 std::vector<CBlockIndex*> vpindexSecondary;
1965 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1966 // Try to limit how much needs to be done inside
1967 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1969 vpindexSecondary.push_back(pindexIntermediate);
1970 pindexIntermediate = pindexIntermediate->pprev;
1973 if (!vpindexSecondary.empty())
1974 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
1976 // Switch to new best branch
1977 if (!Reorganize(txdb, pindexIntermediate))
1980 InvalidChainFound(pindexNew);
1981 return error("SetBestChain() : Reorganize failed");
1984 // Connect further blocks
1985 for (std::vector<CBlockIndex*>::reverse_iterator rit = vpindexSecondary.rbegin(); rit != vpindexSecondary.rend(); ++rit)
1988 if (!block.ReadFromDisk(*rit))
1990 printf("SetBestChain() : ReadFromDisk failed\n");
1993 if (!txdb.TxnBegin()) {
1994 printf("SetBestChain() : TxnBegin 2 failed\n");
1997 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1998 if (!block.SetBestChainInner(txdb, *rit))
2003 // Update best block in wallet (so we can detect restored wallets)
2004 bool fIsInitialDownload = IsInitialBlockDownload();
2005 if (!fIsInitialDownload)
2007 const CBlockLocator locator(pindexNew);
2008 ::SetBestChain(locator);
2012 hashBestChain = hash;
2013 pindexBest = pindexNew;
2014 pblockindexFBBHLast = NULL;
2015 nBestHeight = pindexBest->nHeight;
2016 nBestChainTrust = pindexNew->nChainTrust;
2017 nTimeBestReceived = GetTime();
2018 nTransactionsUpdated++;
2020 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2022 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
2023 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2024 CBigNum(nBestChainTrust).ToString().c_str(),
2025 nBestBlockTrust.Get64(),
2026 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2028 // Check the version of the last 100 blocks to see if we need to upgrade:
2029 if (!fIsInitialDownload)
2032 const CBlockIndex* pindex = pindexBest;
2033 for (int i = 0; i < 100 && pindex != NULL; i++)
2035 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2037 pindex = pindex->pprev;
2040 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2041 if (nUpgraded > 100/2)
2042 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2043 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2046 std::string strCmd = GetArg("-blocknotify", "");
2048 if (!fIsInitialDownload && !strCmd.empty())
2050 boost::thread t(runCommand, regex_replace(strCmd, static_cast<std::regex>("%s"), hashBestChain.GetHex()));
2055 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2056 // Only those coins meeting minimum age requirement counts. As those
2057 // transactions not in main chain are not currently indexed so we
2058 // might not find out about their coin age. Older transactions are
2059 // guaranteed to be in main chain by sync-checkpoint. This rule is
2060 // introduced to help nodes establish a consistent view of the coin
2061 // age (trust score) of competing branches.
2062 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2064 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2070 for (const CTxIn& txin : vin)
2072 // First try finding the previous transaction in database
2073 CTransaction txPrev;
2075 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2076 continue; // previous transaction not in main chain
2077 if (nTime < txPrev.nTime)
2078 return false; // Transaction timestamp violation
2080 // Read block header
2082 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2083 return false; // unable to read block of previous transaction
2084 if (block.GetBlockTime() + nStakeMinAge > nTime)
2085 continue; // only count coins meeting min age requirement
2087 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
2088 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2090 if (fDebug && GetBoolArg("-printcoinage"))
2091 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2094 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / nOneDay;
2095 if (fDebug && GetBoolArg("-printcoinage"))
2096 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2097 nCoinAge = bnCoinDay.getuint64();
2101 // ppcoin: total coin age spent in block, in the unit of coin-days.
2102 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2107 for (const CTransaction& tx : vtx)
2109 uint64_t nTxCoinAge;
2110 if (tx.GetCoinAge(txdb, nTxCoinAge))
2111 nCoinAge += nTxCoinAge;
2116 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2118 if (fDebug && GetBoolArg("-printcoinage"))
2119 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2123 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2125 // Check for duplicate
2126 uint256 hash = GetHash();
2127 if (mapBlockIndex.count(hash))
2128 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2130 // Construct new block index object
2131 CBlockIndex* pindexNew = new(nothrow) CBlockIndex(nFile, nBlockPos, *this);
2133 return error("AddToBlockIndex() : new CBlockIndex failed");
2134 pindexNew->phashBlock = &hash;
2135 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2136 if (miPrev != mapBlockIndex.end())
2138 pindexNew->pprev = (*miPrev).second;
2139 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2142 // ppcoin: compute chain trust score
2143 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2145 // ppcoin: compute stake entropy bit for stake modifier
2146 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2147 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2149 // ppcoin: record proof-of-stake hash value
2150 if (pindexNew->IsProofOfStake())
2152 if (!mapProofOfStake.count(hash))
2153 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2154 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2157 // ppcoin: compute stake modifier
2158 uint64_t nStakeModifier = 0;
2159 bool fGeneratedStakeModifier = false;
2160 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2161 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2162 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2163 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2164 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2165 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2167 // Add to mapBlockIndex
2168 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2169 if (pindexNew->IsProofOfStake())
2170 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2171 pindexNew->phashBlock = &((*mi).first);
2173 // Write to disk block index
2175 if (!txdb.TxnBegin())
2177 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2178 if (!txdb.TxnCommit())
2182 if (pindexNew->nChainTrust > nBestChainTrust)
2183 if (!SetBestChain(txdb, pindexNew))
2186 if (pindexNew == pindexBest)
2188 // Notify UI to display prev block's coinbase if it was ours
2189 static uint256 hashPrevBestCoinBase;
2190 UpdatedTransaction(hashPrevBestCoinBase);
2191 hashPrevBestCoinBase = vtx[0].GetHash();
2194 static int8_t counter = 0;
2195 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2196 uiInterface.NotifyBlocksChanged();
2203 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2205 // These are checks that are independent of context
2206 // that can be verified before saving an orphan block.
2208 set<uint256> uniqueTx; // tx hashes
2209 unsigned int nSigOps = 0; // total sigops
2212 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2213 return DoS(100, error("CheckBlock() : size limits failed"));
2215 bool fProofOfStake = IsProofOfStake();
2217 // First transaction must be coinbase, the rest must not be
2218 if (!vtx[0].IsCoinBase())
2219 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2221 if (!vtx[0].CheckTransaction())
2222 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2224 uniqueTx.insert(vtx[0].GetHash());
2225 nSigOps += vtx[0].GetLegacySigOpCount();
2229 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2230 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2232 // nNonce must be zero for proof-of-stake blocks
2234 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2236 // Coinbase output should be empty if proof-of-stake block
2237 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2238 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2240 // Check coinstake timestamp
2241 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2242 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2244 // NovaCoin: check proof-of-stake block signature
2245 if (fCheckSig && !CheckBlockSignature())
2246 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2248 if (!vtx[1].CheckTransaction())
2249 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2251 uniqueTx.insert(vtx[1].GetHash());
2252 nSigOps += vtx[1].GetLegacySigOpCount();
2256 // Check proof of work matches claimed amount
2257 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2258 return DoS(50, error("CheckBlock() : proof of work failed"));
2261 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2262 return error("CheckBlock() : block timestamp too far in the future");
2264 // Check coinbase timestamp
2265 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2266 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2269 // Iterate all transactions starting from second for proof-of-stake block
2270 // or first for proof-of-work block
2271 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2273 const CTransaction& tx = vtx[i];
2275 // Reject coinbase transactions at non-zero index
2276 if (tx.IsCoinBase())
2277 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2279 // Reject coinstake transactions at index != 1
2280 if (tx.IsCoinStake())
2281 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2283 // Check transaction timestamp
2284 if (GetBlockTime() < (int64_t)tx.nTime)
2285 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2287 // Check transaction consistency
2288 if (!tx.CheckTransaction())
2289 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2291 // Add transaction hash into list of unique transaction IDs
2292 uniqueTx.insert(tx.GetHash());
2294 // Calculate sigops count
2295 nSigOps += tx.GetLegacySigOpCount();
2298 // Check for duplicate txids. This is caught by ConnectInputs(),
2299 // but catching it earlier avoids a potential DoS attack:
2300 if (uniqueTx.size() != vtx.size())
2301 return DoS(100, error("CheckBlock() : duplicate transaction"));
2303 // Reject block if validation would consume too much resources.
2304 if (nSigOps > MAX_BLOCK_SIGOPS)
2305 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2307 // Check merkle root
2308 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2309 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2314 bool CBlock::AcceptBlock()
2316 // Check for duplicate
2317 uint256 hash = GetHash();
2318 if (mapBlockIndex.count(hash))
2319 return error("AcceptBlock() : block already in mapBlockIndex");
2321 // Get prev block index
2322 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2323 if (mi == mapBlockIndex.end())
2324 return DoS(10, error("AcceptBlock() : prev block not found"));
2325 CBlockIndex* pindexPrev = (*mi).second;
2326 int nHeight = pindexPrev->nHeight+1;
2328 // Check proof-of-work or proof-of-stake
2329 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2330 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2332 int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
2333 int nMaxOffset = 12 * nOneHour; // 12 hours
2334 if (fTestNet || pindexPrev->nTime < 1450569600)
2335 nMaxOffset = 7 * nOneWeek; // One week (permanently on testNet or until 20 Dec, 2015 on mainNet)
2337 // Check timestamp against prev
2338 if (GetBlockTime() <= nMedianTimePast || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2339 return error("AcceptBlock() : block's timestamp is too early");
2341 // Don't accept blocks with future timestamps
2342 if (pindexPrev->nHeight > 1 && nMedianTimePast + nMaxOffset < GetBlockTime())
2343 return error("AcceptBlock() : block's timestamp is too far in the future");
2345 // Check that all transactions are finalized
2346 for (const CTransaction& tx : vtx)
2347 if (!tx.IsFinal(nHeight, GetBlockTime()))
2348 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2350 // Check that the block chain matches the known block chain up to a checkpoint
2351 if (!Checkpoints::CheckHardened(nHeight, hash))
2352 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2354 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2356 // Check that the block satisfies synchronized checkpoint
2357 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2358 return error("AcceptBlock() : rejected by synchronized checkpoint");
2360 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2361 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2363 // Enforce rule that the coinbase starts with serialized block height
2364 CScript expect = CScript() << nHeight;
2365 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2366 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2367 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2369 // Write block to history file
2370 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2371 return error("AcceptBlock() : out of disk space");
2372 unsigned int nFile = std::numeric_limits<unsigned int>::max();
2373 unsigned int nBlockPos = 0;
2374 if (!WriteToDisk(nFile, nBlockPos))
2375 return error("AcceptBlock() : WriteToDisk failed");
2376 if (!AddToBlockIndex(nFile, nBlockPos))
2377 return error("AcceptBlock() : AddToBlockIndex failed");
2379 // Relay inventory, but don't relay old inventory during initial block download
2380 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2381 if (hashBestChain == hash)
2384 for (CNode* pnode : vNodes)
2385 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2386 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2389 // ppcoin: check pending sync-checkpoint
2390 Checkpoints::AcceptPendingSyncCheckpoint();
2395 uint256 CBlockIndex::GetBlockTrust() const
2398 bnTarget.SetCompact(nBits);
2403 // Return 1 for the first 12 blocks
2404 if (pprev == NULL || pprev->nHeight < 12)
2407 const CBlockIndex* currentIndex = pprev;
2409 if(IsProofOfStake())
2411 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2413 // Return 1/3 of score if parent block is not the PoW block
2414 if (!pprev->IsProofOfWork())
2415 return (bnNewTrust / 3).getuint256();
2419 // Check last 12 blocks type
2420 while (pprev->nHeight - currentIndex->nHeight < 12)
2422 if (currentIndex->IsProofOfWork())
2424 currentIndex = currentIndex->pprev;
2427 // Return 1/3 of score if less than 3 PoW blocks found
2429 return (bnNewTrust / 3).getuint256();
2431 return bnNewTrust.getuint256();
2435 // Calculate work amount for block
2436 CBigNum bnPoWTrust = CBigNum(nPoWBase) / (bnTarget+1);
2438 // Set nPowTrust to 1 if PoW difficulty is too low
2442 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2444 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2445 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2446 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2450 // Check last 12 blocks type
2451 while (pprev->nHeight - currentIndex->nHeight < 12)
2453 if (currentIndex->IsProofOfStake())
2455 currentIndex = currentIndex->pprev;
2458 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2460 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2462 bnTarget.SetCompact(pprev->nBits);
2467 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2469 // Return nPoWTrust + full trust score for previous block nBits
2470 return (bnPoWTrust + bnNewTrust).getuint256();
2474 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2476 unsigned int nFound = 0;
2477 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2479 if (pstart->nVersion >= minVersion)
2481 pstart = pstart->pprev;
2483 return (nFound >= nRequired);
2486 bool static ReserealizeBlockSignature(CBlock* pblock)
2488 if (pblock->IsProofOfWork())
2490 pblock->vchBlockSig.clear();
2494 return CPubKey::ReserealizeSignature(pblock->vchBlockSig);
2497 bool static IsCanonicalBlockSignature(CBlock* pblock)
2499 if (pblock->IsProofOfWork())
2500 return pblock->vchBlockSig.empty();
2502 return IsDERSignature(pblock->vchBlockSig);
2505 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2507 // Check for duplicate
2508 uint256 hash = pblock->GetHash();
2509 if (mapBlockIndex.count(hash))
2510 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2511 if (mapOrphanBlocks.count(hash))
2512 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2514 // Check that block isn't listed as unconditionally banned.
2515 if (!Checkpoints::CheckBanned(hash)) {
2517 pfrom->Misbehaving(100);
2518 return error("ProcessBlock() : block %s is rejected by hard-coded banlist", hash.GetHex().substr(0,20).c_str());
2521 // Check proof-of-stake
2522 // Limited duplicity on stake: prevents block flood attack
2523 // Duplicate stake allowed only when there is orphan child block
2524 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2525 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());
2527 // Strip the garbage from newly received blocks, if we found some
2528 if (!IsCanonicalBlockSignature(pblock)) {
2529 if (!ReserealizeBlockSignature(pblock))
2530 printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2533 // Preliminary checks
2534 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2535 return error("ProcessBlock() : CheckBlock FAILED");
2537 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2538 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2540 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2541 int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2543 bnNewBlock.SetCompact(pblock->nBits);
2546 if (pblock->IsProofOfStake())
2547 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2549 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2551 if (bnNewBlock > bnRequired)
2554 pfrom->Misbehaving(100);
2555 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2560 // ppcoin: ask for pending sync-checkpoint if any
2561 if (!IsInitialBlockDownload())
2562 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2564 // If don't already have its previous block, shunt it off to holding area until we get it
2565 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2567 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2568 // ppcoin: check proof-of-stake
2569 if (pblock->IsProofOfStake())
2571 // Limited duplicity on stake: prevents block flood attack
2572 // Duplicate stake allowed only when there is orphan child block
2573 if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2574 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
2576 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2578 CBlock* pblock2 = new CBlock(*pblock);
2579 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2580 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2582 // Ask this guy to fill in what we're missing
2585 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2586 // ppcoin: getblocks may not obtain the ancestor block rejected
2587 // earlier by duplicate-stake check so we ask for it again directly
2588 if (!IsInitialBlockDownload())
2589 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2594 // ppcoin: verify hash target and signature of coinstake tx
2595 if (pblock->IsProofOfStake())
2597 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2598 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2600 // Having prev block in index should be enough for validation
2601 if (mapBlockIndex.count(pblock->hashPrevBlock))
2602 return error("ProcessBlock(): check proof-of-stake (%s, %d) failed for block %s\n", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
2604 // Orphan blocks should be validated later once all parents successfully added to local chain
2605 printf("ProcessBlock(): delaying proof-of-stake validation for orphan block %s\n", hash.ToString().c_str());
2606 return false; // do not error here as we expect this to happen here
2609 // Needed for AcceptBlock()
2610 if (!mapProofOfStake.count(hash))
2611 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2615 if (!pblock->AcceptBlock())
2616 return error("ProcessBlock() : AcceptBlock FAILED");
2618 // Process any orphan blocks that depended on this one
2619 vector<uint256> vWorkQueue;
2620 vWorkQueue.push_back(hash);
2621 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2623 uint256 hashPrev = vWorkQueue[i];
2624 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2625 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2628 CBlock* pblockOrphan = (*mi).second;
2629 uint256 hashOrphanBlock = pblockOrphan->GetHash();
2631 if (pblockOrphan->IsProofOfStake()) {
2632 // Check proof-of-stake and do other contextual
2633 // preparations before running AcceptBlock()
2634 uint256 hashOrphanProofOfStake = 0;
2635 uint256 targetOrphanProofOfStake = 0;
2637 if (CheckProofOfStake(pblockOrphan->vtx[1], pblockOrphan->nBits, hashOrphanProofOfStake, targetOrphanProofOfStake))
2639 // Needed for AcceptBlock()
2640 if (!mapProofOfStake.count(hashOrphanBlock))
2641 mapProofOfStake.insert(make_pair(hashOrphanBlock, hashOrphanProofOfStake));
2643 // Finally, we're ready to run AcceptBlock()
2644 if (pblockOrphan->AcceptBlock())
2645 vWorkQueue.push_back(hashOrphanBlock);
2646 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2649 // proof-of-work verification
2650 // is notoriously simpler
2651 if (pblockOrphan->AcceptBlock())
2652 vWorkQueue.push_back(hashOrphanBlock);
2655 mapOrphanBlocks.erase(hashOrphanBlock);
2656 delete pblockOrphan;
2659 mapOrphanBlocksByPrev.erase(hashPrev);
2662 printf("ProcessBlock: ACCEPTED\n");
2664 // ppcoin: if responsible for sync-checkpoint send it
2665 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2666 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2671 // ppcoin: check block signature
2672 bool CBlock::CheckBlockSignature() const
2674 if (vchBlockSig.empty())
2677 txnouttype whichType;
2678 vector<valtype> vSolutions;
2679 if (!Solver(vtx[1].vout[1].scriptPubKey, whichType, vSolutions))
2682 if (whichType == TX_PUBKEY)
2684 valtype& vchPubKey = vSolutions[0];
2685 CPubKey key(vchPubKey);
2688 return key.Verify(GetHash(), vchBlockSig);
2694 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2696 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
2698 // Check for nMinDiskSpace bytes (currently 50MB)
2699 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2702 string strMessage = _("Warning: Disk space is low!");
2703 strMiscWarning = strMessage;
2704 printf("*** %s\n", strMessage.c_str());
2705 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2712 static boost::filesystem::path BlockFilePath(unsigned int nFile)
2714 string strBlockFn = strprintf("blk%04u.dat", nFile);
2715 return GetDataDir() / strBlockFn;
2718 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2720 if ((nFile < 1) || (nFile == std::numeric_limits<uint32_t>::max()))
2722 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2725 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2727 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2736 static unsigned int nCurrentBlockFile = 1;
2738 FILE* AppendBlockFile(unsigned int& nFileRet)
2743 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2746 if (fseek(file, 0, SEEK_END) != 0)
2748 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2749 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2751 nFileRet = nCurrentBlockFile;
2755 nCurrentBlockFile++;
2759 void UnloadBlockIndex()
2761 mapBlockIndex.clear();
2762 setStakeSeen.clear();
2763 pindexGenesisBlock = NULL;
2765 nBestChainTrust = 0;
2766 nBestInvalidTrust = 0;
2771 bool LoadBlockIndex(bool fAllowNew)
2775 pchMessageStart[0] = 0xcd;
2776 pchMessageStart[1] = 0xf2;
2777 pchMessageStart[2] = 0xc0;
2778 pchMessageStart[3] = 0xef;
2780 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2781 nStakeMinAge = 2 * nOneHour; // test net min age is 2 hours
2782 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2783 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2784 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2791 if (!txdb.LoadBlockIndex())
2795 // Init with genesis block
2797 if (mapBlockIndex.empty())
2806 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2807 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2808 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2810 // vMerkleTree: 4cb33b3b6a
2814 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2815 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2816 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2818 // vMerkleTree: 4cb33b3b6a
2820 const string strTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2822 txNew.nTime = 1360105017;
2823 txNew.vin.resize(1);
2824 txNew.vout.resize(1);
2825 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>(strTimestamp.begin(), strTimestamp.end());
2826 txNew.vout[0].SetEmpty();
2828 block.vtx.push_back(txNew);
2829 block.hashPrevBlock = 0;
2830 block.hashMerkleRoot = block.BuildMerkleTree();
2832 block.nTime = 1360105017;
2833 block.nBits = bnProofOfWorkLimit.GetCompact();
2834 block.nNonce = !fTestNet ? 1575379 : 46534;
2837 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2839 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2840 assert(block.CheckBlock());
2842 // Start new block file
2844 unsigned int nBlockPos;
2845 if (!block.WriteToDisk(nFile, nBlockPos))
2846 return error("LoadBlockIndex() : writing genesis block to disk failed");
2847 if (!block.AddToBlockIndex(nFile, nBlockPos))
2848 return error("LoadBlockIndex() : genesis block not accepted");
2850 // initialize synchronized checkpoint
2851 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2852 return error("LoadBlockIndex() : failed to init sync checkpoint");
2854 // upgrade time set to zero if txdb initialized
2856 if (!txdb.WriteModifierUpgradeTime(0))
2857 return error("LoadBlockIndex() : failed to init upgrade info");
2858 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2864 string strPubKey = "";
2865 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2867 // write checkpoint master key to db
2869 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2870 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2871 if (!txdb.TxnCommit())
2872 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2873 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2874 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2877 // upgrade time set to zero if blocktreedb initialized
2878 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2880 if (nModifierUpgradeTime)
2881 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2883 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2887 nModifierUpgradeTime = GetTime();
2888 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2889 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2890 return error("LoadBlockIndex() : failed to write upgrade info");
2899 void PrintBlockTree()
2901 // pre-compute tree structure
2902 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2903 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2905 CBlockIndex* pindex = (*mi).second;
2906 mapNext[pindex->pprev].push_back(pindex);
2908 //while (rand() % 3 == 0)
2909 // mapNext[pindex->pprev].push_back(pindex);
2912 vector<pair<int, CBlockIndex*> > vStack;
2913 vStack.push_back(make_pair(0, pindexGenesisBlock));
2916 while (!vStack.empty())
2918 int nCol = vStack.back().first;
2919 CBlockIndex* pindex = vStack.back().second;
2922 // print split or gap
2923 if (nCol > nPrevCol)
2925 for (int i = 0; i < nCol-1; i++)
2929 else if (nCol < nPrevCol)
2931 for (int i = 0; i < nCol; i++)
2938 for (int i = 0; i < nCol; i++)
2943 block.ReadFromDisk(pindex);
2944 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
2948 block.GetHash().ToString().c_str(),
2950 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2951 FormatMoney(pindex->nMint).c_str(),
2954 PrintWallets(block);
2956 // put the main time-chain first
2957 vector<CBlockIndex*>& vNext = mapNext[pindex];
2958 for (unsigned int i = 0; i < vNext.size(); i++)
2960 if (vNext[i]->pnext)
2962 swap(vNext[0], vNext[i]);
2968 for (unsigned int i = 0; i < vNext.size(); i++)
2969 vStack.push_back(make_pair(nCol+i, vNext[i]));
2973 bool LoadExternalBlockFile(FILE* fileIn)
2975 int64_t nStart = GetTimeMillis();
2981 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2982 unsigned int nPos = 0;
2983 while (nPos != std::numeric_limits<uint32_t>::max() && blkdat.good() && !fRequestShutdown)
2985 unsigned char pchData[65536];
2987 fseek(blkdat, nPos, SEEK_SET);
2988 size_t nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2991 nPos = std::numeric_limits<uint32_t>::max();
2994 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2997 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2999 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
3002 nPos += ((unsigned char*)nFind - pchData) + 1;
3005 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
3006 } while(!fRequestShutdown);
3007 if (nPos == std::numeric_limits<uint32_t>::max())
3009 fseek(blkdat, nPos, SEEK_SET);
3012 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
3016 if (ProcessBlock(NULL,&block))
3024 catch (const std::exception&) {
3025 printf("%s() : Deserialize or I/O error caught during load\n",
3026 BOOST_CURRENT_FUNCTION);
3029 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3033 //////////////////////////////////////////////////////////////////////////////
3038 extern map<uint256, CAlert> mapAlerts;
3039 extern CCriticalSection cs_mapAlerts;
3041 string GetWarnings(string strFor)
3044 string strStatusBar;
3047 if (GetBoolArg("-testsafemode"))
3050 // Misc warnings like out of disk space and clock is wrong
3051 if (!strMiscWarning.empty())
3054 strStatusBar = strMiscWarning;
3057 // if detected unmet upgrade requirement enter safe mode
3058 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3059 if (IsFixedModifierInterval(nModifierUpgradeTime + nOneDay)) // 1 day margin
3062 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3065 // if detected invalid checkpoint enter safe mode
3066 if (Checkpoints::hashInvalidCheckpoint != 0)
3069 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3075 for (auto& item : mapAlerts)
3077 const CAlert& alert = item.second;
3078 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3080 nPriority = alert.nPriority;
3081 strStatusBar = alert.strStatusBar;
3082 if (nPriority > 1000)
3083 strRPC = strStatusBar;
3088 if (strFor == "statusbar")
3089 return strStatusBar;
3090 else if (strFor == "rpc")
3092 assert(!"GetWarnings() : invalid parameter");
3103 //////////////////////////////////////////////////////////////////////////////
3109 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3115 bool txInMap = false;
3118 txInMap = (mempool.exists(inv.hash));
3121 mapOrphanTransactions.count(inv.hash) ||
3122 txdb.ContainsTx(inv.hash);
3126 return mapBlockIndex.count(inv.hash) ||
3127 mapOrphanBlocks.count(inv.hash);
3129 // Don't know what it is, just say we already got one
3136 // The message start string is designed to be unlikely to occur in normal data.
3137 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3138 // a large 4-byte int at any alignment.
3139 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3141 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3143 static map<CService, CPubKey> mapReuseKey;
3144 RandAddSeedPerfmon();
3146 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3147 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3149 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3153 if (strCommand == "version")
3155 // Each connection can only send one version message
3156 if (pfrom->nVersion != 0)
3158 pfrom->Misbehaving(1);
3165 uint64_t nNonce = 1;
3166 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3167 if (pfrom->nVersion < MIN_PROTO_VERSION)
3169 // Since February 20, 2012, the protocol is initiated at version 209,
3170 // and earlier versions are no longer supported
3171 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3172 pfrom->fDisconnect = true;
3176 if (pfrom->nVersion == 10300)
3177 pfrom->nVersion = 300;
3179 vRecv >> addrFrom >> nNonce;
3181 vRecv >> pfrom->strSubVer;
3183 vRecv >> pfrom->nStartingHeight;
3185 if (pfrom->fInbound && addrMe.IsRoutable())
3187 pfrom->addrLocal = addrMe;
3191 // Disconnect if we connected to ourself
3192 if (nNonce == nLocalHostNonce && nNonce > 1)
3194 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3195 pfrom->fDisconnect = true;
3199 if (pfrom->nVersion < 60010)
3201 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3202 pfrom->fDisconnect = true;
3206 // record my external IP reported by peer
3207 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3208 addrSeenByPeer = addrMe;
3210 // Be shy and don't send version until we hear
3211 if (pfrom->fInbound)
3212 pfrom->PushVersion();
3214 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3216 AddTimeData(pfrom->addr, nTime);
3219 pfrom->PushMessage("verack");
3220 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3222 if (!pfrom->fInbound)
3224 // Advertise our address
3225 if (!fNoListen && !IsInitialBlockDownload())
3227 CAddress addr = GetLocalAddress(&pfrom->addr);
3228 if (addr.IsRoutable())
3229 pfrom->PushAddress(addr);
3232 // Get recent addresses
3233 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3235 pfrom->PushMessage("getaddr");
3236 pfrom->fGetAddr = true;
3238 addrman.Good(pfrom->addr);
3240 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3242 addrman.Add(addrFrom, addrFrom);
3243 addrman.Good(addrFrom);
3247 // Ask the first connected node for block updates
3248 static int nAskedForBlocks = 0;
3249 if (!pfrom->fClient && !pfrom->fOneShot &&
3250 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3251 (pfrom->nVersion < NOBLKS_VERSION_START ||
3252 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3253 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3256 pfrom->PushGetBlocks(pindexBest, uint256(0));
3262 for (auto& item : mapAlerts)
3263 item.second.RelayTo(pfrom);
3266 // Relay sync-checkpoint
3268 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3269 if (!Checkpoints::checkpointMessage.IsNull())
3270 Checkpoints::checkpointMessage.RelayTo(pfrom);
3273 pfrom->fSuccessfullyConnected = true;
3275 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());
3277 cPeerBlockCounts.input(pfrom->nStartingHeight);
3279 // ppcoin: ask for pending sync-checkpoint if any
3280 if (!IsInitialBlockDownload())
3281 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3285 else if (pfrom->nVersion == 0)
3287 // Must have a version message before anything else
3288 pfrom->Misbehaving(1);
3293 else if (strCommand == "verack")
3295 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3299 else if (strCommand == "addr")
3301 vector<CAddress> vAddr;
3304 // Don't want addr from older versions unless seeding
3305 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3307 if (vAddr.size() > 1000)
3309 pfrom->Misbehaving(20);
3310 return error("message addr size() = %" PRIszu "", vAddr.size());
3313 // Store the new addresses
3314 vector<CAddress> vAddrOk;
3315 int64_t nNow = GetAdjustedTime();
3316 int64_t nSince = nNow - 10 * 60;
3317 for (CAddress& addr : vAddr)
3321 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3322 addr.nTime = nNow - 5 * nOneDay;
3323 pfrom->AddAddressKnown(addr);
3324 bool fReachable = IsReachable(addr);
3325 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3327 // Relay to a limited number of other nodes
3330 // Use deterministic randomness to send to the same nodes for 24 hours
3331 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3332 static uint256 hashSalt;
3334 hashSalt = GetRandHash();
3335 uint64_t hashAddr = addr.GetHash();
3336 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/nOneDay);
3337 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3338 multimap<uint256, CNode*> mapMix;
3339 for (CNode* pnode : vNodes)
3341 if (pnode->nVersion < CADDR_TIME_VERSION)
3343 unsigned int nPointer;
3344 memcpy(&nPointer, &pnode, sizeof(nPointer));
3345 uint256 hashKey = hashRand ^ nPointer;
3346 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3347 mapMix.insert(make_pair(hashKey, pnode));
3349 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3350 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3351 ((*mi).second)->PushAddress(addr);
3354 // Do not store addresses outside our network
3356 vAddrOk.push_back(addr);
3358 addrman.Add(vAddrOk, pfrom->addr, 2 * nOneHour);
3359 if (vAddr.size() < 1000)
3360 pfrom->fGetAddr = false;
3361 if (pfrom->fOneShot)
3362 pfrom->fDisconnect = true;
3365 else if (strCommand == "inv")
3369 if (vInv.size() > MAX_INV_SZ)
3371 pfrom->Misbehaving(20);
3372 return error("message inv size() = %" PRIszu "", vInv.size());
3375 // find last block in inv vector
3376 size_t nLastBlock = std::numeric_limits<size_t>::max();
3377 for (size_t nInv = 0; nInv < vInv.size(); nInv++) {
3378 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3379 nLastBlock = vInv.size() - 1 - nInv;
3384 for (size_t nInv = 0; nInv < vInv.size(); nInv++)
3386 const CInv &inv = vInv[nInv];
3390 pfrom->AddInventoryKnown(inv);
3392 bool fAlreadyHave = AlreadyHave(txdb, inv);
3394 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3398 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3399 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3400 } else if (nInv == nLastBlock) {
3401 // In case we are on a very long side-chain, it is possible that we already have
3402 // the last block in an inv bundle sent in response to getblocks. Try to detect
3403 // this situation and push another getblocks to continue.
3404 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3406 printf("force request: %s\n", inv.ToString().c_str());
3409 // Track requests for our stuff
3410 Inventory(inv.hash);
3415 else if (strCommand == "getdata")
3419 if (vInv.size() > MAX_INV_SZ)
3421 pfrom->Misbehaving(20);
3422 return error("message getdata size() = %" PRIszu "", vInv.size());
3425 if (fDebugNet || (vInv.size() != 1))
3426 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3428 for (const CInv& inv : vInv)
3432 if (fDebugNet || (vInv.size() == 1))
3433 printf("received getdata for: %s\n", inv.ToString().c_str());
3435 if (inv.type == MSG_BLOCK)
3437 // Send block from disk
3438 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3439 if (mi != mapBlockIndex.end())
3442 block.ReadFromDisk((*mi).second);
3443 pfrom->PushMessage("block", block);
3445 // Trigger them to send a getblocks request for the next batch of inventory
3446 if (inv.hash == pfrom->hashContinue)
3448 // ppcoin: send latest proof-of-work block to allow the
3449 // download node to accept as orphan (proof-of-stake
3450 // block might be rejected by stake connection check)
3452 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3453 pfrom->PushMessage("inv", vInv);
3454 pfrom->hashContinue = 0;
3458 else if (inv.IsKnownType())
3460 // Send stream from relay memory
3461 bool pushed = false;
3464 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3465 if (mi != mapRelay.end()) {
3466 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3470 if (!pushed && inv.type == MSG_TX) {
3472 if (mempool.exists(inv.hash)) {
3473 CTransaction tx = mempool.lookup(inv.hash);
3474 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3477 pfrom->PushMessage("tx", ss);
3482 // Track requests for our stuff
3483 Inventory(inv.hash);
3488 else if (strCommand == "getblocks")
3490 CBlockLocator locator;
3492 vRecv >> locator >> hashStop;
3494 // Find the last block the caller has in the main chain
3495 CBlockIndex* pindex = locator.GetBlockIndex();
3497 // Send the rest of the chain
3499 pindex = pindex->pnext;
3501 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3502 for (; pindex; pindex = pindex->pnext)
3504 if (pindex->GetBlockHash() == hashStop)
3506 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3507 // ppcoin: tell downloading node about the latest block if it's
3508 // without risk being rejected due to stake connection check
3509 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3510 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3513 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3516 // When this block is requested, we'll send an inv that'll make them
3517 // getblocks the next batch of inventory.
3518 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3519 pfrom->hashContinue = pindex->GetBlockHash();
3524 else if (strCommand == "checkpoint")
3526 CSyncCheckpoint checkpoint;
3527 vRecv >> checkpoint;
3529 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3532 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3534 for (CNode* pnode : vNodes)
3535 checkpoint.RelayTo(pnode);
3539 else if (strCommand == "getheaders")
3541 CBlockLocator locator;
3543 vRecv >> locator >> hashStop;
3545 CBlockIndex* pindex = NULL;
3546 if (locator.IsNull())
3548 // If locator is null, return the hashStop block
3549 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3550 if (mi == mapBlockIndex.end())
3552 pindex = (*mi).second;
3556 // Find the last block the caller has in the main chain
3557 pindex = locator.GetBlockIndex();
3559 pindex = pindex->pnext;
3562 vector<CBlock> vHeaders;
3564 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3565 for (; pindex; pindex = pindex->pnext)
3567 vHeaders.push_back(pindex->GetBlockHeader());
3568 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3571 pfrom->PushMessage("headers", vHeaders);
3575 else if (strCommand == "tx")
3577 vector<uint256> vWorkQueue;
3578 vector<uint256> vEraseQueue;
3579 CDataStream vMsg(vRecv);
3584 CInv inv(MSG_TX, tx.GetHash());
3585 pfrom->AddInventoryKnown(inv);
3587 bool fMissingInputs = false;
3588 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3590 SyncWithWallets(tx, NULL, true);
3591 RelayTransaction(tx, inv.hash);
3592 mapAlreadyAskedFor.erase(inv);
3593 vWorkQueue.push_back(inv.hash);
3594 vEraseQueue.push_back(inv.hash);
3596 // Recursively process any orphan transactions that depended on this one
3597 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3599 uint256 hashPrev = vWorkQueue[i];
3600 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3601 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3604 const uint256& orphanTxHash = *mi;
3605 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3606 bool fMissingInputs2 = false;
3608 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3610 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3611 SyncWithWallets(tx, NULL, true);
3612 RelayTransaction(orphanTx, orphanTxHash);
3613 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3614 vWorkQueue.push_back(orphanTxHash);
3615 vEraseQueue.push_back(orphanTxHash);
3617 else if (!fMissingInputs2)
3620 vEraseQueue.push_back(orphanTxHash);
3621 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3626 for (uint256 hash : vEraseQueue)
3627 EraseOrphanTx(hash);
3629 else if (fMissingInputs)
3633 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3634 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3636 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3638 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3642 else if (strCommand == "block")
3646 uint256 hashBlock = block.GetHash();
3648 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3651 CInv inv(MSG_BLOCK, hashBlock);
3652 pfrom->AddInventoryKnown(inv);
3654 if (ProcessBlock(pfrom, &block))
3655 mapAlreadyAskedFor.erase(inv);
3656 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3660 // This asymmetric behavior for inbound and outbound connections was introduced
3661 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
3662 // to users' AddrMan and later request them by sending getaddr messages.
3663 // Making users (which are behind NAT and can only make outgoing connections) ignore
3664 // getaddr message mitigates the attack.
3665 else if ((strCommand == "getaddr") && (pfrom->fInbound))
3667 // Don't return addresses older than nCutOff timestamp
3668 int64_t nCutOff = GetTime() - (nNodeLifespan * nOneDay);
3669 pfrom->vAddrToSend.clear();
3670 vector<CAddress> vAddr = addrman.GetAddr();
3671 for (const CAddress &addr : vAddr)
3672 if(addr.nTime > nCutOff)
3673 pfrom->PushAddress(addr);
3677 else if (strCommand == "mempool")
3679 std::vector<uint256> vtxid;
3680 mempool.queryHashes(vtxid);
3682 for (unsigned int i = 0; i < vtxid.size(); i++) {
3683 CInv inv(MSG_TX, vtxid[i]);
3684 vInv.push_back(inv);
3685 if (i == (MAX_INV_SZ - 1))
3688 if (vInv.size() > 0)
3689 pfrom->PushMessage("inv", vInv);
3693 else if (strCommand == "checkorder")
3698 if (!GetBoolArg("-allowreceivebyip"))
3700 pfrom->PushMessage("reply", hashReply, 2, string(""));
3707 /// we have a chance to check the order here
3709 // Keep giving the same key to the same ip until they use it
3710 if (!mapReuseKey.count(pfrom->addr))
3711 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3713 // Send back approval of order and pubkey to use
3714 CScript scriptPubKey;
3715 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3716 pfrom->PushMessage("reply", hashReply, 0, scriptPubKey);
3720 else if (strCommand == "reply")
3725 CRequestTracker tracker;
3727 LOCK(pfrom->cs_mapRequests);
3728 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3729 if (mi != pfrom->mapRequests.end())
3731 tracker = (*mi).second;
3732 pfrom->mapRequests.erase(mi);
3735 if (!tracker.IsNull())
3736 tracker.fn(tracker.param1, vRecv);
3740 else if (strCommand == "ping")
3744 // Echo the message back with the nonce. This allows for two useful features:
3746 // 1) A remote node can quickly check if the connection is operational
3747 // 2) Remote nodes can measure the latency of the network thread. If this node
3748 // is overloaded it won't respond to pings quickly and the remote node can
3749 // avoid sending us more work, like chain download requests.
3751 // The nonce stops the remote getting confused between different pings: without
3752 // it, if the remote node sends a ping once per second and this node takes 5
3753 // seconds to respond to each, the 5th ping the remote sends would appear to
3754 // return very quickly.
3755 pfrom->PushMessage("pong", nonce);
3759 else if (strCommand == "alert")
3764 uint256 alertHash = alert.GetHash();
3765 if (pfrom->setKnown.count(alertHash) == 0)
3767 if (alert.ProcessAlert())
3770 pfrom->setKnown.insert(alertHash);
3773 for (CNode* pnode : vNodes)
3774 alert.RelayTo(pnode);
3778 // Small DoS penalty so peers that send us lots of
3779 // duplicate/expired/invalid-signature/whatever alerts
3780 // eventually get banned.
3781 // This isn't a Misbehaving(100) (immediate ban) because the
3782 // peer might be an older or different implementation with
3783 // a different signature key, etc.
3784 pfrom->Misbehaving(10);
3792 // Ignore unknown commands for extensibility
3796 // Update the last seen time for this node's address
3797 if (pfrom->fNetworkNode)
3798 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3799 AddressCurrentlyConnected(pfrom->addr);
3805 bool ProcessMessages(CNode* pfrom)
3807 CDataStream& vRecv = pfrom->vRecv;
3811 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3815 // (4) message start
3824 // Don't bother if send buffer is too full to respond anyway
3825 if (pfrom->vSend.size() >= SendBufferSize())
3828 // Scan for message start
3829 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3830 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3831 if (vRecv.end() - pstart < nHeaderSize)
3833 if ((int)vRecv.size() > nHeaderSize)
3835 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3836 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3840 if (pstart - vRecv.begin() > 0)
3841 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
3842 vRecv.erase(vRecv.begin(), pstart);
3845 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3850 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3853 string strCommand = hdr.GetCommand();
3856 unsigned int nMessageSize = hdr.nMessageSize;
3857 if (nMessageSize > MAX_SIZE)
3859 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3862 if (nMessageSize > vRecv.size())
3864 // Rewind and wait for rest of message
3865 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3870 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3871 unsigned int nChecksum = 0;
3872 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3873 if (nChecksum != hdr.nChecksum)
3875 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3876 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3880 // Copy message to its own buffer
3881 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3882 vRecv.ignore(nMessageSize);
3890 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3895 catch (std::ios_base::failure& e)
3897 if (strstr(e.what(), "end of data"))
3899 // Allow exceptions from under-length message on vRecv
3900 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());
3902 else if (strstr(e.what(), "size too large"))
3904 // Allow exceptions from over-long size
3905 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3909 PrintExceptionContinue(&e, "ProcessMessages()");
3912 catch (std::exception& e) {
3913 PrintExceptionContinue(&e, "ProcessMessages()");
3915 PrintExceptionContinue(NULL, "ProcessMessages()");
3919 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3929 bool SendMessages(CNode* pto)
3931 TRY_LOCK(cs_main, lockMain);
3933 // Current time in microseconds
3934 int64_t nNow = GetTimeMicros();
3936 // Don't send anything until we get their version message
3937 if (pto->nVersion == 0)
3940 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3942 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
3944 pto->PushMessage("ping", nonce);
3948 if (pto->fStartSync) {
3949 pto->fStartSync = false;
3950 pto->PushGetBlocks(pindexBest, uint256(0));
3953 // Resend wallet transactions that haven't gotten in a block yet
3954 ResendWalletTransactions();
3956 // Address refresh broadcast
3957 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3958 AdvertiseLocal(pto);
3959 pto->nNextLocalAddrSend = PoissonNextSend(nNow, nOneDay);
3965 if (pto->nNextAddrSend < nNow) {
3966 pto->nNextAddrSend = PoissonNextSend(nNow, 30);
3967 vector<CAddress> vAddr;
3968 vAddr.reserve(pto->vAddrToSend.size());
3969 for (const CAddress& addr : pto->vAddrToSend)
3971 if (pto->setAddrKnown.insert(addr).second)
3973 vAddr.push_back(addr);
3974 // receiver rejects addr messages larger than 1000
3975 if (vAddr.size() >= 1000)
3977 pto->PushMessage("addr", vAddr);
3982 pto->vAddrToSend.clear();
3984 pto->PushMessage("addr", vAddr);
3988 // Message: inventory
3991 vector<CInv> vInvWait;
3993 bool fSendTrickle = false;
3994 if (pto->nNextInvSend < nNow) {
3995 fSendTrickle = true;
3996 pto->nNextInvSend = PoissonNextSend(nNow, 5);
3998 LOCK(pto->cs_inventory);
3999 vInv.reserve(pto->vInventoryToSend.size());
4000 vInvWait.reserve(pto->vInventoryToSend.size());
4001 for (const CInv& inv : pto->vInventoryToSend)
4003 if (pto->setInventoryKnown.count(inv))
4006 // trickle out tx inv to protect privacy
4007 if (inv.type == MSG_TX && !fSendTrickle)
4009 // 1/4 of tx invs blast to all immediately
4010 static uint256 hashSalt;
4012 hashSalt = GetRandHash();
4013 uint256 hashRand = inv.hash ^ hashSalt;
4014 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4015 bool fTrickleWait = ((hashRand & 3) != 0);
4019 vInvWait.push_back(inv);
4024 // returns true if wasn't already contained in the set
4025 if (pto->setInventoryKnown.insert(inv).second)
4027 vInv.push_back(inv);
4028 if (vInv.size() >= 1000)
4030 pto->PushMessage("inv", vInv);
4035 pto->vInventoryToSend = vInvWait;
4038 pto->PushMessage("inv", vInv);
4044 vector<CInv> vGetData;
4046 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4048 const CInv& inv = (*pto->mapAskFor.begin()).second;
4049 if (!AlreadyHave(txdb, inv))
4052 printf("sending getdata: %s\n", inv.ToString().c_str());
4053 vGetData.push_back(inv);
4054 if (vGetData.size() >= 1000)
4056 pto->PushMessage("getdata", vGetData);
4059 mapAlreadyAskedFor[inv] = nNow;
4061 pto->mapAskFor.erase(pto->mapAskFor.begin());
4063 if (!vGetData.empty())
4064 pto->PushMessage("getdata", vGetData);
4077 std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4078 for (; it1 != mapBlockIndex.end(); it1++)
4079 delete (*it1).second;
4080 mapBlockIndex.clear();
4083 std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4084 for (; it2 != mapOrphanBlocks.end(); it2++)
4085 delete (*it2).second;
4086 mapOrphanBlocks.clear();
4088 // orphan transactions
4090 } instance_of_cmaincleanup;