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"
11 #include "ui_interface.h"
12 #include "checkqueue.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
21 using namespace boost;
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
31 unsigned int nTransactionsUpdated = 0;
33 map<uint256, CBlockIndex*> mapBlockIndex;
34 set<pair<COutPoint, unsigned int> > setStakeSeen;
36 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
37 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
38 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
39 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
40 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
42 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
44 unsigned int nStakeMinAge = 30 * nOneDay; // 30 days as zero time weight
45 unsigned int nStakeMaxAge = 90 * nOneDay; // 90 days as full weight
46 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
47 unsigned int nModifierInterval = 6 * nOneHour; // time to elapse before new modifier is computed
49 int nCoinbaseMaturity = 500;
51 CBlockIndex* pindexGenesisBlock = NULL;
54 uint256 nBestChainTrust = 0;
55 uint256 nBestInvalidTrust = 0;
57 uint256 hashBestChain = 0;
58 CBlockIndex* pindexBest = NULL;
59 int64_t nTimeBestReceived = 0;
60 int nScriptCheckThreads = 0;
62 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
64 map<uint256, CBlock*> mapOrphanBlocks;
65 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
66 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
67 map<uint256, uint256> mapProofOfStake;
69 map<uint256, CTransaction> mapOrphanTransactions;
70 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
72 // Constant stuff for coinbase transactions we create:
73 CScript COINBASE_FLAGS;
75 const string strMessageMagic = "NovaCoin Signed Message:\n";
78 int64_t nTransactionFee = MIN_TX_FEE;
79 int64_t nMinimumInputValue = MIN_TXOUT_AMOUNT;
81 // Ping and address broadcast intervals
82 int64_t nPingInterval = 30 * 60;
84 extern enum Checkpoints::CPMode CheckpointsMode;
86 //////////////////////////////////////////////////////////////////////////////
88 // dispatching functions
91 // These functions dispatch to one or all registered wallets
94 void RegisterWallet(CWallet* pwalletIn)
97 LOCK(cs_setpwalletRegistered);
98 setpwalletRegistered.insert(pwalletIn);
102 void UnregisterWallet(CWallet* pwalletIn)
105 LOCK(cs_setpwalletRegistered);
106 setpwalletRegistered.erase(pwalletIn);
110 // check whether the passed transaction is from us
111 bool static IsFromMe(CTransaction& tx)
113 for(CWallet* pwallet : setpwalletRegistered)
114 if (pwallet->IsFromMe(tx))
119 // erases transaction with the given hash from all wallets
120 void static EraseFromWallets(uint256 hash)
122 for(CWallet* pwallet : setpwalletRegistered)
123 pwallet->EraseFromWallet(hash);
126 // make sure all wallets know about the given transaction, in the given block
127 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
131 // wallets need to refund inputs when disconnecting coinstake
132 if (tx.IsCoinStake())
134 for(CWallet* pwallet : setpwalletRegistered)
135 if (pwallet->IsFromMe(tx))
136 pwallet->DisableTransaction(tx);
141 for(CWallet* pwallet : setpwalletRegistered)
142 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
145 // notify wallets about a new best chain
146 void static SetBestChain(const CBlockLocator& loc)
148 for(CWallet* pwallet : setpwalletRegistered)
149 pwallet->SetBestChain(loc);
152 // notify wallets about an updated transaction
153 void static UpdatedTransaction(const uint256& hashTx)
155 for(CWallet* pwallet : setpwalletRegistered)
156 pwallet->UpdatedTransaction(hashTx);
160 void static PrintWallets(const CBlock& block)
162 for(CWallet* pwallet : setpwalletRegistered)
163 pwallet->PrintWallet(block);
166 // notify wallets about an incoming inventory (for request counts)
167 void static Inventory(const uint256& hash)
169 for(CWallet* pwallet : setpwalletRegistered)
170 pwallet->Inventory(hash);
173 // ask wallets to resend their transactions
174 void ResendWalletTransactions(bool fForceResend)
176 for(CWallet* pwallet : setpwalletRegistered)
177 pwallet->ResendWalletTransactions(fForceResend);
186 //////////////////////////////////////////////////////////////////////////////
188 // mapOrphanTransactions
191 bool AddOrphanTx(const CTransaction& tx)
193 auto hash = tx.GetHash();
194 if (mapOrphanTransactions.count(hash))
197 // Ignore big transactions, to avoid a
198 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
199 // large transaction with a missing parent then we assume
200 // it will rebroadcast it later, after the parent transaction(s)
201 // have been mined or received.
202 // 10,000 orphans, each of which is at most 5,000 bytes big is
203 // at most 500 megabytes of orphans:
205 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
209 printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
213 mapOrphanTransactions[hash] = tx;
214 for(const CTxIn& txin : tx.vin)
215 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
217 printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
218 mapOrphanTransactions.size());
222 void static EraseOrphanTx(uint256 hash)
224 if (!mapOrphanTransactions.count(hash))
226 const auto& tx = mapOrphanTransactions[hash];
227 for(const auto& txin : tx.vin)
229 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
230 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
231 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
233 mapOrphanTransactions.erase(hash);
236 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
238 unsigned int nEvicted = 0;
239 while (mapOrphanTransactions.size() > nMaxOrphans)
241 // Evict a random orphan:
242 auto randomhash = GetRandHash();
243 auto it = mapOrphanTransactions.lower_bound(randomhash);
244 if (it == mapOrphanTransactions.end())
245 it = mapOrphanTransactions.begin();
246 EraseOrphanTx(it->first);
258 //////////////////////////////////////////////////////////////////////////////
260 // CTransaction and CTxIndex
263 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
266 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
268 if (!ReadFromDisk(txindexRet.pos))
270 if (prevout.n >= vout.size())
278 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
281 return ReadFromDisk(txdb, prevout, txindex);
284 bool CTransaction::ReadFromDisk(COutPoint prevout)
288 return ReadFromDisk(txdb, prevout, txindex);
291 bool CTransaction::IsStandard(string& strReason) const
293 if (nVersion > CTransaction::CURRENT_VERSION)
295 strReason = "version";
299 unsigned int nDataOut = 0;
300 txnouttype whichType;
301 for(const CTxIn& txin : vin)
303 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
304 // keys. (remember the 520 byte limit on redeemScript size) That works
305 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
306 // bytes of scriptSig, which we round off to 1650 bytes for some minor
307 // future-proofing. That's also enough to spend a 20-of-20
308 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
309 // considered standard)
310 if (txin.scriptSig.size() > 1650)
312 strReason = "scriptsig-size";
315 if (!txin.scriptSig.IsPushOnly())
317 strReason = "scriptsig-not-pushonly";
320 if (!txin.scriptSig.HasCanonicalPushes()) {
321 strReason = "txin-scriptsig-not-canonicalpushes";
325 for(const CTxOut& txout : vout) {
326 if (!::IsStandard(txout.scriptPubKey, whichType)) {
327 strReason = "scriptpubkey";
330 if (whichType == TX_NULL_DATA)
333 if (txout.nValue == 0) {
334 strReason = "txout-value=0";
337 if (!txout.scriptPubKey.HasCanonicalPushes()) {
338 strReason = "txout-scriptsig-not-canonicalpushes";
344 // only one OP_RETURN txout is permitted
346 strReason = "multi-op-return";
354 // Check transaction inputs, and make sure any
355 // pay-to-script-hash transactions are evaluating IsStandard scripts
357 // Why bother? To avoid denial-of-service attacks; an attacker
358 // can submit a standard HASH... OP_EQUAL transaction,
359 // which will get accepted into blocks. The redemption
360 // script can be anything; an attacker could use a very
361 // expensive-to-check-upon-redemption script like:
362 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
364 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
367 return true; // Coinbases don't use vin normally
369 for (unsigned int i = 0; i < vin.size(); i++)
371 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
373 vector<vector<unsigned char> > vSolutions;
374 txnouttype whichType;
375 // get the scriptPubKey corresponding to this input:
376 const CScript& prevScript = prev.scriptPubKey;
377 if (!Solver(prevScript, whichType, vSolutions))
379 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
380 if (nArgsExpected < 0)
383 // Transactions with extra stuff in their scriptSigs are
384 // non-standard. Note that this EvalScript() call will
385 // be quick, because if there are any operations
386 // beside "push data" in the scriptSig the
387 // IsStandard() call returns false
388 vector<vector<unsigned char> > stack;
389 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
392 if (whichType == TX_SCRIPTHASH)
396 CScript subscript(stack.back().begin(), stack.back().end());
397 vector<vector<unsigned char> > vSolutions2;
398 txnouttype whichType2;
399 if (!Solver(subscript, whichType2, vSolutions2))
401 if (whichType2 == TX_SCRIPTHASH)
405 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
408 nArgsExpected += tmpExpected;
411 if (stack.size() != (unsigned int)nArgsExpected)
419 CTransaction::GetLegacySigOpCount() const
421 unsigned int nSigOps = 0;
424 // Coinbase scriptsigs are never executed, so there is
425 // no sense in calculation of sigops.
426 for(const CTxIn& txin : vin)
428 nSigOps += txin.scriptSig.GetSigOpCount(false);
431 for(const CTxOut& txout : vout)
433 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
438 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
451 // Load the block this tx is in
453 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
455 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
460 // Update the tx's hashBlock
461 hashBlock = pblock->GetHash();
463 // Locate the transaction
464 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
465 if (pblock->vtx[nIndex] == *(CTransaction*)this)
467 if (nIndex == (int)pblock->vtx.size())
469 vMerkleBranch.clear();
471 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
475 // Fill in merkle branch
476 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
479 // Is the tx in a block that's in the main chain
480 auto mi = mapBlockIndex.find(hashBlock);
481 if (mi == mapBlockIndex.end())
483 const CBlockIndex* pindex = (*mi).second;
484 if (!pindex || !pindex->IsInMainChain())
487 return pindexBest->nHeight - pindex->nHeight + 1;
490 bool CTransaction::CheckTransaction() const
492 // Basic checks that don't depend on any context
494 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
496 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
498 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
499 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
501 // Check for negative or overflow output values
502 int64_t nValueOut = 0;
503 for (unsigned int i = 0; i < vout.size(); i++)
505 const CTxOut& txout = vout[i];
506 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
507 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
509 if (txout.nValue < 0)
510 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
511 if (txout.nValue > MAX_MONEY)
512 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
513 nValueOut += txout.nValue;
514 if (!MoneyRange(nValueOut))
515 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
518 // Check for duplicate inputs
519 set<COutPoint> vInOutPoints;
520 for(const CTxIn& txin : vin)
522 if (vInOutPoints.count(txin.prevout))
524 vInOutPoints.insert(txin.prevout);
529 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
530 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
534 for(const CTxIn& txin : vin)
535 if (txin.prevout.IsNull())
536 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
542 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
544 int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
548 // Enforce 0.01 as minimum fee for coinstake
550 nMinRelayTxFee = CENT;
553 // Base fee is either nMinTxFee or nMinRelayTxFee
554 auto nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
556 unsigned int nNewBlockSize = nBlockSize + nBytes;
557 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
563 // Transactions under 1K are free
569 // Free transaction area
570 if (nNewBlockSize < 27000)
575 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
576 // each non empty output which is less than 0.01
578 // It's safe to ignore empty outputs here, because these inputs are allowed
579 // only for coinbase and coinstake transactions.
580 for(const CTxOut& txout : vout)
581 if (txout.nValue < CENT && !txout.IsEmpty())
584 // Raise the price as the block approaches full
585 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
587 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
589 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
592 if (!MoneyRange(nMinFee))
599 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
600 bool* pfMissingInputs)
603 *pfMissingInputs = false;
605 // Time (prevent mempool memory exhaustion attack)
606 if (tx.nTime > FutureDrift(GetAdjustedTime()))
607 return tx.DoS(10, error("CTxMemPool::accept() : transaction timestamp is too far in the future"));
609 if (!tx.CheckTransaction())
610 return error("CTxMemPool::accept() : CheckTransaction failed");
612 // Coinbase is only valid in a block, not as a loose transaction
614 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
616 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
617 if (tx.IsCoinStake())
618 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
620 // To help v0.1.5 clients who would see it as a negative number
621 if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
622 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
624 // Rather not work on nonstandard transactions (unless -testnet)
626 if (!fTestNet && !tx.IsStandard(strNonStd))
627 return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
629 // Do we already have it?
630 auto hash = tx.GetHash();
633 if (mapTx.count(hash))
637 if (txdb.ContainsTx(hash))
640 // Check for conflicts with in-memory transactions
641 CTransaction* ptxOld = NULL;
642 for (unsigned int i = 0; i < tx.vin.size(); i++)
644 auto outpoint = tx.vin[i].prevout;
645 if (mapNextTx.count(outpoint))
647 // Replacement feature isn't supported by Novacoin.
655 map<uint256, CTxIndex> mapUnused;
656 bool fInvalid = false;
657 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
660 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
662 *pfMissingInputs = true;
666 // Check for non-standard pay-to-script-hash in inputs
667 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
668 return error("CTxMemPool::accept() : nonstandard transaction input");
670 // Note: if you modify this code to accept non-standard transactions, then
671 // you should add code here to check that the transaction does a
672 // reasonable number of ECDSA signature verifications.
674 auto nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
675 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
677 // Don't accept it if it can't get into a block
678 auto txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
679 if (nFees < txMinFee)
680 return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
681 hash.ToString().c_str(),
684 // Continuously rate-limit free transactions
685 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
686 // be annoying or make others' transactions take longer to confirm.
687 if (nFees < MIN_RELAY_TX_FEE)
689 static CCriticalSection cs;
690 static double dFreeCount;
691 static int64_t nLastTime;
692 auto nNow = GetTime();
696 // Use an exponentially decaying ~10-minute window:
697 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
699 // -limitfreerelay unit is thousand-bytes-per-minute
700 // At default rate it would take over a month to fill 1GB
701 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
702 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
704 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
709 // Check against previous transactions
710 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
711 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, STRICT_FLAGS))
713 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
717 // Store transaction in memory
722 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
725 addUnchecked(hash, tx);
728 ///// are we sure this is ok when loading transactions or restoring block txes
729 // If updated, erase old tx from wallet
731 EraseFromWallets(ptxOld->GetHash());
733 printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
734 hash.ToString().substr(0,10).c_str(),
739 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
741 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
744 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
746 // Add to memory pool without checking anything. Don't call this directly,
747 // call CTxMemPool::accept to properly check the transaction first.
750 for (unsigned int i = 0; i < tx.vin.size(); i++)
751 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
752 nTransactionsUpdated++;
758 bool CTxMemPool::remove(CTransaction &tx)
760 // Remove transaction from memory pool
763 auto hash = tx.GetHash();
764 if (mapTx.count(hash))
766 for(const CTxIn& txin : tx.vin)
767 mapNextTx.erase(txin.prevout);
769 nTransactionsUpdated++;
775 void CTxMemPool::clear()
780 ++nTransactionsUpdated;
783 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
788 vtxid.reserve(mapTx.size());
789 for (auto mi = mapTx.begin(); mi != mapTx.end(); ++mi)
790 vtxid.push_back((*mi).first);
796 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
798 if (hashBlock == 0 || nIndex == -1)
801 // Find the block it claims to be in
802 auto mi = mapBlockIndex.find(hashBlock);
803 if (mi == mapBlockIndex.end())
805 CBlockIndex* pindex = (*mi).second;
806 if (!pindex || !pindex->IsInMainChain())
809 // Make sure the merkle branch connects to this block
810 if (!fMerkleVerified)
812 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
814 fMerkleVerified = true;
818 return pindexBest->nHeight - pindex->nHeight + 1;
822 int CMerkleTx::GetBlocksToMaturity() const
824 if (!(IsCoinBase() || IsCoinStake()))
826 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
830 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
834 if (!IsInMainChain() && !ClientConnectInputs())
836 return CTransaction::AcceptToMemoryPool(txdb, false);
840 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
844 bool CMerkleTx::AcceptToMemoryPool()
847 return AcceptToMemoryPool(txdb);
852 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
857 // Add previous supporting transactions first
858 for(CMerkleTx& tx : vtxPrev)
860 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
862 auto hash = tx.GetHash();
863 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
864 tx.AcceptToMemoryPool(txdb, fCheckInputs);
867 return AcceptToMemoryPool(txdb, fCheckInputs);
872 bool CWalletTx::AcceptWalletTransaction()
875 return AcceptWalletTransaction(txdb);
878 int CTxIndex::GetDepthInMainChain() const
882 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
884 // Find the block in the index
885 auto mi = mapBlockIndex.find(block.GetHash());
886 if (mi == mapBlockIndex.end())
888 auto pindex = (*mi).second;
889 if (!pindex || !pindex->IsInMainChain())
891 return 1 + nBestHeight - pindex->nHeight;
894 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
895 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
901 if (mempool.exists(hash))
903 tx = mempool.lookup(hash);
909 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
912 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
913 hashBlock = block.GetHash();
927 //////////////////////////////////////////////////////////////////////////////
929 // CBlock and CBlockIndex
932 static CBlockIndex* pblockindexFBBHLast;
933 CBlockIndex* FindBlockByHeight(int nHeight)
935 CBlockIndex *pblockindex;
936 if (nHeight < nBestHeight / 2)
937 pblockindex = pindexGenesisBlock;
939 pblockindex = pindexBest;
940 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
941 pblockindex = pblockindexFBBHLast;
942 while (pblockindex->nHeight > nHeight)
943 pblockindex = pblockindex->pprev;
944 while (pblockindex->nHeight < nHeight)
945 pblockindex = pblockindex->pnext;
946 pblockindexFBBHLast = pblockindex;
950 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
952 if (!fReadTransactions)
954 *this = pindex->GetBlockHeader();
957 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
959 if (GetHash() != pindex->GetBlockHash())
960 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
964 uint256 static GetOrphanRoot(const CBlock* pblock)
966 // Work back to the first block in the orphan chain
967 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
968 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
969 return pblock->GetHash();
972 // ppcoin: find block wanted by given orphan block
973 uint256 WantedByOrphan(const CBlock* pblockOrphan)
975 // Work back to the first block in the orphan chain
976 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
977 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
978 return pblockOrphan->hashPrevBlock;
981 // select stake target limit according to hard-coded conditions
982 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
984 if(fTestNet) // separate proof of stake target limit for testnet
985 return bnProofOfStakeLimit;
986 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
987 return bnProofOfStakeLimit;
988 if(nHeight + 1 > 15000) // 24 bits since block 15000
989 return bnProofOfStakeLegacyLimit;
990 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
991 return bnProofOfStakeHardLimit;
993 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
996 // miner's coin base reward based on nBits
997 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees)
999 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1002 bnTarget.SetCompact(nBits);
1003 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1004 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1006 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1007 // A reasonably continuous curve is used to avoid shock to market
1008 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1010 // Human readable form:
1012 // nSubsidy = 100 / (diff ^ 1/6)
1014 // Please note that we're using bisection to find an approximate solutuion
1015 CBigNum bnLowerBound = CENT;
1016 CBigNum bnUpperBound = bnSubsidyLimit;
1017 while (bnLowerBound + CENT <= bnUpperBound)
1019 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1020 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1021 bnUpperBound = bnMidValue;
1023 bnLowerBound = bnMidValue;
1026 int64_t nSubsidy = bnUpperBound.getuint64();
1028 nSubsidy = (nSubsidy / CENT) * CENT;
1029 if (fDebug && GetBoolArg("-printcreation"))
1030 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1032 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1035 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1036 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1038 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1040 // Stage 2 of emission process is mostly PoS-based.
1042 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1044 bnTarget.SetCompact(nBits);
1045 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1046 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1048 // A reasonably continuous curve is used to avoid shock to market
1050 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1051 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1052 bnMidPart, bnRewardPart;
1054 while (bnLowerBound + CENT <= bnUpperBound)
1056 auto bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1059 // Reward for coin-year is cut in half every 8x multiply of PoS difficulty
1061 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1063 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1066 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1067 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1069 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1070 bnUpperBound = bnMidValue;
1072 bnLowerBound = bnMidValue;
1075 nRewardCoinYear = bnUpperBound.getuint64();
1076 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1079 return nRewardCoinYear;
1081 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1083 // Set reasonable reward limit for large inputs
1085 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1087 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1088 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1090 nSubsidy = min(nSubsidy, nSubsidyLimit);
1092 if (fDebug && GetBoolArg("-printcreation"))
1093 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1098 static const int64_t nTargetTimespan = 7 * nOneDay; // one week
1100 // get proof of work blocks max spacing according to hard-coded conditions
1101 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1103 if(nTime > TARGETS_SWITCH_TIME)
1104 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1107 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1109 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1113 // maximum nBits value could possible be required nTime after
1115 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1118 bnResult.SetCompact(nBase);
1120 while (nTime > 0 && bnResult < bnTargetLimit)
1122 // Maximum 200% adjustment per day...
1126 if (bnResult > bnTargetLimit)
1127 bnResult = bnTargetLimit;
1128 return bnResult.GetCompact();
1132 // minimum amount of work that could possibly be required nTime after
1133 // minimum proof-of-work required was nBase
1135 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1137 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1141 // minimum amount of stake that could possibly be required nTime after
1142 // minimum proof-of-stake required was nBase
1144 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1146 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1150 // ppcoin: find last block index up to pindex
1151 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1153 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1154 pindex = pindex->pprev;
1158 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1160 if (pindexLast == NULL)
1161 return bnProofOfWorkLimit.GetCompact(); // genesis block
1163 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1165 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1166 if (pindexPrev->pprev == NULL)
1167 return bnTargetLimit.GetCompact(); // first block
1168 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1169 if (pindexPrevPrev->pprev == NULL)
1170 return bnTargetLimit.GetCompact(); // second block
1172 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1174 // ppcoin: target change every block
1175 // ppcoin: retarget with exponential moving toward target spacing
1177 bnNew.SetCompact(pindexPrev->nBits);
1178 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1179 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1180 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1181 bnNew /= ((nInterval + 1) * nTargetSpacing);
1183 if (bnNew > bnTargetLimit)
1184 bnNew = bnTargetLimit;
1186 return bnNew.GetCompact();
1189 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1192 bnTarget.SetCompact(nBits);
1195 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1196 return error("CheckProofOfWork() : nBits below minimum work");
1198 // Check proof of work matches claimed amount
1199 if (hash > bnTarget.getuint256())
1200 return error("CheckProofOfWork() : hash doesn't match nBits");
1205 // Return maximum amount of blocks that other nodes claim to have
1206 int GetNumBlocksOfPeers()
1208 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1211 bool IsInitialBlockDownload()
1213 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1215 static int64_t nLastUpdate;
1216 static CBlockIndex* pindexLastBest;
1217 auto nCurrentTime = GetTime();
1218 if (pindexBest != pindexLastBest)
1220 pindexLastBest = pindexBest;
1221 nLastUpdate = nCurrentTime;
1223 return (nCurrentTime - nLastUpdate < 10 &&
1224 pindexBest->GetBlockTime() < nCurrentTime - nOneDay);
1227 void static InvalidChainFound(CBlockIndex* pindexNew)
1229 if (pindexNew->nChainTrust > nBestInvalidTrust)
1231 nBestInvalidTrust = pindexNew->nChainTrust;
1232 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1233 uiInterface.NotifyBlocksChanged();
1236 auto nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1237 auto nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1239 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1240 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1241 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1242 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1243 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1244 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1245 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1246 nBestBlockTrust.Get64(),
1247 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1251 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1253 nTime = max(GetBlockTime(), GetAdjustedTime());
1266 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1268 // Relinquish previous transactions' spent pointers
1271 for(const CTxIn& txin : vin)
1273 auto prevout = txin.prevout;
1275 // Get prev txindex from disk
1277 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1278 return error("DisconnectInputs() : ReadTxIndex failed");
1280 if (prevout.n >= txindex.vSpent.size())
1281 return error("DisconnectInputs() : prevout.n out of range");
1283 // Mark outpoint as not spent
1284 txindex.vSpent[prevout.n].SetNull();
1287 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1288 return error("DisconnectInputs() : UpdateTxIndex failed");
1292 // Remove transaction from index
1293 // This can fail if a duplicate of this transaction was in a chain that got
1294 // reorganized away. This is only possible if this transaction was completely
1295 // spent, so erasing it would be a no-op anyway.
1296 txdb.EraseTxIndex(*this);
1302 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1303 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1305 // FetchInputs can return false either because we just haven't seen some inputs
1306 // (in which case the transaction should be stored as an orphan)
1307 // or because the transaction is malformed (in which case the transaction should
1308 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1312 return true; // Coinbase transactions have no inputs to fetch.
1314 for (unsigned int i = 0; i < vin.size(); i++)
1316 auto prevout = vin[i].prevout;
1317 if (inputsRet.count(prevout.hash))
1318 continue; // Got it already
1321 CTxIndex& txindex = inputsRet[prevout.hash].first;
1323 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1325 // Get txindex from current proposed changes
1326 txindex = mapTestPool.find(prevout.hash)->second;
1330 // Read txindex from txdb
1331 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1333 if (!fFound && (fBlock || fMiner))
1334 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());
1337 CTransaction& txPrev = inputsRet[prevout.hash].second;
1338 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1340 // Get prev tx from single transactions in memory
1343 if (!mempool.exists(prevout.hash))
1344 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());
1345 txPrev = mempool.lookup(prevout.hash);
1348 txindex.vSpent.resize(txPrev.vout.size());
1352 // Get prev tx from disk
1353 if (!txPrev.ReadFromDisk(txindex.pos))
1354 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1358 // Make sure all prevout.n indexes are valid:
1359 for (unsigned int i = 0; i < vin.size(); i++)
1361 const COutPoint prevout = vin[i].prevout;
1362 assert(inputsRet.count(prevout.hash) != 0);
1363 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1364 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1365 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1367 // Revisit this if/when transaction replacement is implemented and allows
1370 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()));
1377 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1379 auto mi = inputs.find(input.prevout.hash);
1380 if (mi == inputs.end())
1381 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1383 const auto& txPrev = (mi->second).second;
1384 if (input.prevout.n >= txPrev.vout.size())
1385 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1387 return txPrev.vout[input.prevout.n];
1390 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1395 int64_t nResult = 0;
1396 for (unsigned int i = 0; i < vin.size(); i++)
1398 nResult += GetOutputFor(vin[i], inputs).nValue;
1404 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1409 unsigned int nSigOps = 0;
1410 for (unsigned int i = 0; i < vin.size(); i++)
1412 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1413 if (prevout.scriptPubKey.IsPayToScriptHash())
1414 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1419 bool CScriptCheck::operator()() const {
1420 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1421 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1422 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1426 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1428 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1431 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1432 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1434 // Take over previous transactions' spent pointers
1435 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1436 // fMiner is true when called from the internal bitcoin miner
1437 // ... both are false when called from CTransaction::AcceptToMemoryPool
1441 int64_t nValueIn = 0;
1443 for (unsigned int i = 0; i < vin.size(); i++)
1445 auto prevout = vin[i].prevout;
1446 assert(inputs.count(prevout.hash) > 0);
1447 CTxIndex& txindex = inputs[prevout.hash].first;
1448 CTransaction& txPrev = inputs[prevout.hash].second;
1450 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1451 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()));
1453 // If prev is coinbase or coinstake, check that it's matured
1454 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1455 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1456 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1457 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1459 // ppcoin: check transaction timestamp
1460 if (txPrev.nTime > nTime)
1461 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1463 // Check for negative or overflow input values
1464 nValueIn += txPrev.vout[prevout.n].nValue;
1465 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1466 return DoS(100, error("ConnectInputs() : txin values out of range"));
1471 pvChecks->reserve(vin.size());
1473 // The first loop above does all the inexpensive checks.
1474 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1475 // Helps prevent CPU exhaustion attacks.
1476 for (unsigned int i = 0; i < vin.size(); i++)
1478 auto prevout = vin[i].prevout;
1479 assert(inputs.count(prevout.hash) > 0);
1480 CTxIndex& txindex = inputs[prevout.hash].first;
1481 CTransaction& txPrev = inputs[prevout.hash].second;
1483 // Check for conflicts (double-spend)
1484 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1485 // for an attacker to attempt to split the network.
1486 if (!txindex.vSpent[prevout.n].IsNull())
1487 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());
1489 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1490 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1491 // still computed and checked, and any change will be caught at the next checkpoint.
1495 CScriptCheck check(txPrev, *this, i, flags, 0);
1498 pvChecks->push_back(CScriptCheck());
1499 check.swap(pvChecks->back());
1503 if (flags & STRICT_FLAGS)
1505 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1506 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1508 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1510 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1514 // Mark outpoints as spent
1515 txindex.vSpent[prevout.n] = posThisTx;
1518 if (fBlock || fMiner)
1520 mapTestPool[prevout.hash] = txindex;
1526 if (nTime > Checkpoints::GetLastCheckpointTime())
1528 unsigned int nTxSize = GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
1530 // coin stake tx earns reward instead of paying fee
1532 if (!GetCoinAge(txdb, nCoinAge))
1533 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1535 auto nReward = GetValueOut() - nValueIn;
1536 auto nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1538 if (nReward > nCalculatedReward)
1539 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1544 if (nValueIn < GetValueOut())
1545 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1547 // Tally transaction fees
1548 auto nTxFee = nValueIn - GetValueOut();
1550 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1553 if (!MoneyRange(nFees))
1554 return DoS(100, error("ConnectInputs() : nFees out of range"));
1562 bool CTransaction::ClientConnectInputs()
1567 // Take over previous transactions' spent pointers
1570 int64_t nValueIn = 0;
1571 for (unsigned int i = 0; i < vin.size(); i++)
1573 // Get prev tx from single transactions in memory
1574 auto prevout = vin[i].prevout;
1575 if (!mempool.exists(prevout.hash))
1577 CTransaction& txPrev = mempool.lookup(prevout.hash);
1579 if (prevout.n >= txPrev.vout.size())
1583 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1584 return error("ClientConnectInputs() : VerifySignature failed");
1586 ///// this is redundant with the mempool.mapNextTx stuff,
1587 ///// not sure which I want to get rid of
1588 ///// this has to go away now that posNext is gone
1589 // // Check for conflicts
1590 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1591 // return error("ConnectInputs() : prev tx already used");
1593 // // Flag outpoints as used
1594 // txPrev.vout[prevout.n].posNext = posThisTx;
1596 nValueIn += txPrev.vout[prevout.n].nValue;
1598 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1599 return error("ClientConnectInputs() : txin values out of range");
1601 if (GetValueOut() > nValueIn)
1611 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1613 // Disconnect in reverse order
1614 for (int i = vtx.size()-1; i >= 0; i--)
1615 if (!vtx[i].DisconnectInputs(txdb))
1618 // Update block index on disk without changing it in memory.
1619 // The memory index structure will be changed after the db commits.
1622 CDiskBlockIndex blockindexPrev(pindex->pprev);
1623 blockindexPrev.hashNext = 0;
1624 if (!txdb.WriteBlockIndex(blockindexPrev))
1625 return error("DisconnectBlock() : WriteBlockIndex failed");
1628 // ppcoin: clean up wallet after disconnecting coinstake
1629 for(CTransaction& tx : vtx)
1630 SyncWithWallets(tx, this, false, false);
1635 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1637 void ThreadScriptCheck(void*) {
1638 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1639 RenameThread("novacoin-scriptch");
1640 scriptcheckqueue.Thread();
1641 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1644 void ThreadScriptCheckQuit() {
1645 scriptcheckqueue.Quit();
1648 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1650 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1651 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1654 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1655 // unless those are already completely spent.
1656 // If such overwrites are allowed, coinbases and transactions depending upon those
1657 // can be duplicated to remove the ability to spend the first instance -- even after
1658 // being sent to another address.
1659 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1660 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1661 // already refuses previously-known transaction ids entirely.
1662 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1663 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1664 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1665 // initial block download.
1666 bool fEnforceBIP30 = true; // Always active in NovaCoin
1667 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1669 //// issue here: it doesn't know the version
1670 unsigned int nTxPos;
1672 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1673 // 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
1676 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1678 map<uint256, CTxIndex> mapQueuedChanges;
1679 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1682 int64_t nValueIn = 0;
1683 int64_t nValueOut = 0;
1684 unsigned int nSigOps = 0;
1687 auto hashTx = tx.GetHash();
1689 if (fEnforceBIP30) {
1690 CTxIndex txindexOld;
1691 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1692 for(CDiskTxPos &pos : txindexOld.vSpent)
1698 nSigOps += tx.GetLegacySigOpCount();
1699 if (nSigOps > MAX_BLOCK_SIGOPS)
1700 return DoS(100, error("ConnectBlock() : too many sigops"));
1702 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1704 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1706 MapPrevTx mapInputs;
1707 if (tx.IsCoinBase())
1708 nValueOut += tx.GetValueOut();
1712 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1715 // Add in sigops done by pay-to-script-hash inputs;
1716 // this is to prevent a "rogue miner" from creating
1717 // an incredibly-expensive-to-validate block.
1718 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1719 if (nSigOps > MAX_BLOCK_SIGOPS)
1720 return DoS(100, error("ConnectBlock() : too many sigops"));
1722 auto nTxValueIn = tx.GetValueIn(mapInputs);
1723 auto nTxValueOut = tx.GetValueOut();
1724 nValueIn += nTxValueIn;
1725 nValueOut += nTxValueOut;
1726 if (!tx.IsCoinStake())
1727 nFees += nTxValueIn - nTxValueOut;
1729 unsigned int nFlags = SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH;
1731 if (tx.nTime >= CHECKLOCKTIMEVERIFY_SWITCH_TIME) {
1732 nFlags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1733 // OP_CHECKSEQUENCEVERIFY is senseless without BIP68, so we're going disable it for now.
1734 // nFlags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1737 std::vector<CScriptCheck> vChecks;
1738 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, nFlags, nScriptCheckThreads ? &vChecks : NULL))
1740 control.Add(vChecks);
1743 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1746 if (!control.Wait())
1747 return DoS(100, false);
1749 if (IsProofOfWork())
1751 auto nBlockReward = GetProofOfWorkReward(nBits, nFees);
1753 // Check coinbase reward
1754 if (vtx[0].GetValueOut() > nBlockReward)
1755 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1756 vtx[0].GetValueOut(),
1760 // track money supply and mint amount info
1761 pindex->nMint = nValueOut - nValueIn + nFees;
1762 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1763 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1764 return error("Connect() : WriteBlockIndex for pindex failed");
1766 // fees are not collected by proof-of-stake miners
1767 // fees are destroyed to compensate the entire network
1768 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1769 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
1774 // Write queued txindex changes
1775 for (auto mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1777 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1778 return error("ConnectBlock() : UpdateTxIndex failed");
1781 // Update block index on disk without changing it in memory.
1782 // The memory index structure will be changed after the db commits.
1785 CDiskBlockIndex blockindexPrev(pindex->pprev);
1786 blockindexPrev.hashNext = pindex->GetBlockHash();
1787 if (!txdb.WriteBlockIndex(blockindexPrev))
1788 return error("ConnectBlock() : WriteBlockIndex failed");
1791 // Watch for transactions paying to me
1792 for(CTransaction& tx : vtx)
1793 SyncWithWallets(tx, this, true);
1799 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1801 printf("REORGANIZE\n");
1804 CBlockIndex* pfork = pindexBest;
1805 CBlockIndex* plonger = pindexNew;
1806 while (pfork != plonger)
1808 while (plonger->nHeight > pfork->nHeight)
1809 if ((plonger = plonger->pprev) == NULL)
1810 return error("Reorganize() : plonger->pprev is null");
1811 if (pfork == plonger)
1813 if ((pfork = pfork->pprev) == NULL)
1814 return error("Reorganize() : pfork->pprev is null");
1817 // List of what to disconnect
1818 vector<CBlockIndex*> vDisconnect;
1819 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1820 vDisconnect.push_back(pindex);
1822 // List of what to connect
1823 vector<CBlockIndex*> vConnect;
1824 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1825 vConnect.push_back(pindex);
1826 reverse(vConnect.begin(), vConnect.end());
1828 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());
1829 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());
1831 // Disconnect shorter branch
1832 vector<CTransaction> vResurrect;
1833 for(CBlockIndex* pindex : vDisconnect)
1836 if (!block.ReadFromDisk(pindex))
1837 return error("Reorganize() : ReadFromDisk for disconnect failed");
1838 if (!block.DisconnectBlock(txdb, pindex))
1839 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1841 // Queue memory transactions to resurrect
1842 for(const CTransaction& tx : block.vtx)
1843 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1844 vResurrect.push_back(tx);
1847 // Connect longer branch
1848 vector<CTransaction> vDelete;
1849 for (unsigned int i = 0; i < vConnect.size(); i++)
1851 CBlockIndex* pindex = vConnect[i];
1853 if (!block.ReadFromDisk(pindex))
1854 return error("Reorganize() : ReadFromDisk for connect failed");
1855 if (!block.ConnectBlock(txdb, pindex))
1858 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1861 // Queue memory transactions to delete
1862 for(const CTransaction& tx : block.vtx)
1863 vDelete.push_back(tx);
1865 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1866 return error("Reorganize() : WriteHashBestChain failed");
1868 // Make sure it's successfully written to disk before changing memory structure
1869 if (!txdb.TxnCommit())
1870 return error("Reorganize() : TxnCommit failed");
1872 // Disconnect shorter branch
1873 for(CBlockIndex* pindex : vDisconnect)
1875 pindex->pprev->pnext = NULL;
1877 // Connect longer branch
1878 for(CBlockIndex* pindex : vConnect)
1880 pindex->pprev->pnext = pindex;
1882 // Resurrect memory transactions that were in the disconnected branch
1883 for(CTransaction& tx : vResurrect)
1884 tx.AcceptToMemoryPool(txdb, false);
1886 // Delete redundant memory transactions that are in the connected branch
1887 for(CTransaction& tx : vDelete)
1890 printf("REORGANIZE: done\n");
1896 // Called from inside SetBestChain: attaches a block to the new best chain being built
1897 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1899 auto hash = GetHash();
1901 // Adding to current best branch
1902 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1905 InvalidChainFound(pindexNew);
1908 if (!txdb.TxnCommit())
1909 return error("SetBestChain() : TxnCommit failed");
1911 // Add to current best branch
1912 pindexNew->pprev->pnext = pindexNew;
1914 // Delete redundant memory transactions
1915 for(CTransaction& tx : vtx)
1921 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1923 auto hash = GetHash();
1925 if (!txdb.TxnBegin())
1926 return error("SetBestChain() : TxnBegin failed");
1928 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1930 txdb.WriteHashBestChain(hash);
1931 if (!txdb.TxnCommit())
1932 return error("SetBestChain() : TxnCommit failed");
1933 pindexGenesisBlock = pindexNew;
1935 else if (hashPrevBlock == hashBestChain)
1937 if (!SetBestChainInner(txdb, pindexNew))
1938 return error("SetBestChain() : SetBestChainInner failed");
1942 // the first block in the new chain that will cause it to become the new best chain
1943 CBlockIndex *pindexIntermediate = pindexNew;
1945 // list of blocks that need to be connected afterwards
1946 std::vector<CBlockIndex*> vpindexSecondary;
1948 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1949 // Try to limit how much needs to be done inside
1950 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1952 vpindexSecondary.push_back(pindexIntermediate);
1953 pindexIntermediate = pindexIntermediate->pprev;
1956 if (!vpindexSecondary.empty())
1957 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
1959 // Switch to new best branch
1960 if (!Reorganize(txdb, pindexIntermediate))
1963 InvalidChainFound(pindexNew);
1964 return error("SetBestChain() : Reorganize failed");
1967 // Connect further blocks
1968 for (std::vector<CBlockIndex*>::reverse_iterator rit = vpindexSecondary.rbegin(); rit != vpindexSecondary.rend(); ++rit)
1971 if (!block.ReadFromDisk(*rit))
1973 printf("SetBestChain() : ReadFromDisk failed\n");
1976 if (!txdb.TxnBegin()) {
1977 printf("SetBestChain() : TxnBegin 2 failed\n");
1980 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1981 if (!block.SetBestChainInner(txdb, *rit))
1986 // Update best block in wallet (so we can detect restored wallets)
1987 bool fIsInitialDownload = IsInitialBlockDownload();
1988 if (!fIsInitialDownload)
1990 const CBlockLocator locator(pindexNew);
1991 ::SetBestChain(locator);
1995 hashBestChain = hash;
1996 pindexBest = pindexNew;
1997 pblockindexFBBHLast = NULL;
1998 nBestHeight = pindexBest->nHeight;
1999 nBestChainTrust = pindexNew->nChainTrust;
2000 nTimeBestReceived = GetTime();
2001 nTransactionsUpdated++;
2003 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2005 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
2006 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2007 CBigNum(nBestChainTrust).ToString().c_str(),
2008 nBestBlockTrust.Get64(),
2009 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2011 // Check the version of the last 100 blocks to see if we need to upgrade:
2012 if (!fIsInitialDownload)
2015 const CBlockIndex* pindex = pindexBest;
2016 for (int i = 0; i < 100 && pindex != NULL; i++)
2018 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2020 pindex = pindex->pprev;
2023 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2024 if (nUpgraded > 100/2)
2025 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2026 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2029 auto strCmd = GetArg("-blocknotify", "");
2031 if (!fIsInitialDownload && !strCmd.empty())
2033 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
2034 boost::thread t(runCommand, strCmd); // thread runs free
2040 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2041 // Only those coins meeting minimum age requirement counts. As those
2042 // transactions not in main chain are not currently indexed so we
2043 // might not find out about their coin age. Older transactions are
2044 // guaranteed to be in main chain by sync-checkpoint. This rule is
2045 // introduced to help nodes establish a consistent view of the coin
2046 // age (trust score) of competing branches.
2047 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2049 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2055 for(const CTxIn& txin : vin)
2057 // First try finding the previous transaction in database
2058 CTransaction txPrev;
2060 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2061 continue; // previous transaction not in main chain
2062 if (nTime < txPrev.nTime)
2063 return false; // Transaction timestamp violation
2065 // Read block header
2067 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2068 return false; // unable to read block of previous transaction
2069 if (block.GetBlockTime() + nStakeMinAge > nTime)
2070 continue; // only count coins meeting min age requirement
2072 auto nValueIn = txPrev.vout[txin.prevout.n].nValue;
2073 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2075 if (fDebug && GetBoolArg("-printcoinage"))
2076 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2079 auto bnCoinDay = bnCentSecond * CENT / COIN / nOneDay;
2080 if (fDebug && GetBoolArg("-printcoinage"))
2081 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2082 nCoinAge = bnCoinDay.getuint64();
2086 // ppcoin: total coin age spent in block, in the unit of coin-days.
2087 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2092 for(const CTransaction& tx : vtx)
2094 uint64_t nTxCoinAge;
2095 if (tx.GetCoinAge(txdb, nTxCoinAge))
2096 nCoinAge += nTxCoinAge;
2101 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2103 if (fDebug && GetBoolArg("-printcoinage"))
2104 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2108 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2110 // Check for duplicate
2111 auto hash = GetHash();
2112 if (mapBlockIndex.count(hash))
2113 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2115 // Construct new block index object
2116 CBlockIndex* pindexNew = new(nothrow) CBlockIndex(nFile, nBlockPos, *this);
2118 return error("AddToBlockIndex() : new CBlockIndex failed");
2119 pindexNew->phashBlock = &hash;
2120 auto miPrev = mapBlockIndex.find(hashPrevBlock);
2121 if (miPrev != mapBlockIndex.end())
2123 pindexNew->pprev = (*miPrev).second;
2124 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2127 // ppcoin: compute chain trust score
2128 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2130 // ppcoin: compute stake entropy bit for stake modifier
2131 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2132 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2134 // ppcoin: record proof-of-stake hash value
2135 if (pindexNew->IsProofOfStake())
2137 if (!mapProofOfStake.count(hash))
2138 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2139 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2142 // ppcoin: compute stake modifier
2143 uint64_t nStakeModifier = 0;
2144 bool fGeneratedStakeModifier = false;
2145 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2146 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2147 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2148 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2149 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2150 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2152 // Add to mapBlockIndex
2153 auto mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2154 if (pindexNew->IsProofOfStake())
2155 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2156 pindexNew->phashBlock = &((*mi).first);
2158 // Write to disk block index
2160 if (!txdb.TxnBegin())
2162 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2163 if (!txdb.TxnCommit())
2167 if (pindexNew->nChainTrust > nBestChainTrust)
2168 if (!SetBestChain(txdb, pindexNew))
2171 if (pindexNew == pindexBest)
2173 // Notify UI to display prev block's coinbase if it was ours
2174 static uint256 hashPrevBestCoinBase;
2175 UpdatedTransaction(hashPrevBestCoinBase);
2176 hashPrevBestCoinBase = vtx[0].GetHash();
2179 static int8_t counter = 0;
2180 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2181 uiInterface.NotifyBlocksChanged();
2188 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2190 // These are checks that are independent of context
2191 // that can be verified before saving an orphan block.
2193 set<uint256> uniqueTx; // tx hashes
2194 unsigned int nSigOps = 0; // total sigops
2197 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2198 return DoS(100, error("CheckBlock() : size limits failed"));
2200 bool fProofOfStake = IsProofOfStake();
2202 // First transaction must be coinbase, the rest must not be
2203 if (!vtx[0].IsCoinBase())
2204 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2206 if (!vtx[0].CheckTransaction())
2207 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2209 uniqueTx.insert(vtx[0].GetHash());
2210 nSigOps += vtx[0].GetLegacySigOpCount();
2214 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2215 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2217 // nNonce must be zero for proof-of-stake blocks
2219 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2221 // Coinbase output should be empty if proof-of-stake block
2222 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2223 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2225 // Check coinstake timestamp
2226 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2227 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2229 // NovaCoin: check proof-of-stake block signature
2230 if (fCheckSig && !CheckBlockSignature())
2231 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2233 if (!vtx[1].CheckTransaction())
2234 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2236 uniqueTx.insert(vtx[1].GetHash());
2237 nSigOps += vtx[1].GetLegacySigOpCount();
2241 // Check proof of work matches claimed amount
2242 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2243 return DoS(50, error("CheckBlock() : proof of work failed"));
2246 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2247 return error("CheckBlock() : block timestamp too far in the future");
2249 // Check coinbase timestamp
2250 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2251 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2254 // Iterate all transactions starting from second for proof-of-stake block
2255 // or first for proof-of-work block
2256 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2258 const CTransaction& tx = vtx[i];
2260 // Reject coinbase transactions at non-zero index
2261 if (tx.IsCoinBase())
2262 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2264 // Reject coinstake transactions at index != 1
2265 if (tx.IsCoinStake())
2266 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2268 // Check transaction timestamp
2269 if (GetBlockTime() < (int64_t)tx.nTime)
2270 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2272 // Check transaction consistency
2273 if (!tx.CheckTransaction())
2274 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2276 // Add transaction hash into list of unique transaction IDs
2277 uniqueTx.insert(tx.GetHash());
2279 // Calculate sigops count
2280 nSigOps += tx.GetLegacySigOpCount();
2283 // Check for duplicate txids. This is caught by ConnectInputs(),
2284 // but catching it earlier avoids a potential DoS attack:
2285 if (uniqueTx.size() != vtx.size())
2286 return DoS(100, error("CheckBlock() : duplicate transaction"));
2288 // Reject block if validation would consume too much resources.
2289 if (nSigOps > MAX_BLOCK_SIGOPS)
2290 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2292 // Check merkle root
2293 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2294 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2299 bool CBlock::AcceptBlock()
2301 // Check for duplicate
2302 auto hash = GetHash();
2303 if (mapBlockIndex.count(hash))
2304 return error("AcceptBlock() : block already in mapBlockIndex");
2306 // Get prev block index
2307 auto mi = mapBlockIndex.find(hashPrevBlock);
2308 if (mi == mapBlockIndex.end())
2309 return DoS(10, error("AcceptBlock() : prev block not found"));
2310 CBlockIndex* pindexPrev = (*mi).second;
2311 int nHeight = pindexPrev->nHeight+1;
2313 // Check proof-of-work or proof-of-stake
2314 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2315 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2317 int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
2318 int nMaxOffset = 12 * nOneHour; // 12 hours
2319 if (fTestNet || pindexPrev->nTime < 1450569600)
2320 nMaxOffset = 7 * nOneWeek; // One week (permanently on testNet or until 20 Dec, 2015 on mainNet)
2322 // Check timestamp against prev
2323 if (GetBlockTime() <= nMedianTimePast || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2324 return error("AcceptBlock() : block's timestamp is too early");
2326 // Don't accept blocks with future timestamps
2327 if (pindexPrev->nHeight > 1 && nMedianTimePast + nMaxOffset < GetBlockTime())
2328 return error("AcceptBlock() : block's timestamp is too far in the future");
2330 // Check that all transactions are finalized
2331 for(const CTransaction& tx : vtx)
2332 if (!tx.IsFinal(nHeight, GetBlockTime()))
2333 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2335 // Check that the block chain matches the known block chain up to a checkpoint
2336 if (!Checkpoints::CheckHardened(nHeight, hash))
2337 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2339 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2341 // Check that the block satisfies synchronized checkpoint
2342 if (CheckpointsMode == Checkpoints::CP_STRICT && !cpSatisfies)
2343 return error("AcceptBlock() : rejected by synchronized checkpoint");
2345 if (CheckpointsMode == Checkpoints::CP_ADVISORY && !cpSatisfies)
2346 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2348 // Enforce rule that the coinbase starts with serialized block height
2349 auto expect = CScript() << nHeight;
2350 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2351 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2352 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2354 // Write block to history file
2355 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2356 return error("AcceptBlock() : out of disk space");
2357 unsigned int nFile = std::numeric_limits<unsigned int>::max();
2358 unsigned int nBlockPos = 0;
2359 if (!WriteToDisk(nFile, nBlockPos))
2360 return error("AcceptBlock() : WriteToDisk failed");
2361 if (!AddToBlockIndex(nFile, nBlockPos))
2362 return error("AcceptBlock() : AddToBlockIndex failed");
2364 // Relay inventory, but don't relay old inventory during initial block download
2365 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2366 if (hashBestChain == hash)
2369 for(CNode* pnode : vNodes)
2370 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2371 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2374 // ppcoin: check pending sync-checkpoint
2375 Checkpoints::AcceptPendingSyncCheckpoint();
2380 uint256 CBlockIndex::GetBlockTrust() const
2383 bnTarget.SetCompact(nBits);
2388 // Return 1 for the first 12 blocks
2389 if (pprev == NULL || pprev->nHeight < 12)
2392 const CBlockIndex* currentIndex = pprev;
2394 if(IsProofOfStake())
2396 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2398 // Return 1/3 of score if parent block is not the PoW block
2399 if (!pprev->IsProofOfWork())
2400 return (bnNewTrust / 3).getuint256();
2404 // Check last 12 blocks type
2405 while (pprev->nHeight - currentIndex->nHeight < 12)
2407 if (currentIndex->IsProofOfWork())
2409 currentIndex = currentIndex->pprev;
2412 // Return 1/3 of score if less than 3 PoW blocks found
2414 return (bnNewTrust / 3).getuint256();
2416 return bnNewTrust.getuint256();
2420 // Calculate work amount for block
2421 CBigNum bnPoWTrust = CBigNum(nPoWBase) / (bnTarget+1);
2423 // Set nPowTrust to 1 if PoW difficulty is too low
2427 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2429 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2430 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2431 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2435 // Check last 12 blocks type
2436 while (pprev->nHeight - currentIndex->nHeight < 12)
2438 if (currentIndex->IsProofOfStake())
2440 currentIndex = currentIndex->pprev;
2443 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2445 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2447 bnTarget.SetCompact(pprev->nBits);
2452 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2454 // Return nPoWTrust + full trust score for previous block nBits
2455 return (bnPoWTrust + bnNewTrust).getuint256();
2459 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2461 unsigned int nFound = 0;
2462 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2464 if (pstart->nVersion >= minVersion)
2466 pstart = pstart->pprev;
2468 return (nFound >= nRequired);
2471 bool static ReserealizeBlockSignature(CBlock* pblock)
2473 if (pblock->IsProofOfWork())
2475 pblock->vchBlockSig.clear();
2479 return CPubKey::ReserealizeSignature(pblock->vchBlockSig);
2482 bool static IsCanonicalBlockSignature(CBlock* pblock)
2484 if (pblock->IsProofOfWork())
2485 return pblock->vchBlockSig.empty();
2487 return IsDERSignature(pblock->vchBlockSig);
2490 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2492 // Check for duplicate
2493 auto hash = pblock->GetHash();
2494 if (mapBlockIndex.count(hash))
2495 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2496 if (mapOrphanBlocks.count(hash))
2497 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2499 // Check that block isn't listed as unconditionally banned.
2500 if (!Checkpoints::CheckBanned(hash)) {
2502 pfrom->Misbehaving(100);
2503 return error("ProcessBlock() : block %s is rejected by hard-coded banlist", hash.GetHex().substr(0,20).c_str());
2506 // Check proof-of-stake
2507 // Limited duplicity on stake: prevents block flood attack
2508 // Duplicate stake allowed only when there is orphan child block
2509 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2510 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());
2512 // Strip the garbage from newly received blocks, if we found some
2513 if (!IsCanonicalBlockSignature(pblock)) {
2514 if (!ReserealizeBlockSignature(pblock))
2515 printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2518 // Preliminary checks
2519 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2520 return error("ProcessBlock() : CheckBlock FAILED");
2522 // ppcoin: verify hash target and signature of coinstake tx
2523 if (pblock->IsProofOfStake())
2525 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2526 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2528 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2529 return false; // do not error here as we expect this during initial block download
2531 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2532 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2535 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2536 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2538 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2539 auto deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2541 bnNewBlock.SetCompact(pblock->nBits);
2544 if (pblock->IsProofOfStake())
2545 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2547 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2549 if (bnNewBlock > bnRequired)
2552 pfrom->Misbehaving(100);
2553 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2557 // ppcoin: ask for pending sync-checkpoint if any
2558 if (!IsInitialBlockDownload())
2559 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2561 // If don't already have its previous block, shunt it off to holding area until we get it
2562 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2564 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2565 // ppcoin: check proof-of-stake
2566 if (pblock->IsProofOfStake())
2568 // Limited duplicity on stake: prevents block flood attack
2569 // Duplicate stake allowed only when there is orphan child block
2570 if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2571 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());
2573 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2575 CBlock* pblock2 = new CBlock(*pblock);
2576 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2577 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2579 // Ask this guy to fill in what we're missing
2582 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2583 // ppcoin: getblocks may not obtain the ancestor block rejected
2584 // earlier by duplicate-stake check so we ask for it again directly
2585 if (!IsInitialBlockDownload())
2586 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2592 if (!pblock->AcceptBlock())
2593 return error("ProcessBlock() : AcceptBlock FAILED");
2595 // Recursively process any orphan blocks that depended on this one
2596 vector<uint256> vWorkQueue;
2597 vWorkQueue.push_back(hash);
2598 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2600 auto hashPrev = vWorkQueue[i];
2601 for (auto mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2602 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2605 CBlock* pblockOrphan = (*mi).second;
2606 if (pblockOrphan->AcceptBlock())
2607 vWorkQueue.push_back(pblockOrphan->GetHash());
2608 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2609 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2610 delete pblockOrphan;
2612 mapOrphanBlocksByPrev.erase(hashPrev);
2615 printf("ProcessBlock: ACCEPTED\n");
2617 // ppcoin: if responsible for sync-checkpoint send it
2618 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2619 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2624 // ppcoin: check block signature
2625 bool CBlock::CheckBlockSignature() const
2627 if (vchBlockSig.empty())
2630 txnouttype whichType;
2631 vector<valtype> vSolutions;
2632 if (!Solver(vtx[1].vout[1].scriptPubKey, whichType, vSolutions))
2635 if (whichType == TX_PUBKEY)
2637 auto& vchPubKey = vSolutions[0];
2638 CPubKey key(vchPubKey);
2641 return key.Verify(GetHash(), vchBlockSig);
2647 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2649 uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2651 // Check for nMinDiskSpace bytes (currently 50MB)
2652 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2655 string strMessage = _("Warning: Disk space is low!");
2656 strMiscWarning = strMessage;
2657 printf("*** %s\n", strMessage.c_str());
2658 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2665 static filesystem::path BlockFilePath(unsigned int nFile)
2667 string strBlockFn = strprintf("blk%04u.dat", nFile);
2668 return GetDataDir() / strBlockFn;
2671 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2673 if ((nFile < 1) || (nFile == std::numeric_limits<uint32_t>::max()))
2675 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2678 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2680 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2689 static unsigned int nCurrentBlockFile = 1;
2691 FILE* AppendBlockFile(unsigned int& nFileRet)
2696 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2699 if (fseek(file, 0, SEEK_END) != 0)
2701 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2702 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2704 nFileRet = nCurrentBlockFile;
2708 nCurrentBlockFile++;
2712 void UnloadBlockIndex()
2714 mapBlockIndex.clear();
2715 setStakeSeen.clear();
2716 pindexGenesisBlock = NULL;
2718 nBestChainTrust = 0;
2719 nBestInvalidTrust = 0;
2724 bool LoadBlockIndex(bool fAllowNew)
2728 nNetworkID = 0xefc0f2cd;
2730 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2731 nStakeMinAge = 2 * nOneHour; // test net min age is 2 hours
2732 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2733 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2734 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2741 if (!txdb.LoadBlockIndex())
2745 // Init with genesis block
2747 if (mapBlockIndex.empty())
2756 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2757 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2758 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2760 // vMerkleTree: 4cb33b3b6a
2764 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2765 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2766 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2768 // vMerkleTree: 4cb33b3b6a
2770 const string strTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2772 txNew.nTime = 1360105017;
2773 txNew.vin.resize(1);
2774 txNew.vout.resize(1);
2775 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>(strTimestamp.begin(), strTimestamp.end());
2776 txNew.vout[0].SetEmpty();
2778 block.vtx.push_back(txNew);
2779 block.hashPrevBlock = 0;
2780 block.hashMerkleRoot = block.BuildMerkleTree();
2782 block.nTime = 1360105017;
2783 block.nBits = bnProofOfWorkLimit.GetCompact();
2784 block.nNonce = !fTestNet ? 1575379 : 46534;
2787 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2789 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2790 assert(block.CheckBlock());
2792 // Start new block file
2794 unsigned int nBlockPos;
2795 if (!block.WriteToDisk(nFile, nBlockPos))
2796 return error("LoadBlockIndex() : writing genesis block to disk failed");
2797 if (!block.AddToBlockIndex(nFile, nBlockPos))
2798 return error("LoadBlockIndex() : genesis block not accepted");
2800 // initialize synchronized checkpoint
2801 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2802 return error("LoadBlockIndex() : failed to init sync checkpoint");
2804 // upgrade time set to zero if txdb initialized
2806 if (!txdb.WriteModifierUpgradeTime(0))
2807 return error("LoadBlockIndex() : failed to init upgrade info");
2808 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2814 string strPubKey = "";
2815 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2817 // write checkpoint master key to db
2819 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2820 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2821 if (!txdb.TxnCommit())
2822 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2823 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2824 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2827 // upgrade time set to zero if blocktreedb initialized
2828 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2830 if (nModifierUpgradeTime)
2831 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2833 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2837 nModifierUpgradeTime = GetTime();
2838 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2839 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2840 return error("LoadBlockIndex() : failed to write upgrade info");
2853 void PrintBlockTree()
2855 // pre-compute tree structure
2856 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2857 for (auto mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2859 CBlockIndex* pindex = (*mi).second;
2860 mapNext[pindex->pprev].push_back(pindex);
2862 //while (rand() % 3 == 0)
2863 // mapNext[pindex->pprev].push_back(pindex);
2866 vector<pair<int, CBlockIndex*> > vStack;
2867 vStack.push_back(make_pair(0, pindexGenesisBlock));
2870 while (!vStack.empty())
2872 int nCol = vStack.back().first;
2873 CBlockIndex* pindex = vStack.back().second;
2876 // print split or gap
2877 if (nCol > nPrevCol)
2879 for (int i = 0; i < nCol-1; i++)
2883 else if (nCol < nPrevCol)
2885 for (int i = 0; i < nCol; i++)
2892 for (int i = 0; i < nCol; i++)
2897 block.ReadFromDisk(pindex);
2898 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
2902 block.GetHash().ToString().c_str(),
2904 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2905 FormatMoney(pindex->nMint).c_str(),
2908 PrintWallets(block);
2910 // put the main time-chain first
2911 vector<CBlockIndex*>& vNext = mapNext[pindex];
2912 for (unsigned int i = 0; i < vNext.size(); i++)
2914 if (vNext[i]->pnext)
2916 swap(vNext[0], vNext[i]);
2922 for (unsigned int i = 0; i < vNext.size(); i++)
2923 vStack.push_back(make_pair(nCol+i, vNext[i]));
2927 bool LoadExternalBlockFile(FILE* fileIn, CClientUIInterface& uiInterface)
2929 auto nStart = GetTimeMillis();
2930 vector<uint8_t> pchData(10 * (8+MAX_BLOCK_SIZE));
2931 int32_t nLoaded = 0;
2935 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2937 while (nPos != std::numeric_limits<uint32_t>::max() && blkdat.good() && !fRequestShutdown)
2941 fseek(blkdat, nPos, SEEK_SET);
2942 auto nRead = fread(&pchData[0], 1, pchData.size(), blkdat);
2945 nPos = numeric_limits<uint32_t>::max();
2948 auto it = pchData.begin();
2949 while(it != pchData.end() && !fRequestShutdown)
2951 auto nBlockLength = *reinterpret_cast<const uint32_t*>(&(*(it+4)));
2952 auto SeekToNext = [&pchData, &it, &nPos, &nBlockLength]() {
2954 it = search(it+8, pchData.end(), BEGIN(nNetworkID), END(nNetworkID));
2955 if (it != pchData.end())
2956 nPos += (it - previt);
2958 if (nBlockLength > 0)
2960 if (nBlockLength > (uint32_t)distance(it, pchData.end()))
2963 break; // We've reached the end of buffer
2970 vector<unsigned char> vchBlockBytes(it+8, it+8+nBlockLength);
2971 CDataStream blockData(vchBlockBytes, SER_NETWORK, PROTOCOL_VERSION);
2974 catch (const std::exception&)
2976 printf("LoadExternalBlockFile() : Deserialize error caught at the position %" PRIu32 ", this block may be truncated.", nPos);
2980 if (ProcessBlock(NULL, &block))
2982 advance(it, 8 + nBlockLength);
2983 nPos += (8 + nBlockLength);
2985 static int64_t nLastUpdate = 0;
2986 if (GetTimeMillis() - nLastUpdate > 1000)
2988 uiInterface.InitMessage(strprintf(_("%" PRId32 " blocks were read."), nLoaded));
2989 nLastUpdate = GetTimeMillis();
3000 while(!fRequestShutdown);
3003 catch (const std::exception&) {
3004 printf("%s() : I/O error caught during load\n",
3005 BOOST_CURRENT_FUNCTION);
3008 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3012 //////////////////////////////////////////////////////////////////////////////
3017 extern map<uint256, CAlert> mapAlerts;
3018 extern CCriticalSection cs_mapAlerts;
3020 string GetWarnings(string strFor)
3023 string strStatusBar;
3026 if (GetBoolArg("-testsafemode"))
3029 // Misc warnings like out of disk space and clock is wrong
3030 if (!strMiscWarning.empty())
3033 strStatusBar = strMiscWarning;
3036 // if detected unmet upgrade requirement enter safe mode
3037 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3038 if (IsFixedModifierInterval(nModifierUpgradeTime + nOneDay)) // 1 day margin
3041 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3044 // if detected invalid checkpoint enter safe mode
3045 if (Checkpoints::hashInvalidCheckpoint != 0)
3048 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3054 for(auto& item : mapAlerts)
3056 const CAlert& alert = item.second;
3057 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3059 nPriority = alert.nPriority;
3060 strStatusBar = alert.strStatusBar;
3061 if (nPriority > 1000)
3062 strRPC = strStatusBar;
3067 if (strFor == "statusbar")
3068 return strStatusBar;
3069 else if (strFor == "rpc")
3071 assert(!"GetWarnings() : invalid parameter");
3082 //////////////////////////////////////////////////////////////////////////////
3088 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3090 int nType = inv.GetType();
3091 auto nHash = inv.GetHash();
3097 bool txInMap = false;
3100 txInMap = (mempool.exists(nHash));
3103 mapOrphanTransactions.count(nHash) ||
3104 txdb.ContainsTx(nHash);
3108 return mapBlockIndex.count(nHash) ||
3109 mapOrphanBlocks.count(nHash);
3111 // Don't know what it is, just say we already got one
3115 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3117 static map<CService, CPubKey> mapReuseKey;
3118 RandAddSeedPerfmon();
3120 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3121 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3123 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3127 if (strCommand == "version")
3129 // Each connection can only send one version message
3130 if (pfrom->nVersion != 0)
3132 pfrom->Misbehaving(1);
3139 uint64_t nNonce = 1;
3140 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3141 if (pfrom->nVersion < MIN_PROTO_VERSION)
3143 // Since February 20, 2012, the protocol is initiated at version 209,
3144 // and earlier versions are no longer supported
3145 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3146 pfrom->fDisconnect = true;
3150 if (pfrom->nVersion == 10300)
3151 pfrom->nVersion = 300;
3153 vRecv >> addrFrom >> nNonce;
3155 vRecv >> pfrom->strSubVer;
3157 vRecv >> pfrom->nStartingHeight;
3159 if (pfrom->fInbound && addrMe.IsRoutable())
3161 pfrom->addrLocal = addrMe;
3165 // Disconnect if we connected to ourself
3166 if (nNonce == nLocalHostNonce && nNonce > 1)
3168 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3169 pfrom->fDisconnect = true;
3173 if (pfrom->nVersion < 60010)
3175 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3176 pfrom->fDisconnect = true;
3180 // record my external IP reported by peer
3181 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3182 addrSeenByPeer = addrMe;
3184 // Be shy and don't send version until we hear
3185 if (pfrom->fInbound)
3186 pfrom->PushVersion();
3188 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3190 AddTimeData(pfrom->addr, nTime);
3193 pfrom->PushMessage("verack");
3194 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3196 if (!pfrom->fInbound)
3198 // Advertise our address
3199 if (!fNoListen && !IsInitialBlockDownload())
3201 auto addr = GetLocalAddress(&pfrom->addr);
3202 if (addr.IsRoutable())
3203 pfrom->PushAddress(addr);
3206 // Get recent addresses
3207 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3209 pfrom->PushMessage("getaddr");
3210 pfrom->fGetAddr = true;
3212 addrman.Good(pfrom->addr);
3214 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3216 addrman.Add(addrFrom, addrFrom);
3217 addrman.Good(addrFrom);
3221 // Ask the first connected node for block updates
3222 static int nAskedForBlocks = 0;
3223 if (!pfrom->fClient && !pfrom->fOneShot &&
3224 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3225 (pfrom->nVersion < NOBLKS_VERSION_START ||
3226 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3227 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3230 pfrom->PushGetBlocks(pindexBest, uint256(0));
3236 for(auto& item : mapAlerts)
3237 item.second.RelayTo(pfrom);
3240 // Relay sync-checkpoint
3242 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3243 if (!Checkpoints::checkpointMessage.IsNull())
3244 Checkpoints::checkpointMessage.RelayTo(pfrom);
3247 pfrom->fSuccessfullyConnected = true;
3249 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());
3251 cPeerBlockCounts.input(pfrom->nStartingHeight);
3253 // ppcoin: ask for pending sync-checkpoint if any
3254 if (!IsInitialBlockDownload())
3255 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3259 else if (pfrom->nVersion == 0)
3261 // Must have a version message before anything else
3262 pfrom->Misbehaving(1);
3267 else if (strCommand == "verack")
3269 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3273 else if (strCommand == "addr")
3275 vector<CAddress> vAddr;
3278 // Don't want addr from older versions unless seeding
3279 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3281 if (vAddr.size() > 1000)
3283 pfrom->Misbehaving(20);
3284 return error("message addr size() = %" PRIszu "", vAddr.size());
3287 // Store the new addresses
3288 vector<CAddress> vAddrOk;
3289 auto nNow = GetAdjustedTime();
3290 auto nSince = nNow - 10 * 60;
3291 for(CAddress& addr : vAddr)
3295 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3296 addr.nTime = nNow - 5 * nOneDay;
3297 pfrom->AddAddressKnown(addr);
3298 bool fReachable = IsReachable(addr);
3299 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3301 // Relay to a limited number of other nodes
3304 // Use deterministic randomness to send to the same nodes for 24 hours
3305 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3306 static uint256 hashSalt;
3308 hashSalt = GetRandHash();
3309 uint64_t hashAddr = addr.GetHash();
3310 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/nOneDay);
3311 hashRand = Hash(hashRand.begin(), hashRand.end());
3312 multimap<uint256, CNode*> mapMix;
3313 for(CNode* pnode : vNodes)
3315 if (pnode->nVersion < CADDR_TIME_VERSION)
3317 unsigned int nPointer;
3318 memcpy(&nPointer, &pnode, sizeof(nPointer));
3319 uint256 hashKey = hashRand ^ nPointer;
3320 hashKey = Hash(hashKey.begin(), hashKey.end());
3321 mapMix.insert(make_pair(hashKey, pnode));
3323 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3324 for (auto mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3325 ((*mi).second)->PushAddress(addr);
3328 // Do not store addresses outside our network
3330 vAddrOk.push_back(addr);
3332 addrman.Add(vAddrOk, pfrom->addr, 2 * nOneHour);
3333 if (vAddr.size() < 1000)
3334 pfrom->fGetAddr = false;
3335 if (pfrom->fOneShot)
3336 pfrom->fDisconnect = true;
3339 else if (strCommand == "inv")
3343 if (vInv.size() > MAX_INV_SZ)
3345 pfrom->Misbehaving(20);
3346 return error("message inv size() = %" PRIszu "", vInv.size());
3349 // find last block in inv vector
3350 int nLastBlock = -1;
3351 for (size_t nInv = 0; nInv < vInv.size(); nInv++) {
3352 if (vInv[vInv.size() - 1 - nInv].GetType() == MSG_BLOCK) {
3353 nLastBlock = (int) (vInv.size() - 1 - nInv);
3358 for (size_t nInv = 0; nInv < vInv.size(); nInv++)
3360 const CInv &inv = vInv[nInv];
3361 int nType = inv.GetType();
3362 auto nHash = inv.GetHash();
3366 pfrom->AddInventoryKnown(inv);
3368 bool fAlreadyHave = AlreadyHave(txdb, inv);
3370 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3374 else if (nType == MSG_BLOCK && mapOrphanBlocks.count(nHash)) {
3375 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[nHash]));
3376 } else if (nType == nLastBlock) {
3377 // In case we are on a very long side-chain, it is possible that we already have
3378 // the last block in an inv bundle sent in response to getblocks. Try to detect
3379 // this situation and push another getblocks to continue.
3380 pfrom->PushGetBlocks(mapBlockIndex[nHash], uint256(0));
3382 printf("force request: %s\n", inv.ToString().c_str());
3385 // Track requests for our stuff
3391 else if (strCommand == "getdata")
3395 if (vInv.size() > MAX_INV_SZ)
3397 pfrom->Misbehaving(20);
3398 return error("message getdata size() = %" PRIszu "", vInv.size());
3401 if (fDebugNet || (vInv.size() != 1))
3402 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3404 for(const CInv& inv : vInv)
3408 if (fDebugNet || (vInv.size() == 1))
3409 printf("received getdata for: %s\n", inv.ToString().c_str());
3411 int nType = inv.GetType();
3412 auto nHash = inv.GetHash();
3414 if (nType == MSG_BLOCK)
3416 // Send block from disk
3417 auto mi = mapBlockIndex.find(nHash);
3418 if (mi != mapBlockIndex.end())
3421 block.ReadFromDisk((*mi).second);
3422 pfrom->PushMessage("block", block);
3424 // Trigger them to send a getblocks request for the next batch of inventory
3425 if (nHash == pfrom->hashContinue)
3427 // ppcoin: send latest proof-of-work block to allow the
3428 // download node to accept as orphan (proof-of-stake
3429 // block might be rejected by stake connection check)
3431 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3432 pfrom->PushMessage("inv", vInv);
3433 pfrom->hashContinue = 0;
3437 else if (inv.IsKnownType())
3439 // Send stream from relay memory
3440 bool pushed = false;
3443 auto mi = mapRelay.find(inv);
3444 if (mi != mapRelay.end()) {
3445 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3449 if (!pushed && nType == MSG_TX) {
3451 if (mempool.exists(nHash)) {
3452 CTransaction tx = mempool.lookup(nHash);
3453 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3456 pfrom->PushMessage("tx", ss);
3461 // Track requests for our stuff
3467 else if (strCommand == "getblocks")
3469 CBlockLocator locator;
3471 vRecv >> locator >> hashStop;
3473 // Find the last block the caller has in the main chain
3474 CBlockIndex* pindex = locator.GetBlockIndex();
3476 // Send the rest of the chain
3478 pindex = pindex->pnext;
3480 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3481 for (; pindex; pindex = pindex->pnext)
3483 if (pindex->GetBlockHash() == hashStop)
3485 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3486 // ppcoin: tell downloading node about the latest block if it's
3487 // without risk being rejected due to stake connection check
3488 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3489 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3492 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3495 // When this block is requested, we'll send an inv that'll make them
3496 // getblocks the next batch of inventory.
3497 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3498 pfrom->hashContinue = pindex->GetBlockHash();
3503 else if (strCommand == "checkpoint")
3505 CSyncCheckpoint checkpoint;
3506 vRecv >> checkpoint;
3508 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3511 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3513 for(CNode* pnode : vNodes)
3514 checkpoint.RelayTo(pnode);
3518 else if (strCommand == "getheaders")
3520 CBlockLocator locator;
3522 vRecv >> locator >> hashStop;
3524 CBlockIndex* pindex = NULL;
3525 if (locator.IsNull())
3527 // If locator is null, return the hashStop block
3528 auto mi = mapBlockIndex.find(hashStop);
3529 if (mi == mapBlockIndex.end())
3531 pindex = (*mi).second;
3535 // Find the last block the caller has in the main chain
3536 pindex = locator.GetBlockIndex();
3538 pindex = pindex->pnext;
3541 vector<CBlock> vHeaders;
3543 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3544 for (; pindex; pindex = pindex->pnext)
3546 vHeaders.push_back(pindex->GetBlockHeader());
3547 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3550 pfrom->PushMessage("headers", vHeaders);
3554 else if (strCommand == "tx")
3556 vector<uint256> vWorkQueue;
3557 vector<uint256> vEraseQueue;
3558 CDataStream vMsg(vRecv);
3563 CInv inv(MSG_TX, tx.GetHash());
3564 pfrom->AddInventoryKnown(inv);
3566 bool fMissingInputs = false;
3567 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3569 auto nHash = inv.GetHash();
3571 SyncWithWallets(tx, NULL, true);
3572 RelayTransaction(tx, nHash);
3573 mapAlreadyAskedFor.erase(inv);
3574 vWorkQueue.push_back(nHash);
3575 vEraseQueue.push_back(nHash);
3577 // Recursively process any orphan transactions that depended on this one
3578 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3580 auto hashPrev = vWorkQueue[i];
3581 for (auto mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3582 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3585 const uint256& orphanTxHash = *mi;
3586 auto& orphanTx = mapOrphanTransactions[orphanTxHash];
3587 bool fMissingInputs2 = false;
3589 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3591 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3592 SyncWithWallets(tx, NULL, true);
3593 RelayTransaction(orphanTx, orphanTxHash);
3594 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3595 vWorkQueue.push_back(orphanTxHash);
3596 vEraseQueue.push_back(orphanTxHash);
3598 else if (!fMissingInputs2)
3601 vEraseQueue.push_back(orphanTxHash);
3602 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3607 for(uint256 hash : vEraseQueue)
3608 EraseOrphanTx(hash);
3610 else if (fMissingInputs)
3614 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3615 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3617 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3619 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3623 else if (strCommand == "block")
3627 auto hashBlock = block.GetHash();
3629 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3632 CInv inv(MSG_BLOCK, hashBlock);
3633 pfrom->AddInventoryKnown(inv);
3635 if (ProcessBlock(pfrom, &block))
3636 mapAlreadyAskedFor.erase(inv);
3637 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3641 // This asymmetric behavior for inbound and outbound connections was introduced
3642 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
3643 // to users' AddrMan and later request them by sending getaddr messages.
3644 // Making users (which are behind NAT and can only make outgoing connections) ignore
3645 // getaddr message mitigates the attack.
3646 else if ((strCommand == "getaddr") && (pfrom->fInbound))
3648 // Don't return addresses older than nCutOff timestamp
3649 int64_t nCutOff = GetTime() - (nNodeLifespan * nOneDay);
3650 pfrom->vAddrToSend.clear();
3651 vector<CAddress> vAddr = addrman.GetAddr();
3652 for(const CAddress &addr : vAddr)
3653 if(addr.nTime > nCutOff)
3654 pfrom->PushAddress(addr);
3658 else if (strCommand == "mempool")
3660 std::vector<uint256> vtxid;
3661 mempool.queryHashes(vtxid);
3663 for (unsigned int i = 0; i < vtxid.size(); i++) {
3664 CInv inv(MSG_TX, vtxid[i]);
3665 vInv.push_back(inv);
3666 if (i == (MAX_INV_SZ - 1))
3669 if (vInv.size() > 0)
3670 pfrom->PushMessage("inv", vInv);
3674 else if (strCommand == "checkorder")
3679 if (!GetBoolArg("-allowreceivebyip"))
3681 pfrom->PushMessage("reply", hashReply, 2, string(""));
3688 /// we have a chance to check the order here
3690 // Keep giving the same key to the same ip until they use it
3691 if (!mapReuseKey.count(pfrom->addr))
3692 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3694 // Send back approval of order and pubkey to use
3695 CScript scriptPubKey;
3696 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3697 pfrom->PushMessage("reply", hashReply, 0, scriptPubKey);
3701 else if (strCommand == "reply")
3706 CRequestTracker tracker;
3708 LOCK(pfrom->cs_mapRequests);
3709 auto mi = pfrom->mapRequests.find(hashReply);
3710 if (mi != pfrom->mapRequests.end())
3712 tracker = (*mi).second;
3713 pfrom->mapRequests.erase(mi);
3716 if (!tracker.IsNull())
3717 tracker.fn(tracker.param1, vRecv);
3721 else if (strCommand == "ping")
3725 // Echo the message back with the nonce. This allows for two useful features:
3727 // 1) A remote node can quickly check if the connection is operational
3728 // 2) Remote nodes can measure the latency of the network thread. If this node
3729 // is overloaded it won't respond to pings quickly and the remote node can
3730 // avoid sending us more work, like chain download requests.
3732 // The nonce stops the remote getting confused between different pings: without
3733 // it, if the remote node sends a ping once per second and this node takes 5
3734 // seconds to respond to each, the 5th ping the remote sends would appear to
3735 // return very quickly.
3736 pfrom->PushMessage("pong", nonce);
3740 else if (strCommand == "alert")
3745 auto alertHash = alert.GetHash();
3746 if (pfrom->setKnown.count(alertHash) == 0)
3748 if (alert.ProcessAlert())
3751 pfrom->setKnown.insert(alertHash);
3754 for(CNode* pnode : vNodes)
3755 alert.RelayTo(pnode);
3759 // Small DoS penalty so peers that send us lots of
3760 // duplicate/expired/invalid-signature/whatever alerts
3761 // eventually get banned.
3762 // This isn't a Misbehaving(100) (immediate ban) because the
3763 // peer might be an older or different implementation with
3764 // a different signature key, etc.
3765 pfrom->Misbehaving(10);
3773 // Ignore unknown commands for extensibility
3777 // Update the last seen time for this node's address
3778 if (pfrom->fNetworkNode)
3779 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3780 AddressCurrentlyConnected(pfrom->addr);
3786 bool ProcessMessages(CNode* pfrom)
3788 CDataStream& vRecv = pfrom->vRecv;
3792 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3796 // (4) message start
3805 // Don't bother if send buffer is too full to respond anyway
3806 if (pfrom->vSend.size() >= SendBufferSize())
3809 // Scan for message start
3810 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(nNetworkID), END(nNetworkID));
3811 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3812 if (vRecv.end() - pstart < nHeaderSize)
3814 if ((int)vRecv.size() > nHeaderSize)
3816 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3817 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3821 if (pstart - vRecv.begin() > 0)
3822 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
3823 vRecv.erase(vRecv.begin(), pstart);
3826 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3831 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3834 string strCommand = hdr.GetCommand();
3837 unsigned int nMessageSize = hdr.nMessageSize;
3838 if (nMessageSize > MAX_SIZE)
3840 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3843 if (nMessageSize > vRecv.size())
3845 // Rewind and wait for rest of message
3846 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3851 auto hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3852 unsigned int nChecksum = 0;
3853 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3854 if (nChecksum != hdr.nChecksum)
3856 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3857 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3861 // Copy message to its own buffer
3862 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3863 vRecv.ignore(nMessageSize);
3871 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3876 catch (std::ios_base::failure& e)
3878 if (strstr(e.what(), "end of data"))
3880 // Allow exceptions from under-length message on vRecv
3881 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
3883 else if (strstr(e.what(), "size too large"))
3885 // Allow exceptions from over-long size
3886 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3890 PrintExceptionContinue(&e, "ProcessMessages()");
3893 catch (std::exception& e) {
3894 PrintExceptionContinue(&e, "ProcessMessages()");
3896 PrintExceptionContinue(NULL, "ProcessMessages()");
3900 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3908 bool SendMessages(CNode* pto)
3910 TRY_LOCK(cs_main, lockMain);
3912 // Current time in microseconds
3913 auto nNow = GetTimeMicros();
3915 // Don't send anything until we get their version message
3916 if (pto->nVersion == 0)
3919 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3921 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
3923 pto->PushMessage("ping", nonce);
3927 if (pto->fStartSync) {
3928 pto->fStartSync = false;
3929 pto->PushGetBlocks(pindexBest, uint256(0));
3932 // Resend wallet transactions that haven't gotten in a block yet
3933 ResendWalletTransactions();
3935 // Address refresh broadcast
3936 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3937 AdvertiseLocal(pto);
3938 pto->nNextLocalAddrSend = PoissonNextSend(nNow, nOneDay);
3944 if (pto->nNextAddrSend < nNow) {
3945 pto->nNextAddrSend = PoissonNextSend(nNow, 30);
3946 vector<CAddress> vAddr;
3947 vAddr.reserve(pto->vAddrToSend.size());
3948 for(const CAddress& addr : pto->vAddrToSend)
3950 if (pto->setAddrKnown.insert(addr).second)
3952 vAddr.push_back(addr);
3953 // receiver rejects addr messages larger than 1000
3954 if (vAddr.size() >= 1000)
3956 pto->PushMessage("addr", vAddr);
3961 pto->vAddrToSend.clear();
3963 pto->PushMessage("addr", vAddr);
3967 // Message: inventory
3970 vector<CInv> vInvWait;
3972 bool fSendTrickle = false;
3973 if (pto->nNextInvSend < nNow) {
3974 fSendTrickle = true;
3975 pto->nNextInvSend = PoissonNextSend(nNow, 5);
3977 LOCK(pto->cs_inventory);
3978 vInv.reserve(pto->vInventoryToSend.size());
3979 vInvWait.reserve(pto->vInventoryToSend.size());
3980 for(const CInv& inv : pto->vInventoryToSend)
3982 if (pto->setInventoryKnown.count(inv))
3985 // trickle out tx inv to protect privacy
3986 if (inv.GetType() == MSG_TX && !fSendTrickle)
3988 // 1/4 of tx invs blast to all immediately
3989 static uint256 hashSalt;
3991 hashSalt = GetRandHash();
3992 uint256 hashRand = inv.GetHash() ^ hashSalt;
3993 hashRand = Hash(hashRand.begin(), hashRand.end());
3994 bool fTrickleWait = ((hashRand & 3) != 0);
3998 vInvWait.push_back(inv);
4003 // returns true if wasn't already contained in the set
4004 if (pto->setInventoryKnown.insert(inv).second)
4006 vInv.push_back(inv);
4007 if (vInv.size() >= 1000)
4009 pto->PushMessage("inv", vInv);
4014 pto->vInventoryToSend = vInvWait;
4017 pto->PushMessage("inv", vInv);
4023 vector<CInv> vGetData;
4025 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4027 const CInv& inv = (*pto->mapAskFor.begin()).second;
4028 if (!AlreadyHave(txdb, inv))
4031 printf("sending getdata: %s\n", inv.ToString().c_str());
4032 vGetData.push_back(inv);
4033 if (vGetData.size() >= 1000)
4035 pto->PushMessage("getdata", vGetData);
4038 mapAlreadyAskedFor[inv] = nNow;
4040 pto->mapAskFor.erase(pto->mapAskFor.begin());
4042 if (!vGetData.empty())
4043 pto->PushMessage("getdata", vGetData);
4056 auto it1 = mapBlockIndex.begin();
4057 for (; it1 != mapBlockIndex.end(); it1++)
4058 delete (*it1).second;
4059 mapBlockIndex.clear();
4062 auto it2 = mapOrphanBlocks.begin();
4063 for (; it2 != mapOrphanBlocks.end(); it2++)
4064 delete (*it2).second;
4065 mapOrphanBlocks.clear();
4067 // orphan transactions
4069 } instance_of_cmaincleanup;