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.
9 #include "checkpoints.h"
13 #include "ui_interface.h"
14 #include "checkqueue.h"
16 #include <boost/filesystem.hpp>
17 #include <boost/filesystem/fstream.hpp>
22 using namespace boost;
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
29 CCriticalSection cs_main;
32 unsigned int nTransactionsUpdated = 0;
34 map<uint256, CBlockIndex*> mapBlockIndex;
35 set<pair<COutPoint, unsigned int> > setStakeSeen;
37 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
38 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
39 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
40 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
41 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
43 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
45 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
46 unsigned int nModifierInterval = 6 * nOneHour; // time to elapse before new modifier is computed
48 int nCoinbaseMaturity = 500;
50 CBlockIndex* pindexGenesisBlock = NULL;
53 uint256 nBestChainTrust = 0;
54 uint256 nBestInvalidTrust = 0;
56 uint256 hashBestChain = 0;
57 CBlockIndex* pindexBest = NULL;
58 int64_t nTimeBestReceived = 0;
59 int nScriptCheckThreads = 0;
61 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
63 map<uint256, CBlock*> mapOrphanBlocks;
64 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
65 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
66 map<uint256, uint256> mapProofOfStake;
68 map<uint256, CTransaction> mapOrphanTransactions;
69 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
71 // Constant stuff for coinbase transactions we create:
72 CScript COINBASE_FLAGS;
74 const string strMessageMagic = "NovaCoin Signed Message:\n";
77 int64_t nTransactionFee = MIN_TX_FEE;
78 int64_t nMinimumInputValue = MIN_TXOUT_AMOUNT;
80 // Ping and address broadcast intervals
81 int64_t nPingInterval = 30 * 60;
83 extern enum Checkpoints::CPMode CheckpointsMode;
85 //////////////////////////////////////////////////////////////////////////////
87 // dispatching functions
90 // These functions dispatch to one or all registered wallets
93 void RegisterWallet(CWallet* pwalletIn)
96 LOCK(cs_setpwalletRegistered);
97 setpwalletRegistered.insert(pwalletIn);
101 void UnregisterWallet(CWallet* pwalletIn)
104 LOCK(cs_setpwalletRegistered);
105 setpwalletRegistered.erase(pwalletIn);
109 // check whether the passed transaction is from us
110 bool static IsFromMe(CTransaction& tx)
112 for(CWallet* pwallet : setpwalletRegistered)
113 if (pwallet->IsFromMe(tx))
118 // make sure all wallets know about the given transaction, in the given block
119 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
123 // wallets need to refund inputs when disconnecting coinstake
124 if (tx.IsCoinStake())
126 for(CWallet* pwallet : setpwalletRegistered)
127 if (pwallet->IsFromMe(tx))
128 pwallet->DisableTransaction(tx);
133 for(CWallet* pwallet : setpwalletRegistered)
134 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
137 // notify wallets about a new best chain
138 void static SetBestChain(const CBlockLocator& loc)
140 for(CWallet* pwallet : setpwalletRegistered)
141 pwallet->SetBestChain(loc);
144 // notify wallets about an updated transaction
145 void static UpdatedTransaction(const uint256& hashTx)
147 for(CWallet* pwallet : setpwalletRegistered)
148 pwallet->UpdatedTransaction(hashTx);
152 void static PrintWallets(const CBlock& block)
154 for(CWallet* pwallet : setpwalletRegistered)
155 pwallet->PrintWallet(block);
158 // notify wallets about an incoming inventory (for request counts)
159 void static Inventory(const uint256& hash)
161 for(CWallet* pwallet : setpwalletRegistered)
162 pwallet->Inventory(hash);
165 // ask wallets to resend their transactions
166 void ResendWalletTransactions(bool fForceResend)
168 for(CWallet* pwallet : setpwalletRegistered)
169 pwallet->ResendWalletTransactions(fForceResend);
178 //////////////////////////////////////////////////////////////////////////////
180 // mapOrphanTransactions
183 bool AddOrphanTx(const CTransaction& tx)
185 auto hash = tx.GetHash();
186 if (mapOrphanTransactions.count(hash))
189 // Ignore big transactions, to avoid a
190 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
191 // large transaction with a missing parent then we assume
192 // it will rebroadcast it later, after the parent transaction(s)
193 // have been mined or received.
194 // 10,000 orphans, each of which is at most 5,000 bytes big is
195 // at most 500 megabytes of orphans:
197 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
201 printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
205 mapOrphanTransactions[hash] = tx;
206 for(const CTxIn& txin : tx.vin)
207 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
209 printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
210 mapOrphanTransactions.size());
214 void static EraseOrphanTx(uint256 hash)
216 if (!mapOrphanTransactions.count(hash))
218 const auto& tx = mapOrphanTransactions[hash];
219 for(const auto& txin : tx.vin)
221 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
222 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
223 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
225 mapOrphanTransactions.erase(hash);
228 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
230 unsigned int nEvicted = 0;
231 while (mapOrphanTransactions.size() > nMaxOrphans)
233 // Evict a random orphan:
234 auto randomhash = GetRandHash();
235 auto it = mapOrphanTransactions.lower_bound(randomhash);
236 if (it == mapOrphanTransactions.end())
237 it = mapOrphanTransactions.begin();
238 EraseOrphanTx(it->first);
250 //////////////////////////////////////////////////////////////////////////////
252 // CTransaction and CTxIndex
255 bool CTransaction::IsFinal(int nBlockHeight, int64_t nBlockTime) const
257 // Time based nLockTime implemented in 0.1.6
260 if (nBlockHeight == 0)
261 nBlockHeight = nBestHeight;
263 nBlockTime = GetAdjustedTime();
264 if ((int64_t)nLockTime < ((int64_t)nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
266 for(const CTxIn& txin : vin)
272 bool CTransaction::ReadFromDisk(CDiskTxPos pos, FILE** pfileRet)
274 auto filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
276 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
279 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
280 return error("CTransaction::ReadFromDisk() : fseek failed");
285 catch (const std::exception&) {
286 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
289 // Return file pointer
292 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
293 return error("CTransaction::ReadFromDisk() : second fseek failed");
294 *pfileRet = filein.release();
299 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
302 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
304 if (!ReadFromDisk(txindexRet.pos))
306 if (prevout.n >= vout.size())
314 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
317 return ReadFromDisk(txdb, prevout, txindex);
320 bool CTransaction::ReadFromDisk(COutPoint prevout)
324 return ReadFromDisk(txdb, prevout, txindex);
327 bool CTransaction::IsStandard(string& strReason) const
329 if (nVersion > CTransaction::CURRENT_VERSION)
331 strReason = "version";
335 unsigned int nDataOut = 0;
336 txnouttype whichType;
337 for(const CTxIn& txin : vin)
339 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
340 // keys. (remember the 520 byte limit on redeemScript size) That works
341 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
342 // bytes of scriptSig, which we round off to 1650 bytes for some minor
343 // future-proofing. That's also enough to spend a 20-of-20
344 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
345 // considered standard)
346 if (txin.scriptSig.size() > 1650)
348 strReason = "scriptsig-size";
351 if (!txin.scriptSig.IsPushOnly())
353 strReason = "scriptsig-not-pushonly";
356 if (!txin.scriptSig.HasCanonicalPushes()) {
357 strReason = "txin-scriptsig-not-canonicalpushes";
361 for(const CTxOut& txout : vout) {
362 if (!::IsStandard(txout.scriptPubKey, whichType)) {
363 strReason = "scriptpubkey";
366 if (whichType == TX_NULL_DATA)
369 if (txout.nValue == 0) {
370 strReason = "txout-value=0";
373 if (!txout.scriptPubKey.HasCanonicalPushes()) {
374 strReason = "txout-scriptsig-not-canonicalpushes";
380 // only one OP_RETURN txout is permitted
382 strReason = "multi-op-return";
390 // Check transaction inputs, and make sure any
391 // pay-to-script-hash transactions are evaluating IsStandard scripts
393 // Why bother? To avoid denial-of-service attacks; an attacker
394 // can submit a standard HASH... OP_EQUAL transaction,
395 // which will get accepted into blocks. The redemption
396 // script can be anything; an attacker could use a very
397 // expensive-to-check-upon-redemption script like:
398 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
400 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
403 return true; // Coinbases don't use vin normally
405 for (uint32_t i = 0; i < vin.size(); i++)
407 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
409 vector<vector<unsigned char> > vSolutions;
410 txnouttype whichType;
411 // get the scriptPubKey corresponding to this input:
412 const CScript& prevScript = prev.scriptPubKey;
413 if (!Solver(prevScript, whichType, vSolutions))
415 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
416 if (nArgsExpected < 0)
419 // Transactions with extra stuff in their scriptSigs are
420 // non-standard. Note that this EvalScript() call will
421 // be quick, because if there are any operations
422 // beside "push data" in the scriptSig the
423 // IsStandard() call returns false
424 vector<vector<unsigned char> > stack;
425 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
428 if (whichType == TX_SCRIPTHASH)
432 CScript subscript(stack.back().begin(), stack.back().end());
433 vector<vector<unsigned char> > vSolutions2;
434 txnouttype whichType2;
435 if (!Solver(subscript, whichType2, vSolutions2))
437 if (whichType2 == TX_SCRIPTHASH)
441 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
444 nArgsExpected += tmpExpected;
447 if (stack.size() != (unsigned int)nArgsExpected)
454 unsigned int CTransaction::GetLegacySigOpCount() const
456 unsigned int nSigOps = 0;
459 // Coinbase scriptsigs are never executed, so there is
460 // no sense in calculation of sigops.
461 for(const CTxIn& txin : vin)
463 nSigOps += txin.scriptSig.GetSigOpCount(false);
466 for(const CTxOut& txout : vout)
468 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
473 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
486 // Load the block this tx is in
488 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
490 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
495 // Update the tx's hashBlock
496 hashBlock = pblock->GetHash();
498 // Locate the transaction
499 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
500 if (pblock->vtx[nIndex] == *(CTransaction*)this)
502 if (nIndex == (int)pblock->vtx.size())
504 vMerkleBranch.clear();
506 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
510 // Fill in merkle branch
511 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
514 // Is the tx in a block that's in the main chain
515 auto mi = mapBlockIndex.find(hashBlock);
516 if (mi == mapBlockIndex.end())
518 const CBlockIndex* pindex = (*mi).second;
519 if (!pindex || !pindex->IsInMainChain())
522 return pindexBest->nHeight - pindex->nHeight + 1;
525 bool CTransaction::CheckTransaction() const
527 // Basic checks that don't depend on any context
529 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
531 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
533 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
534 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
536 // Check for negative or overflow output values
537 CBigNum nValueOut = 0;
538 for (uint32_t i = 0; i < vout.size(); i++)
540 const auto& txout = vout[i];
541 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
542 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
543 if (!MoneyRange(txout.nValue))
544 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is out of range"));
545 nValueOut += txout.nValue;
546 if (!MoneyRange(nValueOut))
547 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
550 // Check for duplicate inputs
551 set<COutPoint> vInOutPoints;
552 for(const CTxIn& txin : vin)
554 if (vInOutPoints.count(txin.prevout))
556 vInOutPoints.insert(txin.prevout);
561 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
562 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
566 for(const CTxIn& txin : vin)
567 if (txin.prevout.IsNull())
568 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
574 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
576 int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
580 // Enforce 0.01 as minimum fee for coinstake
582 nMinRelayTxFee = CENT;
585 // Base fee is either nMinTxFee or nMinRelayTxFee
586 auto nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
588 unsigned int nNewBlockSize = nBlockSize + nBytes;
589 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
595 // Transactions under 1K are free
601 // Free transaction area
602 if (nNewBlockSize < 27000)
607 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
608 // each non empty output which is less than 0.01
610 // It's safe to ignore empty outputs here, because these inputs are allowed
611 // only for coinbase and coinstake transactions.
612 for(const CTxOut& txout : vout)
613 if (txout.nValue < CENT && !txout.IsEmpty())
616 // Raise the price as the block approaches full
617 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
619 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
621 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
624 if (!MoneyRange(nMinFee))
630 string CTransaction::ToStringShort() const
633 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
637 string CTransaction::ToString() const
640 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
641 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%" PRIszu ", vout.size=%" PRIszu ", nLockTime=%d)\n",
642 GetHash().ToString().substr(0,10).c_str(),
648 for (unsigned int i = 0; i < vin.size(); i++)
649 str += " " + vin[i].ToString() + "\n";
650 for (unsigned int i = 0; i < vout.size(); i++)
651 str += " " + vout[i].ToString() + "\n";
655 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
656 bool* pfMissingInputs)
659 *pfMissingInputs = false;
661 // Time (prevent mempool memory exhaustion attack)
662 if (tx.nTime > FutureDrift(GetAdjustedTime()))
663 return tx.DoS(10, error("CTxMemPool::accept() : transaction timestamp is too far in the future"));
665 if (!tx.CheckTransaction())
666 return error("CTxMemPool::accept() : CheckTransaction failed");
668 // Coinbase is only valid in a block, not as a loose transaction
670 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
672 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
673 if (tx.IsCoinStake())
674 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
676 // To help v0.1.5 clients who would see it as a negative number
677 if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
678 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
680 // Rather not work on nonstandard transactions (unless -testnet)
682 if (!fTestNet && !tx.IsStandard(strNonStd))
683 return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
685 // Do we already have it?
686 auto hash = tx.GetHash();
689 if (mapTx.count(hash))
693 if (txdb.ContainsTx(hash))
696 // Check for conflicts with in-memory transactions
697 for (unsigned int i = 0; i < tx.vin.size(); i++)
699 auto outpoint = tx.vin[i].prevout;
700 if (mapNextTx.count(outpoint))
702 // Replacement feature isn't supported by Novacoin.
710 map<uint256, CTxIndex> mapUnused;
711 bool fInvalid = false;
712 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
715 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
717 *pfMissingInputs = true;
721 // Check for non-standard pay-to-script-hash in inputs
722 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
723 return error("CTxMemPool::accept() : nonstandard transaction input");
725 // Note: if you modify this code to accept non-standard transactions, then
726 // you should add code here to check that the transaction does a
727 // reasonable number of ECDSA signature verifications.
729 auto nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
730 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
732 // Don't accept it if it can't get into a block
733 auto txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
734 if (nFees < txMinFee)
735 return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
736 hash.ToString().c_str(),
739 // Continuously rate-limit free transactions
740 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
741 // be annoying or make others' transactions take longer to confirm.
742 if (nFees < MIN_RELAY_TX_FEE)
744 static CCriticalSection cs;
745 static double dFreeCount;
746 static int64_t nLastTime;
747 auto nNow = GetTime();
751 // Use an exponentially decaying ~10-minute window:
752 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
754 // -limitfreerelay unit is thousand-bytes-per-minute
755 // At default rate it would take over a month to fill 1GB
756 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
757 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
759 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
764 // Check against previous transactions
765 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
766 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, STRICT_FLAGS))
768 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
772 // Store transaction in memory
775 addUnchecked(hash, tx);
778 printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
779 hash.ToString().substr(0,10).c_str(),
784 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
786 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
789 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
791 // Add to memory pool without checking anything. Don't call this directly,
792 // call CTxMemPool::accept to properly check the transaction first.
795 for (unsigned int i = 0; i < tx.vin.size(); i++)
796 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
797 nTransactionsUpdated++;
803 bool CTxMemPool::remove(CTransaction &tx)
805 // Remove transaction from memory pool
808 auto hash = tx.GetHash();
809 if (mapTx.count(hash))
811 for(const CTxIn& txin : tx.vin)
812 mapNextTx.erase(txin.prevout);
814 nTransactionsUpdated++;
820 void CTxMemPool::clear()
825 ++nTransactionsUpdated;
828 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
833 vtxid.reserve(mapTx.size());
834 for (auto mi = mapTx.begin(); mi != mapTx.end(); ++mi)
835 vtxid.push_back((*mi).first);
839 string CTxIn::ToString() const
843 str += CTxIn::prevout.ToString();
844 if (CTxIn::prevout.IsNull())
845 str += strprintf(", coinbase %s", HexStr(CTxIn::scriptSig).c_str());
847 str += strprintf(", scriptSig=%s", CTxIn::scriptSig.ToString().substr(0,24).c_str());
848 if (CTxIn::nSequence != numeric_limits<unsigned int>::max())
849 str += strprintf(", nSequence=%" PRIu32, CTxIn::nSequence);
855 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
857 if (hashBlock == 0 || nIndex == -1)
860 // Find the block it claims to be in
861 auto mi = mapBlockIndex.find(hashBlock);
862 if (mi == mapBlockIndex.end())
864 CBlockIndex* pindex = (*mi).second;
865 if (!pindex || !pindex->IsInMainChain())
868 // Make sure the merkle branch connects to this block
869 if (!fMerkleVerified)
871 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
873 fMerkleVerified = true;
877 return pindexBest->nHeight - pindex->nHeight + 1;
881 int CMerkleTx::GetBlocksToMaturity() const
883 if (!(IsCoinBase() || IsCoinStake()))
885 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
889 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
893 if (!IsInMainChain() && !ClientConnectInputs())
895 return CTransaction::AcceptToMemoryPool(txdb, false);
899 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
903 bool CMerkleTx::AcceptToMemoryPool()
906 return AcceptToMemoryPool(txdb);
911 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
916 // Add previous supporting transactions first
917 for(CMerkleTx& tx : vtxPrev)
919 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
921 auto hash = tx.GetHash();
922 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
923 tx.AcceptToMemoryPool(txdb, fCheckInputs);
926 return AcceptToMemoryPool(txdb, fCheckInputs);
931 bool CWalletTx::AcceptWalletTransaction()
934 return AcceptWalletTransaction(txdb);
937 int CTxIndex::GetDepthInMainChain() const
941 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
943 // Find the block in the index
944 auto mi = mapBlockIndex.find(block.GetHash());
945 if (mi == mapBlockIndex.end())
947 auto pindex = (*mi).second;
948 if (!pindex || !pindex->IsInMainChain())
950 return 1 + nBestHeight - pindex->nHeight;
953 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
954 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
960 if (mempool.exists(hash))
962 tx = mempool.lookup(hash);
968 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
971 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
972 hashBlock = block.GetHash();
980 // Closure representing one script verification
981 // Note that this stores references to the spending transaction
985 CScript scriptPubKey;
986 const CTransaction *ptxTo = nullptr;
988 unsigned int nFlags = 0;
993 CScriptCheck(const CTransaction& txFromIn, const CTransaction& txToIn, uint32_t nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
994 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
995 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
997 bool operator()() const;
999 void swap(CScriptCheck &check) {
1000 scriptPubKey.swap(check.scriptPubKey);
1001 std::swap(ptxTo, check.ptxTo);
1002 std::swap(nIn, check.nIn);
1003 std::swap(nFlags, check.nFlags);
1004 std::swap(nHashType, check.nHashType);
1011 //////////////////////////////////////////////////////////////////////////////
1013 // CBlock and CBlockIndex
1016 static CBlockIndex* pblockindexFBBHLast;
1017 CBlockIndex* FindBlockByHeight(int nHeight)
1019 CBlockIndex *pblockindex;
1020 if (nHeight < nBestHeight / 2)
1021 pblockindex = pindexGenesisBlock;
1023 pblockindex = pindexBest;
1024 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
1025 pblockindex = pblockindexFBBHLast;
1026 while (pblockindex->nHeight > nHeight)
1027 pblockindex = pblockindex->pprev;
1028 while (pblockindex->nHeight < nHeight)
1029 pblockindex = pblockindex->pnext;
1030 pblockindexFBBHLast = pblockindex;
1034 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1036 if (!fReadTransactions)
1038 *this = pindex->GetBlockHeader();
1041 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
1043 if (GetHash() != pindex->GetBlockHash())
1044 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1048 uint256 static GetOrphanRoot(const CBlock* pblock)
1050 // Work back to the first block in the orphan chain
1051 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1052 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1053 return pblock->GetHash();
1056 // ppcoin: find block wanted by given orphan block
1057 uint256 WantedByOrphan(const CBlock* pblockOrphan)
1059 // Work back to the first block in the orphan chain
1060 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
1061 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
1062 return pblockOrphan->hashPrevBlock;
1065 // select stake target limit according to hard-coded conditions
1066 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1068 if(fTestNet) // separate proof of stake target limit for testnet
1069 return bnProofOfStakeLimit;
1070 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1071 return bnProofOfStakeLimit;
1072 if(nHeight + 1 > 15000) // 24 bits since block 15000
1073 return bnProofOfStakeLegacyLimit;
1074 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1075 return bnProofOfStakeHardLimit;
1077 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1080 // miner's coin base reward based on nBits
1081 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees)
1083 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1086 bnTarget.SetCompact(nBits);
1087 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1088 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1090 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1091 // A reasonably continuous curve is used to avoid shock to market
1092 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1094 // Human readable form:
1096 // nSubsidy = 100 / (diff ^ 1/6)
1098 // Please note that we're using bisection to find an approximate solutuion
1099 CBigNum bnLowerBound = CENT;
1100 CBigNum bnUpperBound = bnSubsidyLimit;
1101 while (bnLowerBound + CENT <= bnUpperBound)
1103 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1104 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1105 bnUpperBound = bnMidValue;
1107 bnLowerBound = bnMidValue;
1110 int64_t nSubsidy = bnUpperBound.getuint64();
1112 nSubsidy = (nSubsidy / CENT) * CENT;
1113 if (fDebug && GetBoolArg("-printcreation"))
1114 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1116 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1119 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1120 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1122 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1124 // Stage 2 of emission process is mostly PoS-based.
1126 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1128 bnTarget.SetCompact(nBits);
1129 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1130 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1132 // A reasonably continuous curve is used to avoid shock to market
1134 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1135 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1136 bnMidPart, bnRewardPart;
1138 while (bnLowerBound + CENT <= bnUpperBound)
1140 auto bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1143 // Reward for coin-year is cut in half every 8x multiply of PoS difficulty
1145 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1147 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1150 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1151 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1153 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1154 bnUpperBound = bnMidValue;
1156 bnLowerBound = bnMidValue;
1159 nRewardCoinYear = bnUpperBound.getuint64();
1160 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1163 return nRewardCoinYear;
1165 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1167 // Set reasonable reward limit for large inputs
1169 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1171 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1172 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1174 nSubsidy = min(nSubsidy, nSubsidyLimit);
1176 if (fDebug && GetBoolArg("-printcreation"))
1177 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1182 static const int64_t nTargetTimespan = 7 * nOneDay; // one week
1184 // get proof of work blocks max spacing according to hard-coded conditions
1185 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1187 if(nTime > TARGETS_SWITCH_TIME)
1188 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1191 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1193 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1197 // maximum nBits value could possible be required nTime after
1199 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1202 bnResult.SetCompact(nBase);
1204 while (nTime > 0 && bnResult < bnTargetLimit)
1206 // Maximum 200% adjustment per day...
1210 if (bnResult > bnTargetLimit)
1211 bnResult = bnTargetLimit;
1212 return bnResult.GetCompact();
1216 // minimum amount of work that could possibly be required nTime after
1217 // minimum proof-of-work required was nBase
1219 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1221 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1225 // minimum amount of stake that could possibly be required nTime after
1226 // minimum proof-of-stake required was nBase
1228 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1230 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1234 // ppcoin: find last block index up to pindex
1235 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1237 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1238 pindex = pindex->pprev;
1242 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1244 if (pindexLast == NULL)
1245 return bnProofOfWorkLimit.GetCompact(); // genesis block
1247 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1249 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1250 if (pindexPrev->pprev == NULL)
1251 return bnTargetLimit.GetCompact(); // first block
1252 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1253 if (pindexPrevPrev->pprev == NULL)
1254 return bnTargetLimit.GetCompact(); // second block
1256 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1258 // ppcoin: target change every block
1259 // ppcoin: retarget with exponential moving toward target spacing
1261 bnNew.SetCompact(pindexPrev->nBits);
1262 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1263 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1264 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1265 bnNew /= ((nInterval + 1) * nTargetSpacing);
1267 if (bnNew > bnTargetLimit)
1268 bnNew = bnTargetLimit;
1270 return bnNew.GetCompact();
1273 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1276 bnTarget.SetCompact(nBits);
1279 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1280 return error("CheckProofOfWork() : nBits below minimum work");
1282 // Check proof of work matches claimed amount
1283 if (hash > bnTarget.getuint256())
1284 return error("CheckProofOfWork() : hash doesn't match nBits");
1289 // Return maximum amount of blocks that other nodes claim to have
1290 int GetNumBlocksOfPeers()
1292 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1295 bool IsInitialBlockDownload()
1297 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1299 static int64_t nLastUpdate;
1300 static CBlockIndex* pindexLastBest;
1301 auto nCurrentTime = GetTime();
1302 if (pindexBest != pindexLastBest)
1304 pindexLastBest = pindexBest;
1305 nLastUpdate = nCurrentTime;
1307 return (nCurrentTime - nLastUpdate < 10 &&
1308 pindexBest->GetBlockTime() < nCurrentTime - nOneDay);
1311 void static InvalidChainFound(CBlockIndex* pindexNew)
1313 if (pindexNew->nChainTrust > nBestInvalidTrust)
1315 nBestInvalidTrust = pindexNew->nChainTrust;
1316 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1317 uiInterface.NotifyBlocksChanged();
1320 auto nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1321 auto nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1323 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1324 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1325 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1326 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1327 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1328 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1329 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1330 nBestBlockTrust.Get64(),
1331 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1334 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1336 nTime = max(GetBlockTime(), GetAdjustedTime());
1339 unsigned int CBlock::GetStakeEntropyBit(unsigned int nHeight) const
1341 // Protocol switch to support p2pool at novacoin block #9689
1342 if (nHeight >= 9689 || fTestNet)
1344 // Take last bit of block hash as entropy bit
1345 auto nEntropyBit = (GetHash().Get32()) & (uint32_t)1;
1346 if (fDebug && GetBoolArg("-printstakemodifier"))
1347 printf("GetStakeEntropyBit: nTime=%" PRIu32 " hashBlock=%s nEntropyBit=%" PRIu32 "\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
1351 // Before novacoin block #9689 - get from pregenerated table
1352 int nBitNum = nHeight & 0xFF;
1353 int nItemNum = nHeight / 0xFF;
1355 auto nEntropyBit = ((entropyStore[nItemNum] & (uint256(1) << nBitNum)) >> nBitNum).Get32();
1356 if (fDebug && GetBoolArg("-printstakemodifier"))
1357 printf("GetStakeEntropyBit: from pregenerated table, nHeight=%" PRIu32 " nEntropyBit=%" PRIu32 "\n", nHeight, nEntropyBit);
1361 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1363 // Relinquish previous transactions' spent pointers
1366 for(const CTxIn& txin : vin)
1368 auto prevout = txin.prevout;
1370 // Get prev txindex from disk
1372 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1373 return error("DisconnectInputs() : ReadTxIndex failed");
1375 if (prevout.n >= txindex.vSpent.size())
1376 return error("DisconnectInputs() : prevout.n out of range");
1378 // Mark outpoint as not spent
1379 txindex.vSpent[prevout.n].SetNull();
1382 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1383 return error("DisconnectInputs() : UpdateTxIndex failed");
1387 // Remove transaction from index
1388 // This can fail if a duplicate of this transaction was in a chain that got
1389 // reorganized away. This is only possible if this transaction was completely
1390 // spent, so erasing it would be a no-op anyway.
1391 txdb.EraseTxIndex(*this);
1397 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1398 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1400 // FetchInputs can return false either because we just haven't seen some inputs
1401 // (in which case the transaction should be stored as an orphan)
1402 // or because the transaction is malformed (in which case the transaction should
1403 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1407 return true; // Coinbase transactions have no inputs to fetch.
1409 for (unsigned int i = 0; i < vin.size(); i++)
1411 auto prevout = vin[i].prevout;
1412 if (inputsRet.count(prevout.hash))
1413 continue; // Got it already
1416 CTxIndex& txindex = inputsRet[prevout.hash].first;
1418 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1420 // Get txindex from current proposed changes
1421 txindex = mapTestPool.find(prevout.hash)->second;
1425 // Read txindex from txdb
1426 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1428 if (!fFound && (fBlock || fMiner))
1429 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());
1432 CTransaction& txPrev = inputsRet[prevout.hash].second;
1433 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1435 // Get prev tx from single transactions in memory
1438 if (!mempool.exists(prevout.hash))
1439 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());
1440 txPrev = mempool.lookup(prevout.hash);
1443 txindex.vSpent.resize(txPrev.vout.size());
1447 // Get prev tx from disk
1448 if (!txPrev.ReadFromDisk(txindex.pos))
1449 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1453 // Make sure all prevout.n indexes are valid:
1454 for (unsigned int i = 0; i < vin.size(); i++)
1456 const COutPoint prevout = vin[i].prevout;
1457 assert(inputsRet.count(prevout.hash) != 0);
1458 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1459 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1460 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1462 // Revisit this if/when transaction replacement is implemented and allows
1465 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()));
1472 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1474 auto mi = inputs.find(input.prevout.hash);
1475 if (mi == inputs.end())
1476 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1478 const auto& txPrev = (mi->second).second;
1479 if (input.prevout.n >= txPrev.vout.size())
1480 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1482 return txPrev.vout[input.prevout.n];
1485 int64_t CTransaction::GetValueOut() const
1487 CBigNum nValueOut = 0;
1488 for(const auto& txout : vout)
1490 nValueOut += txout.nValue;
1491 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
1492 throw runtime_error("CTransaction::GetValueOut() : value out of range");
1494 return nValueOut.getint64();
1497 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1502 CBigNum nResult = 0;
1503 for (uint32_t i = 0; i < vin.size(); i++)
1505 const auto& txOut = GetOutputFor(vin[i], inputs);
1506 nResult += txOut.nValue;
1507 if (!MoneyRange(txOut.nValue) || !MoneyRange(nResult))
1508 throw runtime_error("CTransaction::GetValueIn() : value out of range");
1510 return nResult.getint64();
1514 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1519 unsigned int nSigOps = 0;
1520 for (unsigned int i = 0; i < vin.size(); i++)
1522 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1523 if (prevout.scriptPubKey.IsPayToScriptHash())
1524 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1529 bool CScriptCheck::operator()() const {
1530 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1531 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1532 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1536 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType)
1538 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1541 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1542 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1544 // Take over previous transactions' spent pointers
1545 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1546 // fMiner is true when called from the internal bitcoin miner
1547 // ... both are false when called from CTransaction::AcceptToMemoryPool
1551 int64_t nValueIn = 0;
1553 CBigNum bnValueIn = 0;
1554 for (uint32_t i = 0; i < vin.size(); i++)
1556 auto prevout = vin[i].prevout;
1557 assert(inputs.count(prevout.hash) > 0);
1558 CTxIndex& txindex = inputs[prevout.hash].first;
1559 CTransaction& txPrev = inputs[prevout.hash].second;
1561 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1562 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()));
1564 // If prev is coinbase or coinstake, check that it's matured
1565 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1566 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1567 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1568 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1570 // ppcoin: check transaction timestamp
1571 if (txPrev.nTime > nTime)
1572 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1574 // Check for negative or overflow input values
1575 bnValueIn += txPrev.vout[prevout.n].nValue;
1576 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(bnValueIn))
1577 return DoS(100, error("ConnectInputs() : txin values out of range"));
1579 nValueIn = bnValueIn.getint64();
1583 pvChecks->reserve(vin.size());
1585 // The first loop above does all the inexpensive checks.
1586 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1587 // Helps prevent CPU exhaustion attacks.
1588 for (unsigned int i = 0; i < vin.size(); i++)
1590 auto prevout = vin[i].prevout;
1591 assert(inputs.count(prevout.hash) > 0);
1592 CTxIndex& txindex = inputs[prevout.hash].first;
1593 CTransaction& txPrev = inputs[prevout.hash].second;
1595 // Check for conflicts (double-spend)
1596 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1597 // for an attacker to attempt to split the network.
1598 if (!txindex.vSpent[prevout.n].IsNull())
1599 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());
1601 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1602 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1603 // still computed and checked, and any change will be caught at the next checkpoint.
1607 CScriptCheck check(txPrev, *this, i, flags, 0);
1610 pvChecks->push_back(CScriptCheck());
1611 check.swap(pvChecks->back());
1615 if (flags & STRICT_FLAGS)
1617 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1618 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1620 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1622 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1626 // Mark outpoints as spent
1627 txindex.vSpent[prevout.n] = posThisTx;
1630 if (fBlock || fMiner)
1632 mapTestPool[prevout.hash] = txindex;
1638 if (nTime > Checkpoints::GetLastCheckpointTime())
1640 unsigned int nTxSize = GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
1642 // coin stake tx earns reward instead of paying fee
1644 if (!GetCoinAge(txdb, nCoinAge))
1645 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1647 auto nReward = GetValueOut() - nValueIn;
1648 auto nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1650 if (nReward > nCalculatedReward)
1651 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1656 if (nValueIn < GetValueOut())
1657 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1659 // Tally transaction fees
1660 auto nTxFee = nValueIn - GetValueOut();
1661 if (!MoneyRange(nTxFee))
1662 return DoS(100, error("ConnectInputs() : nFees out of range"));
1670 bool CTransaction::ClientConnectInputs()
1675 // Take over previous transactions' spent pointers
1678 CBigNum bnValueIn = 0;
1679 for (uint32_t i = 0; i < vin.size(); i++)
1681 // Get prev tx from single transactions in memory
1682 auto prevout = vin[i].prevout;
1683 if (!mempool.exists(prevout.hash))
1685 CTransaction& txPrev = mempool.lookup(prevout.hash);
1687 if (prevout.n >= txPrev.vout.size())
1691 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1692 return error("ClientConnectInputs() : VerifySignature failed");
1694 ///// this is redundant with the mempool.mapNextTx stuff,
1695 ///// not sure which I want to get rid of
1696 ///// this has to go away now that posNext is gone
1697 // // Check for conflicts
1698 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1699 // return error("ConnectInputs() : prev tx already used");
1701 // // Flag outpoints as used
1702 // txPrev.vout[prevout.n].posNext = posThisTx;
1704 bnValueIn += txPrev.vout[prevout.n].nValue;
1706 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(bnValueIn))
1707 return error("ClientConnectInputs() : txin values out of range");
1709 if (GetValueOut() > bnValueIn.getint64())
1716 int64_t CBlock::GetMaxTransactionTime() const
1718 int64_t maxTransactionTime = 0;
1719 for(const auto& tx : vtx)
1720 maxTransactionTime = max(maxTransactionTime, (int64_t)tx.nTime);
1721 return maxTransactionTime;
1724 uint256 CBlock::BuildMerkleTree() const
1726 vMerkleTree.clear();
1727 for(const auto& tx : vtx)
1728 vMerkleTree.push_back(tx.GetHash());
1730 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1732 for (int i = 0; i < nSize; i += 2)
1734 int i2 = min(i+1, nSize-1);
1735 vMerkleTree.push_back(Hash(vMerkleTree[j+i].begin(), vMerkleTree[j+i].end(),
1736 vMerkleTree[j+i2].begin(), vMerkleTree[j+i2].end()));
1740 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1743 vector<uint256> CBlock::GetMerkleBranch(int nIndex) const
1745 if (vMerkleTree.empty())
1747 vector<uint256> vMerkleBranch;
1749 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1751 int i = min(nIndex^1, nSize-1);
1752 vMerkleBranch.push_back(vMerkleTree[j+i]);
1756 return vMerkleBranch;
1759 uint256 CBlock::CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1763 for(const uint256& otherside : vMerkleBranch)
1766 hash = Hash(otherside.begin(), otherside.end(), hash.begin(), hash.end());
1768 hash = Hash(hash.begin(), hash.end(), otherside.begin(), otherside.end());
1774 bool CBlock::WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1776 // Open history file to append
1777 auto fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1779 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1781 // Write index header
1782 unsigned int nSize = fileout.GetSerializeSize(*this);
1783 fileout << nNetworkID << nSize;
1786 long fileOutPos = ftell(fileout);
1788 return error("CBlock::WriteToDisk() : ftell failed");
1789 nBlockPosRet = fileOutPos;
1792 // Flush stdio buffers and commit to disk before returning
1794 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1795 FileCommit(fileout);
1800 bool CBlock::ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions)
1804 // Open history file to read
1805 auto filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1807 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1808 if (!fReadTransactions)
1809 filein.nType |= SER_BLOCKHEADERONLY;
1815 catch (const std::exception&) {
1816 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
1820 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1821 return error("CBlock::ReadFromDisk() : errors in block header");
1826 void CBlock::print() const
1828 printf("CBlock(hash=%s, ver=%" PRId32 ", hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%" PRIu32 ", nBits=%08x, nNonce=%" PRIu32 ", vtx=%" PRIszu ", vchBlockSig=%s)\n",
1829 GetHash().ToString().c_str(),
1831 hashPrevBlock.ToString().c_str(),
1832 hashMerkleRoot.ToString().c_str(),
1833 nTime, nBits, nNonce,
1835 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1836 for (unsigned int i = 0; i < vtx.size(); i++)
1841 printf(" vMerkleTree: ");
1842 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1843 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1847 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1849 // Disconnect in reverse order
1850 for (int i = vtx.size()-1; i >= 0; i--)
1851 if (!vtx[i].DisconnectInputs(txdb))
1854 // Update block index on disk without changing it in memory.
1855 // The memory index structure will be changed after the db commits.
1858 CDiskBlockIndex blockindexPrev(pindex->pprev);
1859 blockindexPrev.hashNext = 0;
1860 if (!txdb.WriteBlockIndex(blockindexPrev))
1861 return error("DisconnectBlock() : WriteBlockIndex failed");
1864 // ppcoin: clean up wallet after disconnecting coinstake
1865 for(CTransaction& tx : vtx)
1866 SyncWithWallets(tx, this, false, false);
1871 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1873 void ThreadScriptCheck(void*) {
1874 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1875 RenameThread("novacoin-scriptch");
1876 scriptcheckqueue.Thread();
1877 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1880 void ThreadScriptCheckQuit() {
1881 scriptcheckqueue.Quit();
1884 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1886 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1887 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1890 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1891 // unless those are already completely spent.
1892 // If such overwrites are allowed, coinbases and transactions depending upon those
1893 // can be duplicated to remove the ability to spend the first instance -- even after
1894 // being sent to another address.
1895 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1896 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1897 // already refuses previously-known transaction ids entirely.
1898 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1899 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1900 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1901 // initial block download.
1902 bool fEnforceBIP30 = true; // Always active in NovaCoin
1903 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1905 //// issue here: it doesn't know the version
1906 unsigned int nTxPos;
1908 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1909 // 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
1912 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1914 map<uint256, CTxIndex> mapQueuedChanges;
1915 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1918 int64_t nValueIn = 0;
1919 int64_t nValueOut = 0;
1920 unsigned int nSigOps = 0;
1923 auto hashTx = tx.GetHash();
1925 if (fEnforceBIP30) {
1926 CTxIndex txindexOld;
1927 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1928 for(CDiskTxPos &pos : txindexOld.vSpent)
1934 nSigOps += tx.GetLegacySigOpCount();
1935 if (nSigOps > MAX_BLOCK_SIGOPS)
1936 return DoS(100, error("ConnectBlock() : too many sigops"));
1938 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1940 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1942 MapPrevTx mapInputs;
1943 if (tx.IsCoinBase())
1944 nValueOut += tx.GetValueOut();
1948 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1951 // Add in sigops done by pay-to-script-hash inputs;
1952 // this is to prevent a "rogue miner" from creating
1953 // an incredibly-expensive-to-validate block.
1954 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1955 if (nSigOps > MAX_BLOCK_SIGOPS)
1956 return DoS(100, error("ConnectBlock() : too many sigops"));
1958 auto nTxValueIn = tx.GetValueIn(mapInputs);
1959 auto nTxValueOut = tx.GetValueOut();
1960 nValueIn += nTxValueIn;
1961 nValueOut += nTxValueOut;
1962 if (!tx.IsCoinStake())
1963 nFees += nTxValueIn - nTxValueOut;
1965 unsigned int nFlags = SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH;
1967 if (tx.nTime >= CHECKLOCKTIMEVERIFY_SWITCH_TIME) {
1968 nFlags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1969 // OP_CHECKSEQUENCEVERIFY is senseless without BIP68, so we're going disable it for now.
1970 // nFlags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1973 std::vector<CScriptCheck> vChecks;
1974 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, nFlags, nScriptCheckThreads ? &vChecks : NULL))
1976 control.Add(vChecks);
1979 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1982 if (!control.Wait())
1983 return DoS(100, false);
1985 if (IsProofOfWork())
1987 auto nBlockReward = GetProofOfWorkReward(nBits, nFees);
1989 // Check coinbase reward
1990 if (vtx[0].GetValueOut() > nBlockReward)
1991 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1992 vtx[0].GetValueOut(),
1996 // track money supply and mint amount info
1997 pindex->nMint = nValueOut - nValueIn + nFees;
1998 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1999 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
2000 return error("Connect() : WriteBlockIndex for pindex failed");
2002 // fees are not collected by proof-of-stake miners
2003 // fees are destroyed to compensate the entire network
2004 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
2005 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
2010 // Write queued txindex changes
2011 for (auto mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
2013 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
2014 return error("ConnectBlock() : UpdateTxIndex failed");
2017 // Update block index on disk without changing it in memory.
2018 // The memory index structure will be changed after the db commits.
2021 CDiskBlockIndex blockindexPrev(pindex->pprev);
2022 blockindexPrev.hashNext = pindex->GetBlockHash();
2023 if (!txdb.WriteBlockIndex(blockindexPrev))
2024 return error("ConnectBlock() : WriteBlockIndex failed");
2027 // Watch for transactions paying to me
2028 for(CTransaction& tx : vtx)
2029 SyncWithWallets(tx, this, true);
2035 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
2037 printf("REORGANIZE\n");
2040 CBlockIndex* pfork = pindexBest;
2041 CBlockIndex* plonger = pindexNew;
2042 while (pfork != plonger)
2044 while (plonger->nHeight > pfork->nHeight)
2045 if ((plonger = plonger->pprev) == NULL)
2046 return error("Reorganize() : plonger->pprev is null");
2047 if (pfork == plonger)
2049 if ((pfork = pfork->pprev) == NULL)
2050 return error("Reorganize() : pfork->pprev is null");
2053 // List of what to disconnect
2054 vector<CBlockIndex*> vDisconnect;
2055 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
2056 vDisconnect.push_back(pindex);
2058 // List of what to connect
2059 vector<CBlockIndex*> vConnect;
2060 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
2061 vConnect.push_back(pindex);
2062 reverse(vConnect.begin(), vConnect.end());
2064 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());
2065 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());
2067 // Disconnect shorter branch
2068 vector<CTransaction> vResurrect;
2069 for(CBlockIndex* pindex : vDisconnect)
2072 if (!block.ReadFromDisk(pindex))
2073 return error("Reorganize() : ReadFromDisk for disconnect failed");
2074 if (!block.DisconnectBlock(txdb, pindex))
2075 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
2077 // Queue memory transactions to resurrect
2078 for(const CTransaction& tx : block.vtx)
2079 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
2080 vResurrect.push_back(tx);
2083 // Connect longer branch
2084 vector<CTransaction> vDelete;
2085 for (unsigned int i = 0; i < vConnect.size(); i++)
2087 CBlockIndex* pindex = vConnect[i];
2089 if (!block.ReadFromDisk(pindex))
2090 return error("Reorganize() : ReadFromDisk for connect failed");
2091 if (!block.ConnectBlock(txdb, pindex))
2094 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
2097 // Queue memory transactions to delete
2098 for(const CTransaction& tx : block.vtx)
2099 vDelete.push_back(tx);
2101 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
2102 return error("Reorganize() : WriteHashBestChain failed");
2104 // Make sure it's successfully written to disk before changing memory structure
2105 if (!txdb.TxnCommit())
2106 return error("Reorganize() : TxnCommit failed");
2108 // Disconnect shorter branch
2109 for(CBlockIndex* pindex : vDisconnect)
2111 pindex->pprev->pnext = NULL;
2113 // Connect longer branch
2114 for(CBlockIndex* pindex : vConnect)
2116 pindex->pprev->pnext = pindex;
2118 // Resurrect memory transactions that were in the disconnected branch
2119 for(CTransaction& tx : vResurrect)
2120 tx.AcceptToMemoryPool(txdb, false);
2122 // Delete redundant memory transactions that are in the connected branch
2123 for(CTransaction& tx : vDelete)
2126 printf("REORGANIZE: done\n");
2132 // Called from inside SetBestChain: attaches a block to the new best chain being built
2133 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
2135 auto hash = GetHash();
2137 // Adding to current best branch
2138 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
2141 InvalidChainFound(pindexNew);
2144 if (!txdb.TxnCommit())
2145 return error("SetBestChain() : TxnCommit failed");
2147 // Add to current best branch
2148 pindexNew->pprev->pnext = pindexNew;
2150 // Delete redundant memory transactions
2151 for(CTransaction& tx : vtx)
2157 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
2159 auto hash = GetHash();
2161 if (!txdb.TxnBegin())
2162 return error("SetBestChain() : TxnBegin failed");
2164 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2166 txdb.WriteHashBestChain(hash);
2167 if (!txdb.TxnCommit())
2168 return error("SetBestChain() : TxnCommit failed");
2169 pindexGenesisBlock = pindexNew;
2171 else if (hashPrevBlock == hashBestChain)
2173 if (!SetBestChainInner(txdb, pindexNew))
2174 return error("SetBestChain() : SetBestChainInner failed");
2178 // the first block in the new chain that will cause it to become the new best chain
2179 CBlockIndex *pindexIntermediate = pindexNew;
2181 // list of blocks that need to be connected afterwards
2182 std::vector<CBlockIndex*> vpindexSecondary;
2184 // Reorganize is costly in terms of db load, as it works in a single db transaction.
2185 // Try to limit how much needs to be done inside
2186 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
2188 vpindexSecondary.push_back(pindexIntermediate);
2189 pindexIntermediate = pindexIntermediate->pprev;
2192 if (!vpindexSecondary.empty())
2193 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
2195 // Switch to new best branch
2196 if (!Reorganize(txdb, pindexIntermediate))
2199 InvalidChainFound(pindexNew);
2200 return error("SetBestChain() : Reorganize failed");
2203 // Connect further blocks
2204 for (std::vector<CBlockIndex*>::reverse_iterator rit = vpindexSecondary.rbegin(); rit != vpindexSecondary.rend(); ++rit)
2207 if (!block.ReadFromDisk(*rit))
2209 printf("SetBestChain() : ReadFromDisk failed\n");
2212 if (!txdb.TxnBegin()) {
2213 printf("SetBestChain() : TxnBegin 2 failed\n");
2216 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
2217 if (!block.SetBestChainInner(txdb, *rit))
2222 // Update best block in wallet (so we can detect restored wallets)
2223 bool fIsInitialDownload = IsInitialBlockDownload();
2224 if (!fIsInitialDownload)
2226 const CBlockLocator locator(pindexNew);
2227 ::SetBestChain(locator);
2231 hashBestChain = hash;
2232 pindexBest = pindexNew;
2233 pblockindexFBBHLast = NULL;
2234 nBestHeight = pindexBest->nHeight;
2235 nBestChainTrust = pindexNew->nChainTrust;
2236 nTimeBestReceived = GetTime();
2237 nTransactionsUpdated++;
2239 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2241 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
2242 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2243 CBigNum(nBestChainTrust).ToString().c_str(),
2244 nBestBlockTrust.Get64(),
2245 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2247 // Check the version of the last 100 blocks to see if we need to upgrade:
2248 if (!fIsInitialDownload)
2251 const CBlockIndex* pindex = pindexBest;
2252 for (int i = 0; i < 100 && pindex != NULL; i++)
2254 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2256 pindex = pindex->pprev;
2259 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2260 if (nUpgraded > 100/2)
2261 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2262 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2265 auto strCmd = GetArg("-blocknotify", "");
2267 if (!fIsInitialDownload && !strCmd.empty())
2269 boost::thread t(runCommand, regex_replace(strCmd, static_cast<regex>("%s"), hashBestChain.GetHex()));
2274 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2275 // Only those coins meeting minimum age requirement counts. As those
2276 // transactions not in main chain are not currently indexed so we
2277 // might not find out about their coin age. Older transactions are
2278 // guaranteed to be in main chain by sync-checkpoint. This rule is
2279 // introduced to help nodes establish a consistent view of the coin
2280 // age (trust score) of competing branches.
2281 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2283 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2289 for(const CTxIn& txin : vin)
2291 // First try finding the previous transaction in database
2292 CTransaction txPrev;
2294 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2295 continue; // previous transaction not in main chain
2296 if (nTime < txPrev.nTime)
2297 return false; // Transaction timestamp violation
2299 // Read block header
2301 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2302 return false; // unable to read block of previous transaction
2303 if (block.GetBlockTime() + nStakeMinAge > nTime)
2304 continue; // only count coins meeting min age requirement
2306 auto nValueIn = txPrev.vout[txin.prevout.n].nValue;
2307 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2309 if (fDebug && GetBoolArg("-printcoinage"))
2310 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2313 auto bnCoinDay = bnCentSecond * CENT / COIN / nOneDay;
2314 if (fDebug && GetBoolArg("-printcoinage"))
2315 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2316 nCoinAge = bnCoinDay.getuint64();
2320 // ppcoin: total coin age spent in block, in the unit of coin-days.
2321 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2326 for(const CTransaction& tx : vtx)
2328 uint64_t nTxCoinAge;
2329 if (tx.GetCoinAge(txdb, nTxCoinAge))
2330 nCoinAge += nTxCoinAge;
2335 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2337 if (fDebug && GetBoolArg("-printcoinage"))
2338 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2342 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2344 // Check for duplicate
2345 auto hash = GetHash();
2346 if (mapBlockIndex.count(hash))
2347 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2349 // Construct new block index object
2350 CBlockIndex* pindexNew = new(nothrow) CBlockIndex(nFile, nBlockPos, *this);
2352 return error("AddToBlockIndex() : new CBlockIndex failed");
2353 pindexNew->phashBlock = &hash;
2354 auto miPrev = mapBlockIndex.find(hashPrevBlock);
2355 if (miPrev != mapBlockIndex.end())
2357 pindexNew->pprev = (*miPrev).second;
2358 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2361 // ppcoin: compute chain trust score
2362 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2364 // ppcoin: compute stake entropy bit for stake modifier
2365 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2366 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2368 // ppcoin: record proof-of-stake hash value
2369 if (pindexNew->IsProofOfStake())
2371 if (!mapProofOfStake.count(hash))
2372 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2373 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2376 // ppcoin: compute stake modifier
2377 uint64_t nStakeModifier = 0;
2378 bool fGeneratedStakeModifier = false;
2379 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2380 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2381 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2382 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2383 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2384 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2386 // Add to mapBlockIndex
2387 auto mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2388 if (pindexNew->IsProofOfStake())
2389 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2390 pindexNew->phashBlock = &((*mi).first);
2392 // Write to disk block index
2394 if (!txdb.TxnBegin())
2396 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2397 if (!txdb.TxnCommit())
2401 if (pindexNew->nChainTrust > nBestChainTrust)
2402 if (!SetBestChain(txdb, pindexNew))
2405 if (pindexNew == pindexBest)
2407 // Notify UI to display prev block's coinbase if it was ours
2408 static uint256 hashPrevBestCoinBase;
2409 UpdatedTransaction(hashPrevBestCoinBase);
2410 hashPrevBestCoinBase = vtx[0].GetHash();
2413 static int8_t counter = 0;
2414 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2415 uiInterface.NotifyBlocksChanged();
2422 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2424 // These are checks that are independent of context
2425 // that can be verified before saving an orphan block.
2427 set<uint256> uniqueTx; // tx hashes
2428 unsigned int nSigOps = 0; // total sigops
2431 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2432 return DoS(100, error("CheckBlock() : size limits failed"));
2434 bool fProofOfStake = IsProofOfStake();
2436 // First transaction must be coinbase, the rest must not be
2437 if (!vtx[0].IsCoinBase())
2438 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2440 if (!vtx[0].CheckTransaction())
2441 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2443 uniqueTx.insert(vtx[0].GetHash());
2444 nSigOps += vtx[0].GetLegacySigOpCount();
2448 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2449 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2451 // nNonce must be zero for proof-of-stake blocks
2453 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2455 // Coinbase output should be empty if proof-of-stake block
2456 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2457 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2459 // Check coinstake timestamp
2460 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2461 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2463 // NovaCoin: check proof-of-stake block signature
2464 if (fCheckSig && !CheckBlockSignature())
2465 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2467 if (!vtx[1].CheckTransaction())
2468 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2470 uniqueTx.insert(vtx[1].GetHash());
2471 nSigOps += vtx[1].GetLegacySigOpCount();
2475 // Check proof of work matches claimed amount
2476 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2477 return DoS(50, error("CheckBlock() : proof of work failed"));
2480 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2481 return error("CheckBlock() : block timestamp too far in the future");
2483 // Check coinbase timestamp
2484 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2485 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2488 // Iterate all transactions starting from second for proof-of-stake block
2489 // or first for proof-of-work block
2490 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2492 const CTransaction& tx = vtx[i];
2494 // Reject coinbase transactions at non-zero index
2495 if (tx.IsCoinBase())
2496 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2498 // Reject coinstake transactions at index != 1
2499 if (tx.IsCoinStake())
2500 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2502 // Check transaction timestamp
2503 if (GetBlockTime() < (int64_t)tx.nTime)
2504 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2506 // Check transaction consistency
2507 if (!tx.CheckTransaction())
2508 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2510 // Add transaction hash into list of unique transaction IDs
2511 uniqueTx.insert(tx.GetHash());
2513 // Calculate sigops count
2514 nSigOps += tx.GetLegacySigOpCount();
2517 // Check for duplicate txids. This is caught by ConnectInputs(),
2518 // but catching it earlier avoids a potential DoS attack:
2519 if (uniqueTx.size() != vtx.size())
2520 return DoS(100, error("CheckBlock() : duplicate transaction"));
2522 // Reject block if validation would consume too much resources.
2523 if (nSigOps > MAX_BLOCK_SIGOPS)
2524 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2526 // Check merkle root
2527 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2528 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2533 bool CBlock::AcceptBlock()
2535 // Check for duplicate
2536 auto hash = GetHash();
2537 if (mapBlockIndex.count(hash))
2538 return error("AcceptBlock() : block already in mapBlockIndex");
2540 // Get prev block index
2541 auto mi = mapBlockIndex.find(hashPrevBlock);
2542 if (mi == mapBlockIndex.end())
2543 return DoS(10, error("AcceptBlock() : prev block not found"));
2544 CBlockIndex* pindexPrev = (*mi).second;
2545 int nHeight = pindexPrev->nHeight+1;
2547 // Check proof-of-work or proof-of-stake
2548 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2549 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2551 int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
2552 int nMaxOffset = 12 * nOneHour; // 12 hours
2553 if (fTestNet || pindexPrev->nTime < 1450569600)
2554 nMaxOffset = 7 * nOneWeek; // One week (permanently on testNet or until 20 Dec, 2015 on mainNet)
2556 // Check timestamp against prev
2557 if (GetBlockTime() <= nMedianTimePast || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2558 return error("AcceptBlock() : block's timestamp is too early");
2560 // Don't accept blocks with future timestamps
2561 if (pindexPrev->nHeight > 1 && nMedianTimePast + nMaxOffset < GetBlockTime())
2562 return error("AcceptBlock() : block's timestamp is too far in the future");
2564 // Check that all transactions are finalized
2565 for(const CTransaction& tx : vtx)
2566 if (!tx.IsFinal(nHeight, GetBlockTime()))
2567 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2569 // Check that the block chain matches the known block chain up to a checkpoint
2570 if (!Checkpoints::CheckHardened(nHeight, hash))
2571 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2573 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2575 // Check that the block satisfies synchronized checkpoint
2576 if (CheckpointsMode == Checkpoints::CP_STRICT && !cpSatisfies)
2577 return error("AcceptBlock() : rejected by synchronized checkpoint");
2579 if (CheckpointsMode == Checkpoints::CP_ADVISORY && !cpSatisfies)
2580 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2582 // Enforce rule that the coinbase starts with serialized block height
2583 auto expect = CScript() << nHeight;
2584 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2585 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2586 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2588 // Write block to history file
2589 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2590 return error("AcceptBlock() : out of disk space");
2591 unsigned int nFile = std::numeric_limits<unsigned int>::max();
2592 unsigned int nBlockPos = 0;
2593 if (!WriteToDisk(nFile, nBlockPos))
2594 return error("AcceptBlock() : WriteToDisk failed");
2595 if (!AddToBlockIndex(nFile, nBlockPos))
2596 return error("AcceptBlock() : AddToBlockIndex failed");
2598 // Relay inventory, but don't relay old inventory during initial block download
2599 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2600 if (hashBestChain == hash)
2603 for(CNode* pnode : vNodes)
2604 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2605 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2608 // ppcoin: check pending sync-checkpoint
2609 Checkpoints::AcceptPendingSyncCheckpoint();
2614 uint256 CBlockIndex::GetBlockTrust() const
2617 bnTarget.SetCompact(nBits);
2622 // Return 1 for the first 12 blocks
2623 if (pprev == NULL || pprev->nHeight < 12)
2626 const CBlockIndex* currentIndex = pprev;
2628 if(IsProofOfStake())
2630 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2632 // Return 1/3 of score if parent block is not the PoW block
2633 if (!pprev->IsProofOfWork())
2634 return (bnNewTrust / 3).getuint256();
2638 // Check last 12 blocks type
2639 while (pprev->nHeight - currentIndex->nHeight < 12)
2641 if (currentIndex->IsProofOfWork())
2643 currentIndex = currentIndex->pprev;
2646 // Return 1/3 of score if less than 3 PoW blocks found
2648 return (bnNewTrust / 3).getuint256();
2650 return bnNewTrust.getuint256();
2654 // Calculate work amount for block
2655 CBigNum bnPoWTrust = CBigNum(nPoWBase) / (bnTarget+1);
2657 // Set nPowTrust to 1 if PoW difficulty is too low
2661 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2663 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2664 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2665 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2669 // Check last 12 blocks type
2670 while (pprev->nHeight - currentIndex->nHeight < 12)
2672 if (currentIndex->IsProofOfStake())
2674 currentIndex = currentIndex->pprev;
2677 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2679 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2681 bnTarget.SetCompact(pprev->nBits);
2686 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2688 // Return nPoWTrust + full trust score for previous block nBits
2689 return (bnPoWTrust + bnNewTrust).getuint256();
2693 CBlock CBlockIndex::GetBlockHeader() const
2696 block.nVersion = nVersion;
2698 block.hashPrevBlock = pprev->GetBlockHash();
2699 block.hashMerkleRoot = hashMerkleRoot;
2700 block.nTime = nTime;
2701 block.nBits = nBits;
2702 block.nNonce = nNonce;
2706 enum { nMedianTimeSpan=11 };
2708 int64_t CBlockIndex::GetMedianTimePast() const
2710 int64_t pmedian[nMedianTimeSpan];
2711 int64_t* pbegin = &pmedian[nMedianTimeSpan];
2712 int64_t* pend = &pmedian[nMedianTimeSpan];
2713 const CBlockIndex* pindex = this;
2714 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
2715 *(--pbegin) = pindex->GetBlockTime();
2717 return pbegin[(pend - pbegin)/2];
2720 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2722 unsigned int nFound = 0;
2723 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2725 if (pstart->nVersion >= minVersion)
2727 pstart = pstart->pprev;
2729 return (nFound >= nRequired);
2732 bool CBlockIndex::SetStakeEntropyBit(unsigned int nEntropyBit)
2734 if (nEntropyBit > 1)
2736 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
2740 void CBlockIndex::SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier)
2742 nStakeModifier = nModifier;
2743 if (fGeneratedStakeModifier)
2744 nFlags |= BLOCK_STAKE_MODIFIER;
2747 string CBlockIndex::ToString() const
2749 return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016" PRIx64 ", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
2750 (const void*)pprev, (const void*)pnext, nFile, nBlockPos, nHeight,
2751 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
2752 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
2753 nStakeModifier, nStakeModifierChecksum,
2754 hashProofOfStake.ToString().c_str(),
2755 prevoutStake.ToString().c_str(), nStakeTime,
2756 hashMerkleRoot.ToString().c_str(),
2757 GetBlockHash().ToString().c_str());
2760 bool static ReserealizeBlockSignature(CBlock* pblock)
2762 if (pblock->IsProofOfWork())
2764 pblock->vchBlockSig.clear();
2768 return CPubKey::ReserealizeSignature(pblock->vchBlockSig);
2771 bool static IsCanonicalBlockSignature(CBlock* pblock)
2773 if (pblock->IsProofOfWork())
2774 return pblock->vchBlockSig.empty();
2776 return IsDERSignature(pblock->vchBlockSig);
2779 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2781 // Check for duplicate
2782 auto hash = pblock->GetHash();
2783 if (mapBlockIndex.count(hash))
2784 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2785 if (mapOrphanBlocks.count(hash))
2786 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2788 // Check that block isn't listed as unconditionally banned.
2789 if (!Checkpoints::CheckBanned(hash)) {
2791 pfrom->Misbehaving(100);
2792 return error("ProcessBlock() : block %s is rejected by hard-coded banlist", hash.GetHex().substr(0,20).c_str());
2795 // Check proof-of-stake
2796 // Limited duplicity on stake: prevents block flood attack
2797 // Duplicate stake allowed only when there is orphan child block
2798 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2799 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());
2801 // Strip the garbage from newly received blocks, if we found some
2802 if (!IsCanonicalBlockSignature(pblock)) {
2803 if (!ReserealizeBlockSignature(pblock))
2804 printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2807 // Preliminary checks
2808 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2809 return error("ProcessBlock() : CheckBlock FAILED");
2811 // ppcoin: verify hash target and signature of coinstake tx
2812 if (pblock->IsProofOfStake())
2814 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2815 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2817 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2818 return false; // do not error here as we expect this during initial block download
2820 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2821 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2824 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2825 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2827 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2828 auto deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2830 bnNewBlock.SetCompact(pblock->nBits);
2833 if (pblock->IsProofOfStake())
2834 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2836 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2838 if (bnNewBlock > bnRequired)
2841 pfrom->Misbehaving(100);
2842 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2846 // ppcoin: ask for pending sync-checkpoint if any
2847 if (!IsInitialBlockDownload())
2848 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2850 // If don't already have its previous block, shunt it off to holding area until we get it
2851 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2853 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2854 // ppcoin: check proof-of-stake
2855 if (pblock->IsProofOfStake())
2857 // Limited duplicity on stake: prevents block flood attack
2858 // Duplicate stake allowed only when there is orphan child block
2859 if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2860 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());
2862 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2864 CBlock* pblock2 = new CBlock(*pblock);
2865 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2866 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2868 // Ask this guy to fill in what we're missing
2871 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2872 // ppcoin: getblocks may not obtain the ancestor block rejected
2873 // earlier by duplicate-stake check so we ask for it again directly
2874 if (!IsInitialBlockDownload())
2875 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2881 if (!pblock->AcceptBlock())
2882 return error("ProcessBlock() : AcceptBlock FAILED");
2884 // Recursively process any orphan blocks that depended on this one
2885 vector<uint256> vWorkQueue;
2886 vWorkQueue.push_back(hash);
2887 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2889 auto hashPrev = vWorkQueue[i];
2890 for (auto mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2891 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2894 CBlock* pblockOrphan = (*mi).second;
2895 if (pblockOrphan->AcceptBlock())
2896 vWorkQueue.push_back(pblockOrphan->GetHash());
2897 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2898 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2899 delete pblockOrphan;
2901 mapOrphanBlocksByPrev.erase(hashPrev);
2904 printf("ProcessBlock: ACCEPTED\n");
2906 // ppcoin: if responsible for sync-checkpoint send it
2907 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2908 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2913 // ppcoin: check block signature
2914 bool CBlock::CheckBlockSignature() const
2916 if (vchBlockSig.empty())
2919 txnouttype whichType;
2920 vector<valtype> vSolutions;
2921 if (!Solver(vtx[1].vout[1].scriptPubKey, whichType, vSolutions))
2924 if (whichType == TX_PUBKEY)
2926 auto& vchPubKey = vSolutions[0];
2927 CPubKey key(vchPubKey);
2930 return key.Verify(GetHash(), vchBlockSig);
2942 uint256 CDiskBlockIndex::GetBlockHash() const
2944 if (fUseFastIndex && blockHash != 0)
2948 block.nVersion = nVersion;
2949 block.hashPrevBlock = hashPrev;
2950 block.hashMerkleRoot = hashMerkleRoot;
2951 block.nTime = nTime;
2952 block.nBits = nBits;
2953 block.nNonce = nNonce;
2955 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
2960 string CDiskBlockIndex::ToString() const
2962 string str = "CDiskBlockIndex(";
2963 str += CBlockIndex::ToString();
2964 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
2965 GetBlockHash().ToString().c_str(),
2966 hashPrev.ToString().c_str(),
2967 hashNext.ToString().c_str());
2975 void CBlockLocator::Set(const CBlockIndex* pindex)
2981 vHave.push_back(pindex->GetBlockHash());
2982 // Exponentially larger steps back
2983 for (int i = 0; pindex && i < nStep; i++)
2984 pindex = pindex->pprev;
2985 if (vHave.size() > 10)
2988 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2991 int CBlockLocator::GetDistanceBack()
2993 // Retrace how far back it was in the sender's branch
2996 for(const auto& hash : vHave)
2998 auto mi = mapBlockIndex.find(hash);
2999 if (mi != mapBlockIndex.end())
3001 auto pindex = (*mi).second;
3002 if (pindex->IsInMainChain())
3012 CBlockIndex* CBlockLocator::GetBlockIndex()
3014 // Find the first block the caller has in the main chain
3015 for(const auto& hash : vHave)
3017 auto mi = mapBlockIndex.find(hash);
3018 if (mi != mapBlockIndex.end())
3020 auto pindex = (*mi).second;
3021 if (pindex->IsInMainChain())
3025 return pindexGenesisBlock;
3028 uint256 CBlockLocator::GetBlockHash()
3030 // Find the first block the caller has in the main chain
3031 for(const uint256& hash : vHave)
3033 auto mi = mapBlockIndex.find(hash);
3034 if (mi != mapBlockIndex.end())
3036 auto pindex = (*mi).second;
3037 if (pindex->IsInMainChain())
3041 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
3044 int CBlockLocator::GetHeight()
3046 CBlockIndex* pindex = GetBlockIndex();
3049 return pindex->nHeight;
3052 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3054 uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
3056 // Check for nMinDiskSpace bytes (currently 50MB)
3057 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3060 string strMessage("Warning: Disk space is low!");
3061 strMiscWarning = strMessage;
3062 printf("*** %s\n", strMessage.c_str());
3063 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
3070 static filesystem::path BlockFilePath(unsigned int nFile)
3072 string strBlockFn = strprintf("blk%04u.dat", nFile);
3073 return GetDataDir() / strBlockFn;
3076 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
3078 if ((nFile < 1) || (nFile == std::numeric_limits<uint32_t>::max()))
3080 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
3083 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
3085 if (fseek(file, nBlockPos, SEEK_SET) != 0)
3094 static unsigned int nCurrentBlockFile = 1;
3096 FILE* AppendBlockFile(unsigned int& nFileRet)
3101 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
3104 if (fseek(file, 0, SEEK_END) != 0)
3109 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
3110 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
3112 nFileRet = nCurrentBlockFile;
3116 nCurrentBlockFile++;
3120 void UnloadBlockIndex()
3122 mapBlockIndex.clear();
3123 setStakeSeen.clear();
3124 pindexGenesisBlock = NULL;
3126 nBestChainTrust = 0;
3127 nBestInvalidTrust = 0;
3132 bool LoadBlockIndex(bool fAllowNew)
3136 nNetworkID = 0xefc0f2cd;
3138 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
3139 nStakeMinAge = 2 * nOneHour; // test net min age is 2 hours
3140 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
3141 nCoinbaseMaturity = 10; // test maturity is 10 blocks
3142 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
3149 if (!txdb.LoadBlockIndex())
3153 // Init with genesis block
3155 if (mapBlockIndex.empty())
3164 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
3165 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
3166 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
3168 // vMerkleTree: 4cb33b3b6a
3172 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
3173 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
3174 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
3176 // vMerkleTree: 4cb33b3b6a
3178 const string strTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
3180 txNew.nTime = 1360105017;
3181 txNew.vin.resize(1);
3182 txNew.vout.resize(1);
3183 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>(strTimestamp.begin(), strTimestamp.end());
3184 txNew.vout[0].SetEmpty();
3186 block.vtx.push_back(txNew);
3187 block.hashPrevBlock = 0;
3188 block.hashMerkleRoot = block.BuildMerkleTree();
3190 block.nTime = 1360105017;
3191 block.nBits = bnProofOfWorkLimit.GetCompact();
3192 block.nNonce = !fTestNet ? 1575379 : 46534;
3195 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
3197 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
3198 assert(block.CheckBlock());
3200 // Start new block file
3202 unsigned int nBlockPos;
3203 if (!block.WriteToDisk(nFile, nBlockPos))
3204 return error("LoadBlockIndex() : writing genesis block to disk failed");
3205 if (!block.AddToBlockIndex(nFile, nBlockPos))
3206 return error("LoadBlockIndex() : genesis block not accepted");
3208 // initialize synchronized checkpoint
3209 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
3210 return error("LoadBlockIndex() : failed to init sync checkpoint");
3212 // upgrade time set to zero if txdb initialized
3214 if (!txdb.WriteModifierUpgradeTime(0))
3215 return error("LoadBlockIndex() : failed to init upgrade info");
3216 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
3222 string strPubKey = "";
3223 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
3225 // write checkpoint master key to db
3227 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
3228 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
3229 if (!txdb.TxnCommit())
3230 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
3231 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
3232 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
3235 // upgrade time set to zero if blocktreedb initialized
3236 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
3238 if (nModifierUpgradeTime)
3239 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
3241 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
3245 nModifierUpgradeTime = GetTime();
3246 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
3247 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
3248 return error("LoadBlockIndex() : failed to write upgrade info");
3261 void PrintBlockTree()
3263 // pre-compute tree structure
3264 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
3265 for (auto mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
3267 CBlockIndex* pindex = (*mi).second;
3268 mapNext[pindex->pprev].push_back(pindex);
3270 //while (rand() % 3 == 0)
3271 // mapNext[pindex->pprev].push_back(pindex);
3274 vector<pair<int, CBlockIndex*> > vStack;
3275 vStack.push_back(make_pair(0, pindexGenesisBlock));
3278 while (!vStack.empty())
3280 int nCol = vStack.back().first;
3281 CBlockIndex* pindex = vStack.back().second;
3284 // print split or gap
3285 if (nCol > nPrevCol)
3287 for (int i = 0; i < nCol-1; i++)
3291 else if (nCol < nPrevCol)
3293 for (int i = 0; i < nCol; i++)
3300 for (int i = 0; i < nCol; i++)
3305 block.ReadFromDisk(pindex);
3306 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
3310 block.GetHash().ToString().c_str(),
3312 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
3313 FormatMoney(pindex->nMint).c_str(),
3316 PrintWallets(block);
3318 // put the main time-chain first
3319 vector<CBlockIndex*>& vNext = mapNext[pindex];
3320 for (unsigned int i = 0; i < vNext.size(); i++)
3322 if (vNext[i]->pnext)
3324 swap(vNext[0], vNext[i]);
3330 for (unsigned int i = 0; i < vNext.size(); i++)
3331 vStack.push_back(make_pair(nCol+i, vNext[i]));
3335 bool LoadExternalBlockFile(FILE* fileIn, CClientUIInterface& uiInterface)
3337 auto nStart = GetTimeMillis();
3338 vector<uint8_t> pchData(10 * (8+MAX_BLOCK_SIZE));
3339 int32_t nLoaded = 0;
3343 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
3345 while (nPos != std::numeric_limits<uint32_t>::max() && blkdat.good() && !fRequestShutdown)
3349 fseek(blkdat, nPos, SEEK_SET);
3350 auto nRead = fread(&pchData[0], 1, pchData.size(), blkdat);
3353 nPos = numeric_limits<uint32_t>::max();
3356 auto it = pchData.begin();
3357 while(it != pchData.end() && !fRequestShutdown)
3359 auto nBlockLength = *reinterpret_cast<const uint32_t*>(&(*(it+4)));
3360 auto SeekToNext = [&pchData, &it, &nPos, &nBlockLength]() {
3362 it = search(it+8, pchData.end(), BEGIN(nNetworkID), END(nNetworkID));
3363 if (it != pchData.end())
3364 nPos += (it - previt);
3366 if (nBlockLength > 0)
3368 if (nBlockLength > (uint32_t)distance(it, pchData.end()))
3371 break; // We've reached the end of buffer
3378 vector<unsigned char> vchBlockBytes(it+8, it+8+nBlockLength);
3379 CDataStream blockData(vchBlockBytes, SER_NETWORK, PROTOCOL_VERSION);
3382 catch (const std::exception&)
3384 printf("LoadExternalBlockFile() : Deserialize error caught at the position %" PRIu32 ", this block may be truncated.", nPos);
3388 if (ProcessBlock(NULL, &block))
3390 advance(it, 8 + nBlockLength);
3391 nPos += (8 + nBlockLength);
3393 static int64_t nLastUpdate = 0;
3394 if (GetTimeMillis() - nLastUpdate > 1000)
3396 uiInterface.InitMessage(strprintf(_("%" PRId32 " blocks were read."), nLoaded));
3397 nLastUpdate = GetTimeMillis();
3408 while(!fRequestShutdown);
3411 catch (const std::exception&) {
3412 printf("%s() : I/O error caught during load\n",
3413 BOOST_CURRENT_FUNCTION);
3416 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3420 //////////////////////////////////////////////////////////////////////////////
3425 extern map<uint256, CAlert> mapAlerts;
3426 extern CCriticalSection cs_mapAlerts;
3428 string GetWarnings(string strFor)
3431 string strStatusBar;
3434 if (GetBoolArg("-testsafemode"))
3437 // Misc warnings like out of disk space and clock is wrong
3438 if (!strMiscWarning.empty())
3441 strStatusBar = strMiscWarning;
3444 // if detected unmet upgrade requirement enter safe mode
3445 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3446 if (IsFixedModifierInterval(nModifierUpgradeTime + nOneDay)) // 1 day margin
3449 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3452 // if detected invalid checkpoint enter safe mode
3453 if (Checkpoints::hashInvalidCheckpoint != 0)
3456 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3462 for(auto& item : mapAlerts)
3464 const CAlert& alert = item.second;
3465 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3467 nPriority = alert.nPriority;
3468 strStatusBar = alert.strStatusBar;
3469 if (nPriority > 1000)
3470 strRPC = strStatusBar;
3475 if (strFor == "statusbar")
3476 return strStatusBar;
3477 else if (strFor == "rpc")
3479 assert(!"GetWarnings() : invalid parameter");
3490 //////////////////////////////////////////////////////////////////////////////
3496 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3498 int nType = inv.GetType();
3499 auto nHash = inv.GetHash();
3505 bool txInMap = false;
3508 txInMap = (mempool.exists(nHash));
3511 mapOrphanTransactions.count(nHash) ||
3512 txdb.ContainsTx(nHash);
3516 return mapBlockIndex.count(nHash) ||
3517 mapOrphanBlocks.count(nHash);
3519 // Don't know what it is, just say we already got one
3523 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3525 static map<CService, CPubKey> mapReuseKey;
3526 RandAddSeedPerfmon();
3528 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3529 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3531 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3535 if (strCommand == "version")
3537 // Each connection can only send one version message
3538 if (pfrom->nVersion != 0)
3540 pfrom->Misbehaving(1);
3547 uint64_t nNonce = 1;
3548 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3549 if (pfrom->nVersion < MIN_PROTO_VERSION)
3551 // Since February 20, 2012, the protocol is initiated at version 209,
3552 // and earlier versions are no longer supported
3553 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3554 pfrom->fDisconnect = true;
3558 if (pfrom->nVersion == 10300)
3559 pfrom->nVersion = 300;
3561 vRecv >> addrFrom >> nNonce;
3563 vRecv >> pfrom->strSubVer;
3565 vRecv >> pfrom->nStartingHeight;
3567 if (pfrom->fInbound && addrMe.IsRoutable())
3569 pfrom->addrLocal = addrMe;
3573 // Disconnect if we connected to ourself
3574 if (nNonce == nLocalHostNonce && nNonce > 1)
3576 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3577 pfrom->fDisconnect = true;
3581 if (pfrom->nVersion < 60010)
3583 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3584 pfrom->fDisconnect = true;
3588 // record my external IP reported by peer
3589 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3590 addrSeenByPeer = addrMe;
3592 // Be shy and don't send version until we hear
3593 if (pfrom->fInbound)
3594 pfrom->PushVersion();
3596 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3598 AddTimeData(pfrom->addr, nTime);
3601 pfrom->PushMessage("verack");
3602 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3604 if (!pfrom->fInbound)
3606 // Advertise our address
3607 if (!fNoListen && !IsInitialBlockDownload())
3609 auto addr = GetLocalAddress(&pfrom->addr);
3610 if (addr.IsRoutable())
3611 pfrom->PushAddress(addr);
3614 // Get recent addresses
3615 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3617 pfrom->PushMessage("getaddr");
3618 pfrom->fGetAddr = true;
3620 addrman.Good(pfrom->addr);
3622 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3624 addrman.Add(addrFrom, addrFrom);
3625 addrman.Good(addrFrom);
3629 // Ask the first connected node for block updates
3630 static int nAskedForBlocks = 0;
3631 if (!pfrom->fClient && !pfrom->fOneShot &&
3632 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3633 (pfrom->nVersion < NOBLKS_VERSION_START ||
3634 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3635 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3638 pfrom->PushGetBlocks(pindexBest, uint256(0));
3644 for(auto& item : mapAlerts)
3645 item.second.RelayTo(pfrom);
3648 // Relay sync-checkpoint
3650 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3651 if (!Checkpoints::checkpointMessage.IsNull())
3652 Checkpoints::checkpointMessage.RelayTo(pfrom);
3655 pfrom->fSuccessfullyConnected = true;
3657 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());
3659 cPeerBlockCounts.input(pfrom->nStartingHeight);
3661 // ppcoin: ask for pending sync-checkpoint if any
3662 if (!IsInitialBlockDownload())
3663 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3667 else if (pfrom->nVersion == 0)
3669 // Must have a version message before anything else
3670 pfrom->Misbehaving(1);
3675 else if (strCommand == "verack")
3677 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3681 else if (strCommand == "addr")
3683 vector<CAddress> vAddr;
3686 // Don't want addr from older versions unless seeding
3687 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3689 if (vAddr.size() > 1000)
3691 pfrom->Misbehaving(20);
3692 return error("message addr size() = %" PRIszu "", vAddr.size());
3695 // Store the new addresses
3696 vector<CAddress> vAddrOk;
3697 auto nNow = GetAdjustedTime();
3698 auto nSince = nNow - 10 * 60;
3699 for(CAddress& addr : vAddr)
3703 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3704 addr.nTime = nNow - 5 * nOneDay;
3705 pfrom->AddAddressKnown(addr);
3706 bool fReachable = IsReachable(addr);
3707 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3709 // Relay to a limited number of other nodes
3712 // Use deterministic randomness to send to the same nodes for 24 hours
3713 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3714 static uint256 hashSalt;
3716 hashSalt = GetRandHash();
3717 uint64_t hashAddr = addr.GetHash();
3718 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/nOneDay);
3719 hashRand = Hash(hashRand.begin(), hashRand.end());
3720 multimap<uint256, CNode*> mapMix;
3721 for(CNode* pnode : vNodes)
3723 if (pnode->nVersion < CADDR_TIME_VERSION)
3725 unsigned int nPointer;
3726 memcpy(&nPointer, &pnode, sizeof(nPointer));
3727 uint256 hashKey = hashRand ^ nPointer;
3728 hashKey = Hash(hashKey.begin(), hashKey.end());
3729 mapMix.insert(make_pair(hashKey, pnode));
3731 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3732 for (auto mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3733 ((*mi).second)->PushAddress(addr);
3736 // Do not store addresses outside our network
3738 vAddrOk.push_back(addr);
3740 addrman.Add(vAddrOk, pfrom->addr, 2 * nOneHour);
3741 if (vAddr.size() < 1000)
3742 pfrom->fGetAddr = false;
3743 if (pfrom->fOneShot)
3744 pfrom->fDisconnect = true;
3747 else if (strCommand == "inv")
3751 if (vInv.size() > MAX_INV_SZ)
3753 pfrom->Misbehaving(20);
3754 return error("message inv size() = %" PRIszu "", vInv.size());
3757 // find last block in inv vector
3758 int nLastBlock = -1;
3759 for (size_t nInv = 0; nInv < vInv.size(); nInv++) {
3760 if (vInv[vInv.size() - 1 - nInv].GetType() == MSG_BLOCK) {
3761 nLastBlock = (int) (vInv.size() - 1 - nInv);
3766 for (size_t nInv = 0; nInv < vInv.size(); nInv++)
3768 const CInv &inv = vInv[nInv];
3769 int nType = inv.GetType();
3770 auto nHash = inv.GetHash();
3774 pfrom->AddInventoryKnown(inv);
3776 bool fAlreadyHave = AlreadyHave(txdb, inv);
3778 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3782 else if (nType == MSG_BLOCK && mapOrphanBlocks.count(nHash)) {
3783 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[nHash]));
3784 } else if (nType == nLastBlock) {
3785 // In case we are on a very long side-chain, it is possible that we already have
3786 // the last block in an inv bundle sent in response to getblocks. Try to detect
3787 // this situation and push another getblocks to continue.
3788 pfrom->PushGetBlocks(mapBlockIndex[nHash], uint256(0));
3790 printf("force request: %s\n", inv.ToString().c_str());
3793 // Track requests for our stuff
3799 else if (strCommand == "getdata")
3803 if (vInv.size() > MAX_INV_SZ)
3805 pfrom->Misbehaving(20);
3806 return error("message getdata size() = %" PRIszu "", vInv.size());
3809 if (fDebugNet || (vInv.size() != 1))
3810 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3812 for(const CInv& inv : vInv)
3816 if (fDebugNet || (vInv.size() == 1))
3817 printf("received getdata for: %s\n", inv.ToString().c_str());
3819 int nType = inv.GetType();
3820 auto nHash = inv.GetHash();
3822 if (nType == MSG_BLOCK)
3824 // Send block from disk
3825 auto mi = mapBlockIndex.find(nHash);
3826 if (mi != mapBlockIndex.end())
3829 block.ReadFromDisk((*mi).second);
3830 pfrom->PushMessage("block", block);
3832 // Trigger them to send a getblocks request for the next batch of inventory
3833 if (nHash == pfrom->hashContinue)
3835 // ppcoin: send latest proof-of-work block to allow the
3836 // download node to accept as orphan (proof-of-stake
3837 // block might be rejected by stake connection check)
3839 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3840 pfrom->PushMessage("inv", vInv);
3841 pfrom->hashContinue = 0;
3845 else if (inv.IsKnownType())
3847 // Send stream from relay memory
3848 bool pushed = false;
3851 auto mi = mapRelay.find(inv);
3852 if (mi != mapRelay.end()) {
3853 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3857 if (!pushed && nType == MSG_TX) {
3859 if (mempool.exists(nHash)) {
3860 CTransaction tx = mempool.lookup(nHash);
3861 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3864 pfrom->PushMessage("tx", ss);
3869 // Track requests for our stuff
3875 else if (strCommand == "getblocks")
3877 CBlockLocator locator;
3879 vRecv >> locator >> hashStop;
3881 // Find the last block the caller has in the main chain
3882 CBlockIndex* pindex = locator.GetBlockIndex();
3884 // Send the rest of the chain
3886 pindex = pindex->pnext;
3888 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3889 for (; pindex; pindex = pindex->pnext)
3891 if (pindex->GetBlockHash() == hashStop)
3893 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3894 // ppcoin: tell downloading node about the latest block if it's
3895 // without risk being rejected due to stake connection check
3896 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3897 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3900 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3903 // When this block is requested, we'll send an inv that'll make them
3904 // getblocks the next batch of inventory.
3905 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3906 pfrom->hashContinue = pindex->GetBlockHash();
3911 else if (strCommand == "checkpoint")
3913 CSyncCheckpoint checkpoint;
3914 vRecv >> checkpoint;
3916 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3919 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3921 for(CNode* pnode : vNodes)
3922 checkpoint.RelayTo(pnode);
3926 else if (strCommand == "getheaders")
3928 CBlockLocator locator;
3930 vRecv >> locator >> hashStop;
3932 CBlockIndex* pindex = NULL;
3933 if (locator.IsNull())
3935 // If locator is null, return the hashStop block
3936 auto mi = mapBlockIndex.find(hashStop);
3937 if (mi == mapBlockIndex.end())
3939 pindex = (*mi).second;
3943 // Find the last block the caller has in the main chain
3944 pindex = locator.GetBlockIndex();
3946 pindex = pindex->pnext;
3949 vector<CBlock> vHeaders;
3951 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3952 for (; pindex; pindex = pindex->pnext)
3954 vHeaders.push_back(pindex->GetBlockHeader());
3955 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3958 pfrom->PushMessage("headers", vHeaders);
3962 else if (strCommand == "tx")
3964 vector<uint256> vWorkQueue;
3965 vector<uint256> vEraseQueue;
3966 CDataStream vMsg(vRecv);
3971 CInv inv(MSG_TX, tx.GetHash());
3972 pfrom->AddInventoryKnown(inv);
3974 bool fMissingInputs = false;
3975 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3977 auto nHash = inv.GetHash();
3979 SyncWithWallets(tx, NULL, true);
3980 RelayTransaction(tx, nHash);
3981 mapAlreadyAskedFor.erase(inv);
3982 vWorkQueue.push_back(nHash);
3983 vEraseQueue.push_back(nHash);
3985 // Recursively process any orphan transactions that depended on this one
3986 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3988 auto hashPrev = vWorkQueue[i];
3989 for (auto mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3990 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3993 const uint256& orphanTxHash = *mi;
3994 auto& orphanTx = mapOrphanTransactions[orphanTxHash];
3995 bool fMissingInputs2 = false;
3997 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3999 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
4000 SyncWithWallets(tx, NULL, true);
4001 RelayTransaction(orphanTx, orphanTxHash);
4002 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
4003 vWorkQueue.push_back(orphanTxHash);
4004 vEraseQueue.push_back(orphanTxHash);
4006 else if (!fMissingInputs2)
4009 vEraseQueue.push_back(orphanTxHash);
4010 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
4015 for(uint256 hash : vEraseQueue)
4016 EraseOrphanTx(hash);
4018 else if (fMissingInputs)
4022 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4023 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
4025 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
4027 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
4031 else if (strCommand == "block")
4035 auto hashBlock = block.GetHash();
4037 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
4040 CInv inv(MSG_BLOCK, hashBlock);
4041 pfrom->AddInventoryKnown(inv);
4043 if (ProcessBlock(pfrom, &block))
4044 mapAlreadyAskedFor.erase(inv);
4045 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
4049 // This asymmetric behavior for inbound and outbound connections was introduced
4050 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4051 // to users' AddrMan and later request them by sending getaddr messages.
4052 // Making users (which are behind NAT and can only make outgoing connections) ignore
4053 // getaddr message mitigates the attack.
4054 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4056 // Don't return addresses older than nCutOff timestamp
4057 int64_t nCutOff = GetTime() - (nNodeLifespan * nOneDay);
4058 pfrom->vAddrToSend.clear();
4059 vector<CAddress> vAddr = addrman.GetAddr();
4060 for(const CAddress &addr : vAddr)
4061 if(addr.nTime > nCutOff)
4062 pfrom->PushAddress(addr);
4066 else if (strCommand == "mempool")
4068 std::vector<uint256> vtxid;
4069 mempool.queryHashes(vtxid);
4071 for (unsigned int i = 0; i < vtxid.size(); i++) {
4072 CInv inv(MSG_TX, vtxid[i]);
4073 vInv.push_back(inv);
4074 if (i == (MAX_INV_SZ - 1))
4077 if (vInv.size() > 0)
4078 pfrom->PushMessage("inv", vInv);
4082 else if (strCommand == "checkorder")
4087 if (!GetBoolArg("-allowreceivebyip"))
4089 pfrom->PushMessage("reply", hashReply, 2, string(""));
4096 /// we have a chance to check the order here
4098 // Keep giving the same key to the same ip until they use it
4099 if (!mapReuseKey.count(pfrom->addr))
4100 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
4102 // Send back approval of order and pubkey to use
4103 CScript scriptPubKey;
4104 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
4105 pfrom->PushMessage("reply", hashReply, 0, scriptPubKey);
4109 else if (strCommand == "reply")
4114 CRequestTracker tracker;
4116 LOCK(pfrom->cs_mapRequests);
4117 auto mi = pfrom->mapRequests.find(hashReply);
4118 if (mi != pfrom->mapRequests.end())
4120 tracker = (*mi).second;
4121 pfrom->mapRequests.erase(mi);
4124 if (!tracker.IsNull())
4125 tracker.fn(tracker.param1, vRecv);
4129 else if (strCommand == "ping")
4133 // Echo the message back with the nonce. This allows for two useful features:
4135 // 1) A remote node can quickly check if the connection is operational
4136 // 2) Remote nodes can measure the latency of the network thread. If this node
4137 // is overloaded it won't respond to pings quickly and the remote node can
4138 // avoid sending us more work, like chain download requests.
4140 // The nonce stops the remote getting confused between different pings: without
4141 // it, if the remote node sends a ping once per second and this node takes 5
4142 // seconds to respond to each, the 5th ping the remote sends would appear to
4143 // return very quickly.
4144 pfrom->PushMessage("pong", nonce);
4148 else if (strCommand == "alert")
4153 auto alertHash = alert.GetHash();
4154 if (pfrom->setKnown.count(alertHash) == 0)
4156 if (alert.ProcessAlert())
4159 pfrom->setKnown.insert(alertHash);
4162 for(CNode* pnode : vNodes)
4163 alert.RelayTo(pnode);
4167 // Small DoS penalty so peers that send us lots of
4168 // duplicate/expired/invalid-signature/whatever alerts
4169 // eventually get banned.
4170 // This isn't a Misbehaving(100) (immediate ban) because the
4171 // peer might be an older or different implementation with
4172 // a different signature key, etc.
4173 pfrom->Misbehaving(10);
4181 // Ignore unknown commands for extensibility
4185 // Update the last seen time for this node's address
4186 if (pfrom->fNetworkNode)
4187 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
4188 AddressCurrentlyConnected(pfrom->addr);
4194 bool ProcessMessages(CNode* pfrom)
4196 CDataStream& vRecv = pfrom->vRecv;
4200 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
4204 // (4) message start
4213 // Don't bother if send buffer is too full to respond anyway
4214 if (pfrom->vSend.size() >= SendBufferSize())
4217 // Scan for message start
4218 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(nNetworkID), END(nNetworkID));
4219 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
4220 if (vRecv.end() - pstart < nHeaderSize)
4222 if ((int)vRecv.size() > nHeaderSize)
4224 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
4225 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
4229 if (pstart - vRecv.begin() > 0)
4230 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
4231 vRecv.erase(vRecv.begin(), pstart);
4234 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
4239 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
4242 string strCommand = hdr.GetCommand();
4245 unsigned int nMessageSize = hdr.nMessageSize;
4246 if (nMessageSize > MAX_SIZE)
4248 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
4251 if (nMessageSize > vRecv.size())
4253 // Rewind and wait for rest of message
4254 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
4259 auto hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4260 unsigned int nChecksum = 0;
4261 memcpy(&nChecksum, &hash, sizeof(nChecksum));
4262 if (nChecksum != hdr.nChecksum)
4264 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
4265 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
4269 // Copy message to its own buffer
4270 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
4271 vRecv.ignore(nMessageSize);
4279 fRet = ProcessMessage(pfrom, strCommand, vMsg);
4284 catch (std::ios_base::failure& e)
4286 if (strstr(e.what(), "end of data"))
4288 // Allow exceptions from under-length message on vRecv
4289 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());
4291 else if (strstr(e.what(), "size too large"))
4293 // Allow exceptions from over-long size
4294 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
4298 PrintExceptionContinue(&e, "ProcessMessages()");
4301 catch (std::exception& e) {
4302 PrintExceptionContinue(&e, "ProcessMessages()");
4304 PrintExceptionContinue(NULL, "ProcessMessages()");
4308 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
4316 bool SendMessages(CNode* pto)
4318 TRY_LOCK(cs_main, lockMain);
4320 // Current time in microseconds
4321 auto nNow = GetTimeMicros();
4323 // Don't send anything until we get their version message
4324 if (pto->nVersion == 0)
4327 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
4329 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
4331 pto->PushMessage("ping", nonce);
4335 if (pto->fStartSync) {
4336 pto->fStartSync = false;
4337 pto->PushGetBlocks(pindexBest, uint256(0));
4340 // Resend wallet transactions that haven't gotten in a block yet
4341 ResendWalletTransactions();
4343 // Address refresh broadcast
4344 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
4345 AdvertiseLocal(pto);
4346 pto->nNextLocalAddrSend = PoissonNextSend(nNow, nOneDay);
4352 if (pto->nNextAddrSend < nNow) {
4353 pto->nNextAddrSend = PoissonNextSend(nNow, 30);
4354 vector<CAddress> vAddr;
4355 vAddr.reserve(pto->vAddrToSend.size());
4356 for(const CAddress& addr : pto->vAddrToSend)
4358 if (pto->setAddrKnown.insert(addr).second)
4360 vAddr.push_back(addr);
4361 // receiver rejects addr messages larger than 1000
4362 if (vAddr.size() >= 1000)
4364 pto->PushMessage("addr", vAddr);
4369 pto->vAddrToSend.clear();
4371 pto->PushMessage("addr", vAddr);
4375 // Message: inventory
4378 vector<CInv> vInvWait;
4380 bool fSendTrickle = false;
4381 if (pto->nNextInvSend < nNow) {
4382 fSendTrickle = true;
4383 pto->nNextInvSend = PoissonNextSend(nNow, 5);
4385 LOCK(pto->cs_inventory);
4386 vInv.reserve(pto->vInventoryToSend.size());
4387 vInvWait.reserve(pto->vInventoryToSend.size());
4388 for(const CInv& inv : pto->vInventoryToSend)
4390 if (pto->setInventoryKnown.count(inv))
4393 // trickle out tx inv to protect privacy
4394 if (inv.GetType() == MSG_TX && !fSendTrickle)
4396 // 1/4 of tx invs blast to all immediately
4397 static uint256 hashSalt;
4399 hashSalt = GetRandHash();
4400 uint256 hashRand = inv.GetHash() ^ hashSalt;
4401 hashRand = Hash(hashRand.begin(), hashRand.end());
4402 bool fTrickleWait = ((hashRand & 3) != 0);
4406 vInvWait.push_back(inv);
4411 // returns true if wasn't already contained in the set
4412 if (pto->setInventoryKnown.insert(inv).second)
4414 vInv.push_back(inv);
4415 if (vInv.size() >= 1000)
4417 pto->PushMessage("inv", vInv);
4422 pto->vInventoryToSend = vInvWait;
4425 pto->PushMessage("inv", vInv);
4431 vector<CInv> vGetData;
4433 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4435 const CInv& inv = (*pto->mapAskFor.begin()).second;
4436 if (!AlreadyHave(txdb, inv))
4439 printf("sending getdata: %s\n", inv.ToString().c_str());
4440 vGetData.push_back(inv);
4441 if (vGetData.size() >= 1000)
4443 pto->PushMessage("getdata", vGetData);
4446 mapAlreadyAskedFor[inv] = nNow;
4448 pto->mapAskFor.erase(pto->mapAskFor.begin());
4450 if (!vGetData.empty())
4451 pto->PushMessage("getdata", vGetData);
4464 auto it1 = mapBlockIndex.begin();
4465 for (; it1 != mapBlockIndex.end(); it1++)
4466 delete (*it1).second;
4467 mapBlockIndex.clear();
4470 auto it2 = mapOrphanBlocks.begin();
4471 for (; it2 != mapOrphanBlocks.end(); it2++)
4472 delete (*it2).second;
4473 mapOrphanBlocks.clear();
4475 // orphan transactions
4477 } instance_of_cmaincleanup;