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>
24 CCriticalSection cs_setpwalletRegistered;
25 set<CWallet*> setpwalletRegistered;
27 CCriticalSection cs_main;
30 unsigned int nTransactionsUpdated = 0;
32 map<uint256, CBlockIndex*> mapBlockIndex;
33 set<pair<COutPoint, unsigned int> > setStakeSeen;
35 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
36 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
37 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
38 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
39 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
41 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
43 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
44 unsigned int nModifierInterval = 6 * nOneHour; // time to elapse before new modifier is computed
46 int nCoinbaseMaturity = 500;
48 CBlockIndex* pindexGenesisBlock = NULL;
51 uint256 nBestChainTrust = 0;
52 uint256 nBestInvalidTrust = 0;
54 uint256 hashBestChain = 0;
55 CBlockIndex* pindexBest = NULL;
56 int64_t nTimeBestReceived = 0;
57 int nScriptCheckThreads = 0;
59 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
61 map<uint256, CBlock*> mapOrphanBlocks;
62 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
63 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
64 map<uint256, uint256> mapProofOfStake;
66 map<uint256, CTransaction> mapOrphanTransactions;
67 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
69 // Constant stuff for coinbase transactions we create:
70 CScript COINBASE_FLAGS;
72 const string strMessageMagic = "NovaCoin Signed Message:\n";
75 int64_t nMinimumInputValue = MIN_TXOUT_AMOUNT;
77 // Ping and address broadcast intervals
78 int64_t nPingInterval = 30 * 60;
80 extern enum Checkpoints::CPMode CheckpointsMode;
82 //////////////////////////////////////////////////////////////////////////////
84 // dispatching functions
87 // These functions dispatch to one or all registered wallets
90 void RegisterWallet(CWallet* pwalletIn)
93 LOCK(cs_setpwalletRegistered);
94 setpwalletRegistered.insert(pwalletIn);
98 void UnregisterWallet(CWallet* pwalletIn)
101 LOCK(cs_setpwalletRegistered);
102 setpwalletRegistered.erase(pwalletIn);
106 // check whether the passed transaction is from us
107 bool static IsFromMe(CTransaction& tx)
109 for(CWallet* pwallet : setpwalletRegistered)
110 if (pwallet->IsFromMe(tx))
115 // make sure all wallets know about the given transaction, in the given block
116 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
120 // wallets need to refund inputs when disconnecting coinstake
121 if (tx.IsCoinStake())
123 for(CWallet* pwallet : setpwalletRegistered)
124 if (pwallet->IsFromMe(tx))
125 pwallet->DisableTransaction(tx);
130 for(CWallet* pwallet : setpwalletRegistered)
131 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
134 // notify wallets about a new best chain
135 void static SetBestChain(const CBlockLocator& loc)
137 for(CWallet* pwallet : setpwalletRegistered)
138 pwallet->SetBestChain(loc);
141 // notify wallets about an updated transaction
142 void static UpdatedTransaction(const uint256& hashTx)
144 for(CWallet* pwallet : setpwalletRegistered)
145 pwallet->UpdatedTransaction(hashTx);
149 void static PrintWallets(const CBlock& block)
151 for(CWallet* pwallet : setpwalletRegistered)
152 pwallet->PrintWallet(block);
155 // notify wallets about an incoming inventory (for request counts)
156 void static Inventory(const uint256& hash)
158 for(CWallet* pwallet : setpwalletRegistered)
159 pwallet->Inventory(hash);
162 // ask wallets to resend their transactions
163 void ResendWalletTransactions(bool fForceResend)
165 for(CWallet* pwallet : setpwalletRegistered)
166 pwallet->ResendWalletTransactions(fForceResend);
175 //////////////////////////////////////////////////////////////////////////////
177 // mapOrphanTransactions
180 bool AddOrphanTx(const CTransaction& tx)
182 auto hash = tx.GetHash();
183 if (mapOrphanTransactions.count(hash))
186 // Ignore big transactions, to avoid a
187 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
188 // large transaction with a missing parent then we assume
189 // it will rebroadcast it later, after the parent transaction(s)
190 // have been mined or received.
191 // 10,000 orphans, each of which is at most 5,000 bytes big is
192 // at most 500 megabytes of orphans:
194 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
198 printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
202 mapOrphanTransactions[hash] = tx;
203 for(const CTxIn& txin : tx.vin)
204 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
206 printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
207 mapOrphanTransactions.size());
211 void static EraseOrphanTx(uint256 hash)
213 if (!mapOrphanTransactions.count(hash))
215 const auto& tx = mapOrphanTransactions[hash];
216 for(const auto& txin : tx.vin)
218 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
219 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
220 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
222 mapOrphanTransactions.erase(hash);
225 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
227 unsigned int nEvicted = 0;
228 while (mapOrphanTransactions.size() > nMaxOrphans)
230 // Evict a random orphan:
231 auto randomhash = GetRandHash();
232 auto it = mapOrphanTransactions.lower_bound(randomhash);
233 if (it == mapOrphanTransactions.end())
234 it = mapOrphanTransactions.begin();
235 EraseOrphanTx(it->first);
247 //////////////////////////////////////////////////////////////////////////////
249 // CTransaction and CTxIndex
252 bool CTransaction::IsFinal(int nBlockHeight, int64_t nBlockTime) const
254 // Time based nLockTime implemented in 0.1.6
257 if (nBlockHeight == 0)
258 nBlockHeight = nBestHeight;
260 nBlockTime = GetAdjustedTime();
261 if ((int64_t)nLockTime < ((int64_t)nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
263 for(const CTxIn& txin : vin)
269 bool CTransaction::ReadFromDisk(CDiskTxPos pos, FILE** pfileRet)
271 auto filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
273 return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
276 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
277 return error("CTransaction::ReadFromDisk() : fseek failed");
282 catch (const std::exception&) {
283 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
286 // Return file pointer
289 if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
290 return error("CTransaction::ReadFromDisk() : second fseek failed");
291 *pfileRet = filein.release();
296 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
299 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
301 if (!ReadFromDisk(txindexRet.pos))
303 if (prevout.n >= vout.size())
311 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
314 return ReadFromDisk(txdb, prevout, txindex);
317 bool CTransaction::ReadFromDisk(COutPoint prevout)
321 return ReadFromDisk(txdb, prevout, txindex);
324 bool CTransaction::IsStandard(string& strReason) const
326 if (nVersion > CTransaction::CURRENT_VERSION)
328 strReason = "version";
332 unsigned int nDataOut = 0;
333 txnouttype whichType;
334 for(const CTxIn& txin : vin)
336 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
337 // keys. (remember the 520 byte limit on redeemScript size) That works
338 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
339 // bytes of scriptSig, which we round off to 1650 bytes for some minor
340 // future-proofing. That's also enough to spend a 20-of-20
341 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
342 // considered standard)
343 if (txin.scriptSig.size() > 1650)
345 strReason = "scriptsig-size";
348 if (!txin.scriptSig.IsPushOnly())
350 strReason = "scriptsig-not-pushonly";
353 if (!txin.scriptSig.HasCanonicalPushes()) {
354 strReason = "txin-scriptsig-not-canonicalpushes";
358 for(const CTxOut& txout : vout) {
359 if (!::IsStandard(txout.scriptPubKey, whichType)) {
360 strReason = "scriptpubkey";
363 if (whichType == TX_NULL_DATA)
366 if (txout.nValue == 0) {
367 strReason = "txout-value=0";
370 if (!txout.scriptPubKey.HasCanonicalPushes()) {
371 strReason = "txout-scriptsig-not-canonicalpushes";
377 // only one OP_RETURN txout is permitted
379 strReason = "multi-op-return";
387 // Check transaction inputs, and make sure any
388 // pay-to-script-hash transactions are evaluating IsStandard scripts
390 // Why bother? To avoid denial-of-service attacks; an attacker
391 // can submit a standard HASH... OP_EQUAL transaction,
392 // which will get accepted into blocks. The redemption
393 // script can be anything; an attacker could use a very
394 // expensive-to-check-upon-redemption script like:
395 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
397 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
400 return true; // Coinbases don't use vin normally
402 for (uint32_t i = 0; i < vin.size(); i++)
404 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
406 vector<vector<unsigned char> > vSolutions;
407 txnouttype whichType;
408 // get the scriptPubKey corresponding to this input:
409 const CScript& prevScript = prev.scriptPubKey;
410 if (!Solver(prevScript, whichType, vSolutions))
412 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
413 if (nArgsExpected < 0)
416 // Transactions with extra stuff in their scriptSigs are
417 // non-standard. Note that this EvalScript() call will
418 // be quick, because if there are any operations
419 // beside "push data" in the scriptSig the
420 // IsStandard() call returns false
421 vector<vector<unsigned char> > stack;
422 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
425 if (whichType == TX_SCRIPTHASH)
429 CScript subscript(stack.back().begin(), stack.back().end());
430 vector<vector<unsigned char> > vSolutions2;
431 txnouttype whichType2;
432 if (!Solver(subscript, whichType2, vSolutions2))
434 if (whichType2 == TX_SCRIPTHASH)
438 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
441 nArgsExpected += tmpExpected;
444 if (stack.size() != (unsigned int)nArgsExpected)
451 unsigned int CTransaction::GetLegacySigOpCount() const
453 unsigned int nSigOps = 0;
456 // Coinbase scriptsigs are never executed, so there is
457 // no sense in calculation of sigops.
458 for(const CTxIn& txin : vin)
460 nSigOps += txin.scriptSig.GetSigOpCount(false);
463 for(const CTxOut& txout : vout)
465 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
470 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
483 // Load the block this tx is in
485 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
487 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
492 // Update the tx's hashBlock
493 hashBlock = pblock->GetHash();
495 // Locate the transaction
496 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
497 if (pblock->vtx[nIndex] == *(CTransaction*)this)
499 if (nIndex == (int)pblock->vtx.size())
501 vMerkleBranch.clear();
503 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
507 // Fill in merkle branch
508 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
511 // Is the tx in a block that's in the main chain
512 auto mi = mapBlockIndex.find(hashBlock);
513 if (mi == mapBlockIndex.end())
515 const CBlockIndex* pindex = (*mi).second;
516 if (!pindex || !pindex->IsInMainChain())
519 return pindexBest->nHeight - pindex->nHeight + 1;
522 bool CTransaction::CheckTransaction() const
524 // Basic checks that don't depend on any context
526 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
528 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
530 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
531 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
533 // Check for negative or overflow output values
534 CBigNum nValueOut = 0;
535 for (uint32_t i = 0; i < vout.size(); i++)
537 const auto& txout = vout[i];
538 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
539 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
540 if (!MoneyRange(txout.nValue))
541 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is out of range"));
542 nValueOut += txout.nValue;
543 if (!MoneyRange(nValueOut))
544 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
547 // Check for duplicate inputs
548 set<COutPoint> vInOutPoints;
549 for(const CTxIn& txin : vin)
551 if (vInOutPoints.count(txin.prevout))
553 vInOutPoints.insert(txin.prevout);
558 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
559 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
563 for(const CTxIn& txin : vin)
564 if (txin.prevout.IsNull())
565 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
571 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
573 int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
577 // Enforce 0.01 as minimum fee for coinstake
579 nMinRelayTxFee = CENT;
582 // Base fee is either nMinTxFee or nMinRelayTxFee
583 auto nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
585 unsigned int nNewBlockSize = nBlockSize + nBytes;
586 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
592 // Transactions under 1K are free
598 // Free transaction area
599 if (nNewBlockSize < 27000)
604 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
605 // each non empty output which is less than 0.01
607 // It's safe to ignore empty outputs here, because these inputs are allowed
608 // only for coinbase and coinstake transactions.
609 for(const CTxOut& txout : vout)
610 if (txout.nValue < CENT && !txout.IsEmpty())
613 // Raise the price as the block approaches full
614 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
616 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
618 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
621 if (!MoneyRange(nMinFee))
627 string CTransaction::ToStringShort() const
630 str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
634 string CTransaction::ToString() const
637 str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
638 str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%" PRIszu ", vout.size=%" PRIszu ", nLockTime=%d)\n",
639 GetHash().ToString().substr(0,10).c_str(),
645 for (unsigned int i = 0; i < vin.size(); i++)
646 str += " " + vin[i].ToString() + "\n";
647 for (unsigned int i = 0; i < vout.size(); i++)
648 str += " " + vout[i].ToString() + "\n";
652 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
653 bool* pfMissingInputs)
656 *pfMissingInputs = false;
658 // Time (prevent mempool memory exhaustion attack)
659 if (tx.nTime > FutureDrift(GetAdjustedTime()))
660 return tx.DoS(10, error("CTxMemPool::accept() : transaction timestamp is too far in the future"));
662 if (!tx.CheckTransaction())
663 return error("CTxMemPool::accept() : CheckTransaction failed");
665 // Coinbase is only valid in a block, not as a loose transaction
667 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
669 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
670 if (tx.IsCoinStake())
671 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
673 // To help v0.1.5 clients who would see it as a negative number
674 if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
675 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
677 // Rather not work on nonstandard transactions (unless -testnet)
679 if (!fTestNet && !tx.IsStandard(strNonStd))
680 return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
682 // Do we already have it?
683 auto hash = tx.GetHash();
686 if (mapTx.count(hash))
690 if (txdb.ContainsTx(hash))
693 // Check for conflicts with in-memory transactions
694 for (unsigned int i = 0; i < tx.vin.size(); i++)
696 auto outpoint = tx.vin[i].prevout;
697 if (mapNextTx.count(outpoint))
699 // Replacement feature isn't supported by Novacoin.
707 map<uint256, CTxIndex> mapUnused;
708 bool fInvalid = false;
709 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
712 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
714 *pfMissingInputs = true;
718 // Check for non-standard pay-to-script-hash in inputs
719 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
720 return error("CTxMemPool::accept() : nonstandard transaction input");
722 // Note: if you modify this code to accept non-standard transactions, then
723 // you should add code here to check that the transaction does a
724 // reasonable number of ECDSA signature verifications.
726 auto nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
727 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
729 // Don't accept it if it can't get into a block
730 auto txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
731 if (nFees < txMinFee)
732 return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
733 hash.ToString().c_str(),
736 // Continuously rate-limit free transactions
737 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
738 // be annoying or make others' transactions take longer to confirm.
739 if (nFees < MIN_RELAY_TX_FEE)
741 static CCriticalSection cs;
742 static double dFreeCount;
743 static int64_t nLastTime;
744 auto nNow = GetTime();
748 // Use an exponentially decaying ~10-minute window:
749 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
751 // -limitfreerelay unit is thousand-bytes-per-minute
752 // At default rate it would take over a month to fill 1GB
753 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
754 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
756 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
761 // Check against previous transactions
762 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
763 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, STRICT_FLAGS))
765 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
769 // Store transaction in memory
772 addUnchecked(hash, tx);
775 printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
776 hash.ToString().substr(0,10).c_str(),
781 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
783 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
786 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
788 // Add to memory pool without checking anything. Don't call this directly,
789 // call CTxMemPool::accept to properly check the transaction first.
792 for (unsigned int i = 0; i < tx.vin.size(); i++)
793 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
794 nTransactionsUpdated++;
800 bool CTxMemPool::remove(CTransaction &tx)
802 // Remove transaction from memory pool
805 auto hash = tx.GetHash();
806 if (mapTx.count(hash))
808 for(const CTxIn& txin : tx.vin)
809 mapNextTx.erase(txin.prevout);
811 nTransactionsUpdated++;
817 void CTxMemPool::clear()
822 ++nTransactionsUpdated;
825 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
830 vtxid.reserve(mapTx.size());
831 for (auto mi = mapTx.begin(); mi != mapTx.end(); ++mi)
832 vtxid.push_back((*mi).first);
836 string CTxIn::ToString() const
840 str += CTxIn::prevout.ToString();
841 if (CTxIn::prevout.IsNull())
842 str += strprintf(", coinbase %s", HexStr(CTxIn::scriptSig).c_str());
844 str += strprintf(", scriptSig=%s", CTxIn::scriptSig.ToString().substr(0,24).c_str());
845 if (CTxIn::nSequence != numeric_limits<unsigned int>::max())
846 str += strprintf(", nSequence=%" PRIu32, CTxIn::nSequence);
852 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
854 if (hashBlock == 0 || nIndex == -1)
857 // Find the block it claims to be in
858 auto mi = mapBlockIndex.find(hashBlock);
859 if (mi == mapBlockIndex.end())
861 CBlockIndex* pindex = (*mi).second;
862 if (!pindex || !pindex->IsInMainChain())
865 // Make sure the merkle branch connects to this block
866 if (!fMerkleVerified)
868 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
870 fMerkleVerified = true;
874 return pindexBest->nHeight - pindex->nHeight + 1;
878 int CMerkleTx::GetBlocksToMaturity() const
880 if (!(IsCoinBase() || IsCoinStake()))
882 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
886 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
890 if (!IsInMainChain() && !ClientConnectInputs())
892 return CTransaction::AcceptToMemoryPool(txdb, false);
896 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
900 bool CMerkleTx::AcceptToMemoryPool()
903 return AcceptToMemoryPool(txdb);
908 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
913 // Add previous supporting transactions first
914 for(CMerkleTx& tx : vtxPrev)
916 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
918 auto hash = tx.GetHash();
919 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
920 tx.AcceptToMemoryPool(txdb, fCheckInputs);
923 return AcceptToMemoryPool(txdb, fCheckInputs);
928 bool CWalletTx::AcceptWalletTransaction()
931 return AcceptWalletTransaction(txdb);
934 int CTxIndex::GetDepthInMainChain() const
938 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
940 // Find the block in the index
941 auto mi = mapBlockIndex.find(block.GetHash());
942 if (mi == mapBlockIndex.end())
944 auto pindex = (*mi).second;
945 if (!pindex || !pindex->IsInMainChain())
947 return 1 + nBestHeight - pindex->nHeight;
950 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
951 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
957 if (mempool.exists(hash))
959 tx = mempool.lookup(hash);
965 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
968 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
969 hashBlock = block.GetHash();
977 // Closure representing one script verification
978 // Note that this stores references to the spending transaction
982 CScript scriptPubKey;
983 const CTransaction *ptxTo = nullptr;
985 unsigned int nFlags = 0;
990 CScriptCheck(const CTransaction& txFromIn, const CTransaction& txToIn, uint32_t nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
991 scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
992 ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
994 bool operator()() const;
996 void swap(CScriptCheck &check) {
997 scriptPubKey.swap(check.scriptPubKey);
998 std::swap(ptxTo, check.ptxTo);
999 std::swap(nIn, check.nIn);
1000 std::swap(nFlags, check.nFlags);
1001 std::swap(nHashType, check.nHashType);
1008 //////////////////////////////////////////////////////////////////////////////
1010 // CBlock and CBlockIndex
1013 static CBlockIndex* pblockindexFBBHLast;
1014 CBlockIndex* FindBlockByHeight(int nHeight)
1016 CBlockIndex *pblockindex;
1017 if (nHeight < nBestHeight / 2)
1018 pblockindex = pindexGenesisBlock;
1020 pblockindex = pindexBest;
1021 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
1022 pblockindex = pblockindexFBBHLast;
1023 while (pblockindex->nHeight > nHeight)
1024 pblockindex = pblockindex->pprev;
1025 while (pblockindex->nHeight < nHeight)
1026 pblockindex = pblockindex->pnext;
1027 pblockindexFBBHLast = pblockindex;
1031 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
1033 if (!fReadTransactions)
1035 *this = pindex->GetBlockHeader();
1038 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
1040 if (GetHash() != pindex->GetBlockHash())
1041 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1045 uint256 static GetOrphanRoot(const CBlock* pblock)
1047 // Work back to the first block in the orphan chain
1048 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1049 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1050 return pblock->GetHash();
1053 // ppcoin: find block wanted by given orphan block
1054 uint256 WantedByOrphan(const CBlock* pblockOrphan)
1056 // Work back to the first block in the orphan chain
1057 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
1058 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
1059 return pblockOrphan->hashPrevBlock;
1062 // select stake target limit according to hard-coded conditions
1063 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1065 if(fTestNet) // separate proof of stake target limit for testnet
1066 return bnProofOfStakeLimit;
1067 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1068 return bnProofOfStakeLimit;
1069 if(nHeight + 1 > 15000) // 24 bits since block 15000
1070 return bnProofOfStakeLegacyLimit;
1071 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1072 return bnProofOfStakeHardLimit;
1074 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1077 // miner's coin base reward based on nBits
1078 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees)
1080 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1083 bnTarget.SetCompact(nBits);
1084 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1085 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1087 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1088 // A reasonably continuous curve is used to avoid shock to market
1089 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1091 // Human readable form:
1093 // nSubsidy = 100 / (diff ^ 1/6)
1095 // Please note that we're using bisection to find an approximate solutuion
1096 CBigNum bnLowerBound = CENT;
1097 CBigNum bnUpperBound = bnSubsidyLimit;
1098 while (bnLowerBound + CENT <= bnUpperBound)
1100 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1101 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1102 bnUpperBound = bnMidValue;
1104 bnLowerBound = bnMidValue;
1107 int64_t nSubsidy = bnUpperBound.getuint64();
1109 nSubsidy = (nSubsidy / CENT) * CENT;
1110 if (fDebug && GetBoolArg("-printcreation"))
1111 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1113 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1116 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1117 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1119 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1121 // Stage 2 of emission process is mostly PoS-based.
1123 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1125 bnTarget.SetCompact(nBits);
1126 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1127 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1129 // A reasonably continuous curve is used to avoid shock to market
1131 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1132 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1133 bnMidPart, bnRewardPart;
1135 while (bnLowerBound + CENT <= bnUpperBound)
1137 auto bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1140 // Reward for coin-year is cut in half every 8x multiply of PoS difficulty
1142 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1144 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1147 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1148 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1150 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1151 bnUpperBound = bnMidValue;
1153 bnLowerBound = bnMidValue;
1156 nRewardCoinYear = bnUpperBound.getuint64();
1157 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1160 return nRewardCoinYear;
1162 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1164 // Set reasonable reward limit for large inputs
1166 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1168 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1169 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1171 nSubsidy = min(nSubsidy, nSubsidyLimit);
1173 if (fDebug && GetBoolArg("-printcreation"))
1174 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1179 static const int64_t nTargetTimespan = 7 * nOneDay; // one week
1181 // get proof of work blocks max spacing according to hard-coded conditions
1182 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1184 if(nTime > TARGETS_SWITCH_TIME)
1185 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1188 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1190 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1194 // maximum nBits value could possible be required nTime after
1196 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1199 bnResult.SetCompact(nBase);
1201 while (nTime > 0 && bnResult < bnTargetLimit)
1203 // Maximum 200% adjustment per day...
1207 if (bnResult > bnTargetLimit)
1208 bnResult = bnTargetLimit;
1209 return bnResult.GetCompact();
1213 // minimum amount of work that could possibly be required nTime after
1214 // minimum proof-of-work required was nBase
1216 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1218 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1222 // minimum amount of stake that could possibly be required nTime after
1223 // minimum proof-of-stake required was nBase
1225 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1227 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1231 // ppcoin: find last block index up to pindex
1232 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1234 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1235 pindex = pindex->pprev;
1239 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1241 if (pindexLast == NULL)
1242 return bnProofOfWorkLimit.GetCompact(); // genesis block
1244 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1246 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1247 if (pindexPrev->pprev == NULL)
1248 return bnTargetLimit.GetCompact(); // first block
1249 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1250 if (pindexPrevPrev->pprev == NULL)
1251 return bnTargetLimit.GetCompact(); // second block
1253 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1255 // ppcoin: target change every block
1256 // ppcoin: retarget with exponential moving toward target spacing
1258 bnNew.SetCompact(pindexPrev->nBits);
1259 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1260 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1261 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1262 bnNew /= ((nInterval + 1) * nTargetSpacing);
1264 if (bnNew > bnTargetLimit)
1265 bnNew = bnTargetLimit;
1267 return bnNew.GetCompact();
1270 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1273 bnTarget.SetCompact(nBits);
1276 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1277 return error("CheckProofOfWork() : nBits below minimum work");
1279 // Check proof of work matches claimed amount
1280 if (hash > bnTarget.getuint256())
1281 return error("CheckProofOfWork() : hash doesn't match nBits");
1286 // Return maximum amount of blocks that other nodes claim to have
1287 int GetNumBlocksOfPeers()
1289 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1292 bool IsInitialBlockDownload()
1294 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1296 static int64_t nLastUpdate;
1297 static CBlockIndex* pindexLastBest;
1298 auto nCurrentTime = GetTime();
1299 if (pindexBest != pindexLastBest)
1301 pindexLastBest = pindexBest;
1302 nLastUpdate = nCurrentTime;
1304 return (nCurrentTime - nLastUpdate < 10 &&
1305 pindexBest->GetBlockTime() < nCurrentTime - nOneDay);
1308 void static InvalidChainFound(CBlockIndex* pindexNew)
1310 if (pindexNew->nChainTrust > nBestInvalidTrust)
1312 nBestInvalidTrust = pindexNew->nChainTrust;
1313 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1314 uiInterface.NotifyBlocksChanged();
1317 auto nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1318 auto nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1320 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1321 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1322 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1323 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1324 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1325 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1326 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1327 nBestBlockTrust.Get64(),
1328 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1331 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1333 nTime = max(GetBlockTime(), GetAdjustedTime());
1336 unsigned int CBlock::GetStakeEntropyBit(unsigned int nHeight) const
1338 // Protocol switch to support p2pool at novacoin block #9689
1339 if (nHeight >= 9689 || fTestNet)
1341 // Take last bit of block hash as entropy bit
1342 auto nEntropyBit = (GetHash().Get32()) & (uint32_t)1;
1343 if (fDebug && GetBoolArg("-printstakemodifier"))
1344 printf("GetStakeEntropyBit: nTime=%" PRIu32 " hashBlock=%s nEntropyBit=%" PRIu32 "\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
1348 // Before novacoin block #9689 - get from pregenerated table
1349 int nBitNum = nHeight & 0xFF;
1350 int nItemNum = nHeight / 0xFF;
1352 auto nEntropyBit = ((entropyStore[nItemNum] & (uint256(1) << nBitNum)) >> nBitNum).Get32();
1353 if (fDebug && GetBoolArg("-printstakemodifier"))
1354 printf("GetStakeEntropyBit: from pregenerated table, nHeight=%" PRIu32 " nEntropyBit=%" PRIu32 "\n", nHeight, nEntropyBit);
1358 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1360 // Relinquish previous transactions' spent pointers
1363 for(const CTxIn& txin : vin)
1365 auto prevout = txin.prevout;
1367 // Get prev txindex from disk
1369 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1370 return error("DisconnectInputs() : ReadTxIndex failed");
1372 if (prevout.n >= txindex.vSpent.size())
1373 return error("DisconnectInputs() : prevout.n out of range");
1375 // Mark outpoint as not spent
1376 txindex.vSpent[prevout.n].SetNull();
1379 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1380 return error("DisconnectInputs() : UpdateTxIndex failed");
1384 // Remove transaction from index
1385 // This can fail if a duplicate of this transaction was in a chain that got
1386 // reorganized away. This is only possible if this transaction was completely
1387 // spent, so erasing it would be a no-op anyway.
1388 txdb.EraseTxIndex(*this);
1394 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1395 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1397 // FetchInputs can return false either because we just haven't seen some inputs
1398 // (in which case the transaction should be stored as an orphan)
1399 // or because the transaction is malformed (in which case the transaction should
1400 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1404 return true; // Coinbase transactions have no inputs to fetch.
1406 for (unsigned int i = 0; i < vin.size(); i++)
1408 auto prevout = vin[i].prevout;
1409 if (inputsRet.count(prevout.hash))
1410 continue; // Got it already
1413 CTxIndex& txindex = inputsRet[prevout.hash].first;
1415 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1417 // Get txindex from current proposed changes
1418 txindex = mapTestPool.find(prevout.hash)->second;
1422 // Read txindex from txdb
1423 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1425 if (!fFound && (fBlock || fMiner))
1426 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());
1429 CTransaction& txPrev = inputsRet[prevout.hash].second;
1430 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1432 // Get prev tx from single transactions in memory
1435 if (!mempool.exists(prevout.hash))
1436 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());
1437 txPrev = mempool.lookup(prevout.hash);
1440 txindex.vSpent.resize(txPrev.vout.size());
1444 // Get prev tx from disk
1445 if (!txPrev.ReadFromDisk(txindex.pos))
1446 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1450 // Make sure all prevout.n indexes are valid:
1451 for (unsigned int i = 0; i < vin.size(); i++)
1453 const COutPoint prevout = vin[i].prevout;
1454 assert(inputsRet.count(prevout.hash) != 0);
1455 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1456 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1457 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1459 // Revisit this if/when transaction replacement is implemented and allows
1462 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()));
1469 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1471 auto mi = inputs.find(input.prevout.hash);
1472 if (mi == inputs.end())
1473 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1475 const auto& txPrev = (mi->second).second;
1476 if (input.prevout.n >= txPrev.vout.size())
1477 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1479 return txPrev.vout[input.prevout.n];
1482 int64_t CTransaction::GetValueOut() const
1484 CBigNum nValueOut = 0;
1485 for(const auto& txout : vout)
1487 nValueOut += txout.nValue;
1488 if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
1489 throw runtime_error("CTransaction::GetValueOut() : value out of range");
1491 return nValueOut.getint64();
1494 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1499 CBigNum nResult = 0;
1500 for (uint32_t i = 0; i < vin.size(); i++)
1502 const auto& txOut = GetOutputFor(vin[i], inputs);
1503 nResult += txOut.nValue;
1504 if (!MoneyRange(txOut.nValue) || !MoneyRange(nResult))
1505 throw runtime_error("CTransaction::GetValueIn() : value out of range");
1507 return nResult.getint64();
1511 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1516 unsigned int nSigOps = 0;
1517 for (unsigned int i = 0; i < vin.size(); i++)
1519 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1520 if (prevout.scriptPubKey.IsPayToScriptHash())
1521 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1526 bool CScriptCheck::operator()() const {
1527 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1528 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1529 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1533 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType)
1535 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1538 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1539 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1541 // Take over previous transactions' spent pointers
1542 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1543 // fMiner is true when called from the internal bitcoin miner
1544 // ... both are false when called from CTransaction::AcceptToMemoryPool
1548 int64_t nValueIn = 0;
1550 CBigNum bnValueIn = 0;
1551 for (uint32_t i = 0; i < vin.size(); i++)
1553 auto prevout = vin[i].prevout;
1554 assert(inputs.count(prevout.hash) > 0);
1555 CTxIndex& txindex = inputs[prevout.hash].first;
1556 CTransaction& txPrev = inputs[prevout.hash].second;
1558 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1559 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()));
1561 // If prev is coinbase or coinstake, check that it's matured
1562 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1563 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1564 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1565 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1567 // ppcoin: check transaction timestamp
1568 if (txPrev.nTime > nTime)
1569 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1571 // Check for negative or overflow input values
1572 bnValueIn += txPrev.vout[prevout.n].nValue;
1573 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(bnValueIn))
1574 return DoS(100, error("ConnectInputs() : txin values out of range"));
1576 nValueIn = bnValueIn.getint64();
1580 pvChecks->reserve(vin.size());
1582 // The first loop above does all the inexpensive checks.
1583 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1584 // Helps prevent CPU exhaustion attacks.
1585 for (unsigned int i = 0; i < vin.size(); i++)
1587 auto prevout = vin[i].prevout;
1588 assert(inputs.count(prevout.hash) > 0);
1589 CTxIndex& txindex = inputs[prevout.hash].first;
1590 CTransaction& txPrev = inputs[prevout.hash].second;
1592 // Check for conflicts (double-spend)
1593 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1594 // for an attacker to attempt to split the network.
1595 if (!txindex.vSpent[prevout.n].IsNull())
1596 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());
1598 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1599 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1600 // still computed and checked, and any change will be caught at the next checkpoint.
1604 CScriptCheck check(txPrev, *this, i, flags, 0);
1607 pvChecks->push_back(CScriptCheck());
1608 check.swap(pvChecks->back());
1612 if (flags & STRICT_FLAGS)
1614 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1615 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1617 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1619 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1623 // Mark outpoints as spent
1624 txindex.vSpent[prevout.n] = posThisTx;
1627 if (fBlock || fMiner)
1629 mapTestPool[prevout.hash] = txindex;
1635 if (nTime > Checkpoints::GetLastCheckpointTime())
1637 unsigned int nTxSize = GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
1639 // coin stake tx earns reward instead of paying fee
1641 if (!GetCoinAge(txdb, nCoinAge))
1642 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1644 auto nReward = GetValueOut() - nValueIn;
1645 auto nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1647 if (nReward > nCalculatedReward)
1648 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1653 if (nValueIn < GetValueOut())
1654 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1656 // Tally transaction fees
1657 auto nTxFee = nValueIn - GetValueOut();
1658 if (!MoneyRange(nTxFee))
1659 return DoS(100, error("ConnectInputs() : nFees out of range"));
1667 bool CTransaction::ClientConnectInputs()
1672 // Take over previous transactions' spent pointers
1675 CBigNum bnValueIn = 0;
1676 for (uint32_t i = 0; i < vin.size(); i++)
1678 // Get prev tx from single transactions in memory
1679 auto prevout = vin[i].prevout;
1680 if (!mempool.exists(prevout.hash))
1682 CTransaction& txPrev = mempool.lookup(prevout.hash);
1684 if (prevout.n >= txPrev.vout.size())
1688 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1689 return error("ClientConnectInputs() : VerifySignature failed");
1691 ///// this is redundant with the mempool.mapNextTx stuff,
1692 ///// not sure which I want to get rid of
1693 ///// this has to go away now that posNext is gone
1694 // // Check for conflicts
1695 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1696 // return error("ConnectInputs() : prev tx already used");
1698 // // Flag outpoints as used
1699 // txPrev.vout[prevout.n].posNext = posThisTx;
1701 bnValueIn += txPrev.vout[prevout.n].nValue;
1703 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(bnValueIn))
1704 return error("ClientConnectInputs() : txin values out of range");
1706 if (GetValueOut() > bnValueIn.getint64())
1713 int64_t CBlock::GetMaxTransactionTime() const
1715 int64_t maxTransactionTime = 0;
1716 for(const auto& tx : vtx)
1717 maxTransactionTime = max(maxTransactionTime, (int64_t)tx.nTime);
1718 return maxTransactionTime;
1721 uint256 CBlock::BuildMerkleTree() const
1723 vMerkleTree.clear();
1724 for(const auto& tx : vtx)
1725 vMerkleTree.push_back(tx.GetHash());
1727 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1729 for (int i = 0; i < nSize; i += 2)
1731 int i2 = min(i+1, nSize-1);
1732 vMerkleTree.push_back(Hash(vMerkleTree[j+i].begin(), vMerkleTree[j+i].end(),
1733 vMerkleTree[j+i2].begin(), vMerkleTree[j+i2].end()));
1737 return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1740 vector<uint256> CBlock::GetMerkleBranch(int nIndex) const
1742 if (vMerkleTree.empty())
1744 vector<uint256> vMerkleBranch;
1746 for (int nSize = (int)vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1748 int i = min(nIndex^1, nSize-1);
1749 vMerkleBranch.push_back(vMerkleTree[j+i]);
1753 return vMerkleBranch;
1756 uint256 CBlock::CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1760 for(const uint256& otherside : vMerkleBranch)
1763 hash = Hash(otherside.begin(), otherside.end(), hash.begin(), hash.end());
1765 hash = Hash(hash.begin(), hash.end(), otherside.begin(), otherside.end());
1771 bool CBlock::WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1773 // Open history file to append
1774 auto fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
1776 return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1778 // Write index header
1779 unsigned int nSize = fileout.GetSerializeSize(*this);
1780 fileout << nNetworkID << nSize;
1783 long fileOutPos = ftell(fileout);
1785 return error("CBlock::WriteToDisk() : ftell failed");
1786 nBlockPosRet = fileOutPos;
1789 // Flush stdio buffers and commit to disk before returning
1791 if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1792 FileCommit(fileout);
1797 bool CBlock::ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions)
1801 // Open history file to read
1802 auto filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
1804 return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1805 if (!fReadTransactions)
1806 filein.nType |= SER_BLOCKHEADERONLY;
1812 catch (const std::exception&) {
1813 return error("%s() : deserialize or I/O error", BOOST_CURRENT_FUNCTION);
1817 if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
1818 return error("CBlock::ReadFromDisk() : errors in block header");
1823 void CBlock::print() const
1825 printf("CBlock(hash=%s, ver=%" PRId32 ", hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%" PRIu32 ", nBits=%08x, nNonce=%" PRIu32 ", vtx=%" PRIszu ", vchBlockSig=%s)\n",
1826 GetHash().ToString().c_str(),
1828 hashPrevBlock.ToString().c_str(),
1829 hashMerkleRoot.ToString().c_str(),
1830 nTime, nBits, nNonce,
1832 HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
1833 for (unsigned int i = 0; i < vtx.size(); i++)
1838 printf(" vMerkleTree: ");
1839 for (unsigned int i = 0; i < vMerkleTree.size(); i++)
1840 printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1844 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1846 // Disconnect in reverse order
1847 for (int i = vtx.size()-1; i >= 0; i--)
1848 if (!vtx[i].DisconnectInputs(txdb))
1851 // Update block index on disk without changing it in memory.
1852 // The memory index structure will be changed after the db commits.
1855 CDiskBlockIndex blockindexPrev(pindex->pprev);
1856 blockindexPrev.hashNext = 0;
1857 if (!txdb.WriteBlockIndex(blockindexPrev))
1858 return error("DisconnectBlock() : WriteBlockIndex failed");
1861 // ppcoin: clean up wallet after disconnecting coinstake
1862 for(CTransaction& tx : vtx)
1863 SyncWithWallets(tx, this, false, false);
1868 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1870 void ThreadScriptCheck(void*) {
1871 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1872 RenameThread("novacoin-scriptch");
1873 scriptcheckqueue.Thread();
1874 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1877 void ThreadScriptCheckQuit() {
1878 scriptcheckqueue.Quit();
1881 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1883 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1884 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1887 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1888 // unless those are already completely spent.
1889 // If such overwrites are allowed, coinbases and transactions depending upon those
1890 // can be duplicated to remove the ability to spend the first instance -- even after
1891 // being sent to another address.
1892 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1893 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1894 // already refuses previously-known transaction ids entirely.
1895 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1896 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1897 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1898 // initial block download.
1899 bool fEnforceBIP30 = true; // Always active in NovaCoin
1900 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1902 //// issue here: it doesn't know the version
1903 unsigned int nTxPos;
1905 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1906 // 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
1909 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1911 map<uint256, CTxIndex> mapQueuedChanges;
1912 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1915 int64_t nValueIn = 0;
1916 int64_t nValueOut = 0;
1917 unsigned int nSigOps = 0;
1920 auto hashTx = tx.GetHash();
1922 if (fEnforceBIP30) {
1923 CTxIndex txindexOld;
1924 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1925 for(CDiskTxPos &pos : txindexOld.vSpent)
1931 nSigOps += tx.GetLegacySigOpCount();
1932 if (nSigOps > MAX_BLOCK_SIGOPS)
1933 return DoS(100, error("ConnectBlock() : too many sigops"));
1935 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1937 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1939 MapPrevTx mapInputs;
1940 if (tx.IsCoinBase())
1941 nValueOut += tx.GetValueOut();
1945 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1948 // Add in sigops done by pay-to-script-hash inputs;
1949 // this is to prevent a "rogue miner" from creating
1950 // an incredibly-expensive-to-validate block.
1951 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1952 if (nSigOps > MAX_BLOCK_SIGOPS)
1953 return DoS(100, error("ConnectBlock() : too many sigops"));
1955 auto nTxValueIn = tx.GetValueIn(mapInputs);
1956 auto nTxValueOut = tx.GetValueOut();
1957 nValueIn += nTxValueIn;
1958 nValueOut += nTxValueOut;
1959 if (!tx.IsCoinStake())
1960 nFees += nTxValueIn - nTxValueOut;
1962 unsigned int nFlags = SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH;
1964 if (tx.nTime >= CHECKLOCKTIMEVERIFY_SWITCH_TIME) {
1965 nFlags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1966 // OP_CHECKSEQUENCEVERIFY is senseless without BIP68, so we're going disable it for now.
1967 // nFlags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1970 std::vector<CScriptCheck> vChecks;
1971 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, nFlags, nScriptCheckThreads ? &vChecks : NULL))
1973 control.Add(vChecks);
1976 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1979 if (!control.Wait())
1980 return DoS(100, false);
1982 if (IsProofOfWork())
1984 auto nBlockReward = GetProofOfWorkReward(nBits, nFees);
1986 // Check coinbase reward
1987 if (vtx[0].GetValueOut() > nBlockReward)
1988 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1989 vtx[0].GetValueOut(),
1993 // track money supply and mint amount info
1994 pindex->nMint = nValueOut - nValueIn + nFees;
1995 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1996 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1997 return error("Connect() : WriteBlockIndex for pindex failed");
1999 // fees are not collected by proof-of-stake miners
2000 // fees are destroyed to compensate the entire network
2001 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
2002 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
2007 // Write queued txindex changes
2008 for (auto mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
2010 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
2011 return error("ConnectBlock() : UpdateTxIndex failed");
2014 // Update block index on disk without changing it in memory.
2015 // The memory index structure will be changed after the db commits.
2018 CDiskBlockIndex blockindexPrev(pindex->pprev);
2019 blockindexPrev.hashNext = pindex->GetBlockHash();
2020 if (!txdb.WriteBlockIndex(blockindexPrev))
2021 return error("ConnectBlock() : WriteBlockIndex failed");
2024 // Watch for transactions paying to me
2025 for(CTransaction& tx : vtx)
2026 SyncWithWallets(tx, this, true);
2032 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
2034 printf("REORGANIZE\n");
2037 CBlockIndex* pfork = pindexBest;
2038 CBlockIndex* plonger = pindexNew;
2039 while (pfork != plonger)
2041 while (plonger->nHeight > pfork->nHeight)
2042 if ((plonger = plonger->pprev) == NULL)
2043 return error("Reorganize() : plonger->pprev is null");
2044 if (pfork == plonger)
2046 if ((pfork = pfork->pprev) == NULL)
2047 return error("Reorganize() : pfork->pprev is null");
2050 // List of what to disconnect
2051 vector<CBlockIndex*> vDisconnect;
2052 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
2053 vDisconnect.push_back(pindex);
2055 // List of what to connect
2056 vector<CBlockIndex*> vConnect;
2057 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
2058 vConnect.push_back(pindex);
2059 reverse(vConnect.begin(), vConnect.end());
2061 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());
2062 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());
2064 // Disconnect shorter branch
2065 vector<CTransaction> vResurrect;
2066 for(CBlockIndex* pindex : vDisconnect)
2069 if (!block.ReadFromDisk(pindex))
2070 return error("Reorganize() : ReadFromDisk for disconnect failed");
2071 if (!block.DisconnectBlock(txdb, pindex))
2072 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
2074 // Queue memory transactions to resurrect
2075 for(const CTransaction& tx : block.vtx)
2076 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
2077 vResurrect.push_back(tx);
2080 // Connect longer branch
2081 vector<CTransaction> vDelete;
2082 for (unsigned int i = 0; i < vConnect.size(); i++)
2084 CBlockIndex* pindex = vConnect[i];
2086 if (!block.ReadFromDisk(pindex))
2087 return error("Reorganize() : ReadFromDisk for connect failed");
2088 if (!block.ConnectBlock(txdb, pindex))
2091 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
2094 // Queue memory transactions to delete
2095 for(const CTransaction& tx : block.vtx)
2096 vDelete.push_back(tx);
2098 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
2099 return error("Reorganize() : WriteHashBestChain failed");
2101 // Make sure it's successfully written to disk before changing memory structure
2102 if (!txdb.TxnCommit())
2103 return error("Reorganize() : TxnCommit failed");
2105 // Disconnect shorter branch
2106 for(CBlockIndex* pindex : vDisconnect)
2108 pindex->pprev->pnext = NULL;
2110 // Connect longer branch
2111 for(CBlockIndex* pindex : vConnect)
2113 pindex->pprev->pnext = pindex;
2115 // Resurrect memory transactions that were in the disconnected branch
2116 for(CTransaction& tx : vResurrect)
2117 tx.AcceptToMemoryPool(txdb, false);
2119 // Delete redundant memory transactions that are in the connected branch
2120 for(CTransaction& tx : vDelete)
2123 printf("REORGANIZE: done\n");
2129 // Called from inside SetBestChain: attaches a block to the new best chain being built
2130 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
2132 auto hash = GetHash();
2134 // Adding to current best branch
2135 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
2138 InvalidChainFound(pindexNew);
2141 if (!txdb.TxnCommit())
2142 return error("SetBestChain() : TxnCommit failed");
2144 // Add to current best branch
2145 pindexNew->pprev->pnext = pindexNew;
2147 // Delete redundant memory transactions
2148 for(CTransaction& tx : vtx)
2154 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
2156 auto hash = GetHash();
2158 if (!txdb.TxnBegin())
2159 return error("SetBestChain() : TxnBegin failed");
2161 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2163 txdb.WriteHashBestChain(hash);
2164 if (!txdb.TxnCommit())
2165 return error("SetBestChain() : TxnCommit failed");
2166 pindexGenesisBlock = pindexNew;
2168 else if (hashPrevBlock == hashBestChain)
2170 if (!SetBestChainInner(txdb, pindexNew))
2171 return error("SetBestChain() : SetBestChainInner failed");
2175 // the first block in the new chain that will cause it to become the new best chain
2176 CBlockIndex *pindexIntermediate = pindexNew;
2178 // list of blocks that need to be connected afterwards
2179 std::vector<CBlockIndex*> vpindexSecondary;
2181 // Reorganize is costly in terms of db load, as it works in a single db transaction.
2182 // Try to limit how much needs to be done inside
2183 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
2185 vpindexSecondary.push_back(pindexIntermediate);
2186 pindexIntermediate = pindexIntermediate->pprev;
2189 if (!vpindexSecondary.empty())
2190 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
2192 // Switch to new best branch
2193 if (!Reorganize(txdb, pindexIntermediate))
2196 InvalidChainFound(pindexNew);
2197 return error("SetBestChain() : Reorganize failed");
2200 // Connect further blocks
2201 for (std::vector<CBlockIndex*>::reverse_iterator rit = vpindexSecondary.rbegin(); rit != vpindexSecondary.rend(); ++rit)
2204 if (!block.ReadFromDisk(*rit))
2206 printf("SetBestChain() : ReadFromDisk failed\n");
2209 if (!txdb.TxnBegin()) {
2210 printf("SetBestChain() : TxnBegin 2 failed\n");
2213 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
2214 if (!block.SetBestChainInner(txdb, *rit))
2219 // Update best block in wallet (so we can detect restored wallets)
2220 bool fIsInitialDownload = IsInitialBlockDownload();
2221 if (!fIsInitialDownload)
2223 const CBlockLocator locator(pindexNew);
2224 ::SetBestChain(locator);
2228 hashBestChain = hash;
2229 pindexBest = pindexNew;
2230 pblockindexFBBHLast = NULL;
2231 nBestHeight = pindexBest->nHeight;
2232 nBestChainTrust = pindexNew->nChainTrust;
2233 nTimeBestReceived = GetTime();
2234 nTransactionsUpdated++;
2236 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2238 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
2239 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2240 CBigNum(nBestChainTrust).ToString().c_str(),
2241 nBestBlockTrust.Get64(),
2242 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2244 // Check the version of the last 100 blocks to see if we need to upgrade:
2245 if (!fIsInitialDownload)
2248 const CBlockIndex* pindex = pindexBest;
2249 for (int i = 0; i < 100 && pindex != NULL; i++)
2251 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2253 pindex = pindex->pprev;
2256 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2257 if (nUpgraded > 100/2)
2258 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2259 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2262 auto strCmd = GetArg("-blocknotify", "");
2264 if (!fIsInitialDownload && !strCmd.empty())
2266 boost::thread t(runCommand, regex_replace(strCmd, static_cast<regex>("%s"), hashBestChain.GetHex()));
2271 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2272 // Only those coins meeting minimum age requirement counts. As those
2273 // transactions not in main chain are not currently indexed so we
2274 // might not find out about their coin age. Older transactions are
2275 // guaranteed to be in main chain by sync-checkpoint. This rule is
2276 // introduced to help nodes establish a consistent view of the coin
2277 // age (trust score) of competing branches.
2278 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2280 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2286 for(const CTxIn& txin : vin)
2288 // First try finding the previous transaction in database
2289 CTransaction txPrev;
2291 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2292 continue; // previous transaction not in main chain
2293 if (nTime < txPrev.nTime)
2294 return false; // Transaction timestamp violation
2296 // Read block header
2298 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2299 return false; // unable to read block of previous transaction
2300 if (block.GetBlockTime() + nStakeMinAge > nTime)
2301 continue; // only count coins meeting min age requirement
2303 auto nValueIn = txPrev.vout[txin.prevout.n].nValue;
2304 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2306 if (fDebug && GetBoolArg("-printcoinage"))
2307 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2310 auto bnCoinDay = bnCentSecond * CENT / COIN / nOneDay;
2311 if (fDebug && GetBoolArg("-printcoinage"))
2312 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2313 nCoinAge = bnCoinDay.getuint64();
2317 // ppcoin: total coin age spent in block, in the unit of coin-days.
2318 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2323 for(const CTransaction& tx : vtx)
2325 uint64_t nTxCoinAge;
2326 if (tx.GetCoinAge(txdb, nTxCoinAge))
2327 nCoinAge += nTxCoinAge;
2332 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2334 if (fDebug && GetBoolArg("-printcoinage"))
2335 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2339 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2341 // Check for duplicate
2342 auto hash = GetHash();
2343 if (mapBlockIndex.count(hash))
2344 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2346 // Construct new block index object
2347 CBlockIndex* pindexNew = new(nothrow) CBlockIndex(nFile, nBlockPos, *this);
2349 return error("AddToBlockIndex() : new CBlockIndex failed");
2350 pindexNew->phashBlock = &hash;
2351 auto miPrev = mapBlockIndex.find(hashPrevBlock);
2352 if (miPrev != mapBlockIndex.end())
2354 pindexNew->pprev = (*miPrev).second;
2355 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2358 // ppcoin: compute chain trust score
2359 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2361 // ppcoin: compute stake entropy bit for stake modifier
2362 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2363 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2365 // ppcoin: record proof-of-stake hash value
2366 if (pindexNew->IsProofOfStake())
2368 if (!mapProofOfStake.count(hash))
2369 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2370 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2373 // ppcoin: compute stake modifier
2374 uint64_t nStakeModifier = 0;
2375 bool fGeneratedStakeModifier = false;
2376 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2377 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2378 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2379 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2380 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2381 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2383 // Add to mapBlockIndex
2384 auto mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2385 if (pindexNew->IsProofOfStake())
2386 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2387 pindexNew->phashBlock = &((*mi).first);
2389 // Write to disk block index
2391 if (!txdb.TxnBegin())
2393 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2394 if (!txdb.TxnCommit())
2398 if (pindexNew->nChainTrust > nBestChainTrust)
2399 if (!SetBestChain(txdb, pindexNew))
2402 if (pindexNew == pindexBest)
2404 // Notify UI to display prev block's coinbase if it was ours
2405 static uint256 hashPrevBestCoinBase;
2406 UpdatedTransaction(hashPrevBestCoinBase);
2407 hashPrevBestCoinBase = vtx[0].GetHash();
2410 static int8_t counter = 0;
2411 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2412 uiInterface.NotifyBlocksChanged();
2419 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2421 // These are checks that are independent of context
2422 // that can be verified before saving an orphan block.
2424 set<uint256> uniqueTx; // tx hashes
2425 unsigned int nSigOps = 0; // total sigops
2428 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2429 return DoS(100, error("CheckBlock() : size limits failed"));
2431 bool fProofOfStake = IsProofOfStake();
2433 // First transaction must be coinbase, the rest must not be
2434 if (!vtx[0].IsCoinBase())
2435 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2437 if (!vtx[0].CheckTransaction())
2438 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2440 uniqueTx.insert(vtx[0].GetHash());
2441 nSigOps += vtx[0].GetLegacySigOpCount();
2445 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2446 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2448 // nNonce must be zero for proof-of-stake blocks
2450 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2452 // Coinbase output should be empty if proof-of-stake block
2453 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2454 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2456 // Check coinstake timestamp
2457 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2458 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2460 // NovaCoin: check proof-of-stake block signature
2461 if (fCheckSig && !CheckBlockSignature())
2462 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2464 if (!vtx[1].CheckTransaction())
2465 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2467 uniqueTx.insert(vtx[1].GetHash());
2468 nSigOps += vtx[1].GetLegacySigOpCount();
2472 // Check proof of work matches claimed amount
2473 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2474 return DoS(50, error("CheckBlock() : proof of work failed"));
2477 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2478 return error("CheckBlock() : block timestamp too far in the future");
2480 // Check coinbase timestamp
2481 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2482 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2485 // Iterate all transactions starting from second for proof-of-stake block
2486 // or first for proof-of-work block
2487 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2489 const CTransaction& tx = vtx[i];
2491 // Reject coinbase transactions at non-zero index
2492 if (tx.IsCoinBase())
2493 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2495 // Reject coinstake transactions at index != 1
2496 if (tx.IsCoinStake())
2497 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2499 // Check transaction timestamp
2500 if (GetBlockTime() < (int64_t)tx.nTime)
2501 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2503 // Check transaction consistency
2504 if (!tx.CheckTransaction())
2505 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2507 // Add transaction hash into list of unique transaction IDs
2508 uniqueTx.insert(tx.GetHash());
2510 // Calculate sigops count
2511 nSigOps += tx.GetLegacySigOpCount();
2514 // Check for duplicate txids. This is caught by ConnectInputs(),
2515 // but catching it earlier avoids a potential DoS attack:
2516 if (uniqueTx.size() != vtx.size())
2517 return DoS(100, error("CheckBlock() : duplicate transaction"));
2519 // Reject block if validation would consume too much resources.
2520 if (nSigOps > MAX_BLOCK_SIGOPS)
2521 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2523 // Check merkle root
2524 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2525 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2530 bool CBlock::AcceptBlock()
2532 // Check for duplicate
2533 auto hash = GetHash();
2534 if (mapBlockIndex.count(hash))
2535 return error("AcceptBlock() : block already in mapBlockIndex");
2537 // Get prev block index
2538 auto mi = mapBlockIndex.find(hashPrevBlock);
2539 if (mi == mapBlockIndex.end())
2540 return DoS(10, error("AcceptBlock() : prev block not found"));
2541 CBlockIndex* pindexPrev = (*mi).second;
2542 int nHeight = pindexPrev->nHeight+1;
2544 // Check proof-of-work or proof-of-stake
2545 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2546 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2548 int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
2549 int nMaxOffset = 12 * nOneHour; // 12 hours
2550 if (fTestNet || pindexPrev->nTime < 1450569600)
2551 nMaxOffset = 7 * nOneWeek; // One week (permanently on testNet or until 20 Dec, 2015 on mainNet)
2553 // Check timestamp against prev
2554 if (GetBlockTime() <= nMedianTimePast || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2555 return error("AcceptBlock() : block's timestamp is too early");
2557 // Don't accept blocks with future timestamps
2558 if (pindexPrev->nHeight > 1 && nMedianTimePast + nMaxOffset < GetBlockTime())
2559 return error("AcceptBlock() : block's timestamp is too far in the future");
2561 // Check that all transactions are finalized
2562 for(const CTransaction& tx : vtx)
2563 if (!tx.IsFinal(nHeight, GetBlockTime()))
2564 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2566 // Check that the block chain matches the known block chain up to a checkpoint
2567 if (!Checkpoints::CheckHardened(nHeight, hash))
2568 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2570 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2572 // Check that the block satisfies synchronized checkpoint
2573 if (CheckpointsMode == Checkpoints::CP_STRICT && !cpSatisfies)
2574 return error("AcceptBlock() : rejected by synchronized checkpoint");
2576 if (CheckpointsMode == Checkpoints::CP_ADVISORY && !cpSatisfies)
2577 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2579 // Enforce rule that the coinbase starts with serialized block height
2580 auto expect = CScript() << nHeight;
2581 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2582 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2583 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2585 // Write block to history file
2586 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2587 return error("AcceptBlock() : out of disk space");
2588 unsigned int nFile = std::numeric_limits<unsigned int>::max();
2589 unsigned int nBlockPos = 0;
2590 if (!WriteToDisk(nFile, nBlockPos))
2591 return error("AcceptBlock() : WriteToDisk failed");
2592 if (!AddToBlockIndex(nFile, nBlockPos))
2593 return error("AcceptBlock() : AddToBlockIndex failed");
2595 // Relay inventory, but don't relay old inventory during initial block download
2596 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2597 if (hashBestChain == hash)
2600 for(CNode* pnode : vNodes)
2601 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2602 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2605 // ppcoin: check pending sync-checkpoint
2606 Checkpoints::AcceptPendingSyncCheckpoint();
2611 uint256 CBlockIndex::GetBlockTrust() const
2614 bnTarget.SetCompact(nBits);
2619 // Return 1 for the first 12 blocks
2620 if (pprev == NULL || pprev->nHeight < 12)
2623 const CBlockIndex* currentIndex = pprev;
2625 if(IsProofOfStake())
2627 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2629 // Return 1/3 of score if parent block is not the PoW block
2630 if (!pprev->IsProofOfWork())
2631 return (bnNewTrust / 3).getuint256();
2635 // Check last 12 blocks type
2636 while (pprev->nHeight - currentIndex->nHeight < 12)
2638 if (currentIndex->IsProofOfWork())
2640 currentIndex = currentIndex->pprev;
2643 // Return 1/3 of score if less than 3 PoW blocks found
2645 return (bnNewTrust / 3).getuint256();
2647 return bnNewTrust.getuint256();
2651 // Calculate work amount for block
2652 CBigNum bnPoWTrust = CBigNum(nPoWBase) / (bnTarget+1);
2654 // Set nPowTrust to 1 if PoW difficulty is too low
2658 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2660 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2661 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2662 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2666 // Check last 12 blocks type
2667 while (pprev->nHeight - currentIndex->nHeight < 12)
2669 if (currentIndex->IsProofOfStake())
2671 currentIndex = currentIndex->pprev;
2674 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2676 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2678 bnTarget.SetCompact(pprev->nBits);
2683 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2685 // Return nPoWTrust + full trust score for previous block nBits
2686 return (bnPoWTrust + bnNewTrust).getuint256();
2690 CBlock CBlockIndex::GetBlockHeader() const
2693 block.nVersion = nVersion;
2695 block.hashPrevBlock = pprev->GetBlockHash();
2696 block.hashMerkleRoot = hashMerkleRoot;
2697 block.nTime = nTime;
2698 block.nBits = nBits;
2699 block.nNonce = nNonce;
2703 enum { nMedianTimeSpan=11 };
2705 int64_t CBlockIndex::GetMedianTimePast() const
2707 int64_t pmedian[nMedianTimeSpan];
2708 int64_t* pbegin = &pmedian[nMedianTimeSpan];
2709 int64_t* pend = &pmedian[nMedianTimeSpan];
2710 const CBlockIndex* pindex = this;
2711 for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
2712 *(--pbegin) = pindex->GetBlockTime();
2714 return pbegin[(pend - pbegin)/2];
2717 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2719 unsigned int nFound = 0;
2720 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2722 if (pstart->nVersion >= minVersion)
2724 pstart = pstart->pprev;
2726 return (nFound >= nRequired);
2729 bool CBlockIndex::SetStakeEntropyBit(unsigned int nEntropyBit)
2731 if (nEntropyBit > 1)
2733 nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
2737 void CBlockIndex::SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier)
2739 nStakeModifier = nModifier;
2740 if (fGeneratedStakeModifier)
2741 nFlags |= BLOCK_STAKE_MODIFIER;
2744 string CBlockIndex::ToString() const
2746 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)",
2747 (const void*)pprev, (const void*)pnext, nFile, nBlockPos, nHeight,
2748 FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
2749 GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
2750 nStakeModifier, nStakeModifierChecksum,
2751 hashProofOfStake.ToString().c_str(),
2752 prevoutStake.ToString().c_str(), nStakeTime,
2753 hashMerkleRoot.ToString().c_str(),
2754 GetBlockHash().ToString().c_str());
2757 bool static ReserealizeBlockSignature(CBlock* pblock)
2759 if (pblock->IsProofOfWork())
2761 pblock->vchBlockSig.clear();
2765 return CPubKey::ReserealizeSignature(pblock->vchBlockSig);
2768 bool static IsCanonicalBlockSignature(CBlock* pblock)
2770 if (pblock->IsProofOfWork())
2771 return pblock->vchBlockSig.empty();
2773 return IsDERSignature(pblock->vchBlockSig);
2776 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2778 // Check for duplicate
2779 auto hash = pblock->GetHash();
2780 if (mapBlockIndex.count(hash))
2781 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2782 if (mapOrphanBlocks.count(hash))
2783 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2785 // Check that block isn't listed as unconditionally banned.
2786 if (!Checkpoints::CheckBanned(hash)) {
2788 pfrom->Misbehaving(100);
2789 return error("ProcessBlock() : block %s is rejected by hard-coded banlist", hash.GetHex().substr(0,20).c_str());
2792 // Check proof-of-stake
2793 // Limited duplicity on stake: prevents block flood attack
2794 // Duplicate stake allowed only when there is orphan child block
2795 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2796 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());
2798 // Strip the garbage from newly received blocks, if we found some
2799 if (!IsCanonicalBlockSignature(pblock)) {
2800 if (!ReserealizeBlockSignature(pblock))
2801 printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2804 // Preliminary checks
2805 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2806 return error("ProcessBlock() : CheckBlock FAILED");
2808 // ppcoin: verify hash target and signature of coinstake tx
2809 if (pblock->IsProofOfStake())
2811 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2812 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2814 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2815 return false; // do not error here as we expect this during initial block download
2817 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2818 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2821 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2822 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2824 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2825 auto deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2827 bnNewBlock.SetCompact(pblock->nBits);
2830 if (pblock->IsProofOfStake())
2831 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2833 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2835 if (bnNewBlock > bnRequired)
2838 pfrom->Misbehaving(100);
2839 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2843 // ppcoin: ask for pending sync-checkpoint if any
2844 if (!IsInitialBlockDownload())
2845 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2847 // If don't already have its previous block, shunt it off to holding area until we get it
2848 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2850 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2851 // ppcoin: check proof-of-stake
2852 if (pblock->IsProofOfStake())
2854 // Limited duplicity on stake: prevents block flood attack
2855 // Duplicate stake allowed only when there is orphan child block
2856 if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2857 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());
2859 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2861 CBlock* pblock2 = new CBlock(*pblock);
2862 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2863 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2865 // Ask this guy to fill in what we're missing
2868 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2869 // ppcoin: getblocks may not obtain the ancestor block rejected
2870 // earlier by duplicate-stake check so we ask for it again directly
2871 if (!IsInitialBlockDownload())
2872 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2878 if (!pblock->AcceptBlock())
2879 return error("ProcessBlock() : AcceptBlock FAILED");
2881 // Recursively process any orphan blocks that depended on this one
2882 vector<uint256> vWorkQueue;
2883 vWorkQueue.push_back(hash);
2884 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2886 auto hashPrev = vWorkQueue[i];
2887 for (auto mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2888 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2891 CBlock* pblockOrphan = (*mi).second;
2892 if (pblockOrphan->AcceptBlock())
2893 vWorkQueue.push_back(pblockOrphan->GetHash());
2894 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2895 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2896 delete pblockOrphan;
2898 mapOrphanBlocksByPrev.erase(hashPrev);
2901 printf("ProcessBlock: ACCEPTED\n");
2903 // ppcoin: if responsible for sync-checkpoint send it
2904 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2905 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2910 // ppcoin: check block signature
2911 bool CBlock::CheckBlockSignature() const
2913 if (vchBlockSig.empty())
2916 txnouttype whichType;
2917 vector<valtype> vSolutions;
2918 if (!Solver(vtx[1].vout[1].scriptPubKey, whichType, vSolutions))
2921 if (whichType == TX_PUBKEY)
2923 auto& vchPubKey = vSolutions[0];
2924 CPubKey key(vchPubKey);
2927 return key.Verify(GetHash(), vchBlockSig);
2939 uint256 CDiskBlockIndex::GetBlockHash() const
2941 if (fUseFastIndex && blockHash != 0)
2945 block.nVersion = nVersion;
2946 block.hashPrevBlock = hashPrev;
2947 block.hashMerkleRoot = hashMerkleRoot;
2948 block.nTime = nTime;
2949 block.nBits = nBits;
2950 block.nNonce = nNonce;
2952 const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
2957 string CDiskBlockIndex::ToString() const
2959 string str = "CDiskBlockIndex(";
2960 str += CBlockIndex::ToString();
2961 str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
2962 GetBlockHash().ToString().c_str(),
2963 hashPrev.ToString().c_str(),
2964 hashNext.ToString().c_str());
2972 void CBlockLocator::Set(const CBlockIndex* pindex)
2978 vHave.push_back(pindex->GetBlockHash());
2979 // Exponentially larger steps back
2980 for (int i = 0; pindex && i < nStep; i++)
2981 pindex = pindex->pprev;
2982 if (vHave.size() > 10)
2985 vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2988 int CBlockLocator::GetDistanceBack()
2990 // Retrace how far back it was in the sender's branch
2993 for(const auto& hash : vHave)
2995 auto mi = mapBlockIndex.find(hash);
2996 if (mi != mapBlockIndex.end())
2998 auto pindex = (*mi).second;
2999 if (pindex->IsInMainChain())
3009 CBlockIndex* CBlockLocator::GetBlockIndex()
3011 // Find the first block the caller has in the main chain
3012 for(const auto& hash : vHave)
3014 auto mi = mapBlockIndex.find(hash);
3015 if (mi != mapBlockIndex.end())
3017 auto pindex = (*mi).second;
3018 if (pindex->IsInMainChain())
3022 return pindexGenesisBlock;
3025 uint256 CBlockLocator::GetBlockHash()
3027 // Find the first block the caller has in the main chain
3028 for(const uint256& hash : vHave)
3030 auto mi = mapBlockIndex.find(hash);
3031 if (mi != mapBlockIndex.end())
3033 auto pindex = (*mi).second;
3034 if (pindex->IsInMainChain())
3038 return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
3041 int CBlockLocator::GetHeight()
3043 CBlockIndex* pindex = GetBlockIndex();
3046 return pindex->nHeight;
3049 bool CheckDiskSpace(uint64_t nAdditionalBytes)
3051 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
3053 // Check for nMinDiskSpace bytes (currently 50MB)
3054 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
3057 string strMessage("Warning: Disk space is low!");
3058 strMiscWarning = strMessage;
3059 printf("*** %s\n", strMessage.c_str());
3060 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
3067 static boost::filesystem::path BlockFilePath(unsigned int nFile)
3069 string strBlockFn = strprintf("blk%04u.dat", nFile);
3070 return GetDataDir() / strBlockFn;
3073 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
3075 if ((nFile < 1) || (nFile == std::numeric_limits<uint32_t>::max()))
3077 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
3080 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
3082 if (fseek(file, nBlockPos, SEEK_SET) != 0)
3091 static unsigned int nCurrentBlockFile = 1;
3093 FILE* AppendBlockFile(unsigned int& nFileRet)
3098 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
3101 if (fseek(file, 0, SEEK_END) != 0)
3106 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
3107 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
3109 nFileRet = nCurrentBlockFile;
3113 nCurrentBlockFile++;
3117 void UnloadBlockIndex()
3119 mapBlockIndex.clear();
3120 setStakeSeen.clear();
3121 pindexGenesisBlock = NULL;
3123 nBestChainTrust = 0;
3124 nBestInvalidTrust = 0;
3129 bool LoadBlockIndex(bool fAllowNew)
3133 nNetworkID = 0xefc0f2cd;
3135 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
3136 nStakeMinAge = 2 * nOneHour; // test net min age is 2 hours
3137 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
3138 nCoinbaseMaturity = 10; // test maturity is 10 blocks
3139 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
3146 if (!txdb.LoadBlockIndex())
3150 // Init with genesis block
3152 if (mapBlockIndex.empty())
3161 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
3162 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
3163 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
3165 // vMerkleTree: 4cb33b3b6a
3169 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
3170 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
3171 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
3173 // vMerkleTree: 4cb33b3b6a
3175 const string strTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
3177 txNew.nTime = 1360105017;
3178 txNew.vin.resize(1);
3179 txNew.vout.resize(1);
3180 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>(strTimestamp.begin(), strTimestamp.end());
3181 txNew.vout[0].SetEmpty();
3183 block.vtx.push_back(txNew);
3184 block.hashPrevBlock = 0;
3185 block.hashMerkleRoot = block.BuildMerkleTree();
3187 block.nTime = 1360105017;
3188 block.nBits = bnProofOfWorkLimit.GetCompact();
3189 block.nNonce = !fTestNet ? 1575379 : 46534;
3192 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
3194 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
3195 assert(block.CheckBlock());
3197 // Start new block file
3199 unsigned int nBlockPos;
3200 if (!block.WriteToDisk(nFile, nBlockPos))
3201 return error("LoadBlockIndex() : writing genesis block to disk failed");
3202 if (!block.AddToBlockIndex(nFile, nBlockPos))
3203 return error("LoadBlockIndex() : genesis block not accepted");
3205 // initialize synchronized checkpoint
3206 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
3207 return error("LoadBlockIndex() : failed to init sync checkpoint");
3209 // upgrade time set to zero if txdb initialized
3211 if (!txdb.WriteModifierUpgradeTime(0))
3212 return error("LoadBlockIndex() : failed to init upgrade info");
3213 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
3219 string strPubKey = "";
3220 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
3222 // write checkpoint master key to db
3224 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
3225 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
3226 if (!txdb.TxnCommit())
3227 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
3228 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
3229 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
3232 // upgrade time set to zero if blocktreedb initialized
3233 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
3235 if (nModifierUpgradeTime)
3236 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
3238 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
3242 nModifierUpgradeTime = GetTime();
3243 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
3244 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
3245 return error("LoadBlockIndex() : failed to write upgrade info");
3258 void PrintBlockTree()
3260 // pre-compute tree structure
3261 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
3262 for (auto mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
3264 CBlockIndex* pindex = (*mi).second;
3265 mapNext[pindex->pprev].push_back(pindex);
3267 //while (rand() % 3 == 0)
3268 // mapNext[pindex->pprev].push_back(pindex);
3271 vector<pair<int, CBlockIndex*> > vStack;
3272 vStack.push_back(make_pair(0, pindexGenesisBlock));
3275 while (!vStack.empty())
3277 int nCol = vStack.back().first;
3278 CBlockIndex* pindex = vStack.back().second;
3281 // print split or gap
3282 if (nCol > nPrevCol)
3284 for (int i = 0; i < nCol-1; i++)
3288 else if (nCol < nPrevCol)
3290 for (int i = 0; i < nCol; i++)
3297 for (int i = 0; i < nCol; i++)
3302 block.ReadFromDisk(pindex);
3303 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
3307 block.GetHash().ToString().c_str(),
3309 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
3310 FormatMoney(pindex->nMint).c_str(),
3313 PrintWallets(block);
3315 // put the main time-chain first
3316 vector<CBlockIndex*>& vNext = mapNext[pindex];
3317 for (unsigned int i = 0; i < vNext.size(); i++)
3319 if (vNext[i]->pnext)
3321 swap(vNext[0], vNext[i]);
3327 for (unsigned int i = 0; i < vNext.size(); i++)
3328 vStack.push_back(make_pair(nCol+i, vNext[i]));
3332 bool LoadExternalBlockFile(FILE* fileIn, CClientUIInterface& uiInterface)
3334 auto nStart = GetTimeMillis();
3335 vector<uint8_t> pchData(10 * (8+MAX_BLOCK_SIZE));
3336 int32_t nLoaded = 0;
3340 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
3342 while (nPos != std::numeric_limits<uint32_t>::max() && blkdat.good() && !fRequestShutdown)
3346 fseek(blkdat, nPos, SEEK_SET);
3347 auto nRead = fread(&pchData[0], 1, pchData.size(), blkdat);
3350 nPos = numeric_limits<uint32_t>::max();
3353 auto it = pchData.begin();
3354 while(it != pchData.end() && !fRequestShutdown)
3356 auto nBlockLength = *reinterpret_cast<const uint32_t*>(&(*(it+4)));
3357 auto SeekToNext = [&pchData, &it, &nPos, &nBlockLength]() {
3359 it = search(it+8, pchData.end(), BEGIN(nNetworkID), END(nNetworkID));
3360 if (it != pchData.end())
3361 nPos += (it - previt);
3363 if (nBlockLength > 0)
3365 if (nBlockLength > (uint32_t)distance(it, pchData.end()))
3368 break; // We've reached the end of buffer
3375 vector<unsigned char> vchBlockBytes(it+8, it+8+nBlockLength);
3376 CDataStream blockData(vchBlockBytes, SER_NETWORK, PROTOCOL_VERSION);
3379 catch (const std::exception&)
3381 printf("LoadExternalBlockFile() : Deserialize error caught at the position %" PRIu32 ", this block may be truncated.", nPos);
3385 if (ProcessBlock(NULL, &block))
3387 advance(it, 8 + nBlockLength);
3388 nPos += (8 + nBlockLength);
3390 static int64_t nLastUpdate = 0;
3391 if (GetTimeMillis() - nLastUpdate > 1000)
3393 uiInterface.InitMessage(strprintf(_("%" PRId32 " blocks were read."), nLoaded));
3394 nLastUpdate = GetTimeMillis();
3405 while(!fRequestShutdown);
3408 catch (const std::exception&) {
3409 printf("%s() : I/O error caught during load\n",
3410 BOOST_CURRENT_FUNCTION);
3413 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3417 //////////////////////////////////////////////////////////////////////////////
3422 extern map<uint256, CAlert> mapAlerts;
3423 extern CCriticalSection cs_mapAlerts;
3425 string GetWarnings(string strFor)
3428 string strStatusBar;
3431 if (GetBoolArg("-testsafemode"))
3434 // Misc warnings like out of disk space and clock is wrong
3435 if (!strMiscWarning.empty())
3438 strStatusBar = strMiscWarning;
3441 // if detected unmet upgrade requirement enter safe mode
3442 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3443 if (IsFixedModifierInterval(nModifierUpgradeTime + nOneDay)) // 1 day margin
3446 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3449 // if detected invalid checkpoint enter safe mode
3450 if (Checkpoints::hashInvalidCheckpoint != 0)
3453 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3459 for(auto& item : mapAlerts)
3461 const CAlert& alert = item.second;
3462 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3464 nPriority = alert.nPriority;
3465 strStatusBar = alert.strStatusBar;
3466 if (nPriority > 1000)
3467 strRPC = strStatusBar;
3472 if (strFor == "statusbar")
3473 return strStatusBar;
3474 else if (strFor == "rpc")
3476 assert(!"GetWarnings() : invalid parameter");
3487 //////////////////////////////////////////////////////////////////////////////
3493 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3495 int nType = inv.GetType();
3496 auto nHash = inv.GetHash();
3502 bool txInMap = false;
3505 txInMap = (mempool.exists(nHash));
3508 mapOrphanTransactions.count(nHash) ||
3509 txdb.ContainsTx(nHash);
3513 return mapBlockIndex.count(nHash) ||
3514 mapOrphanBlocks.count(nHash);
3516 // Don't know what it is, just say we already got one
3520 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3522 static map<CService, CPubKey> mapReuseKey;
3523 RandAddSeedPerfmon();
3525 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3526 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3528 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3532 if (strCommand == "version")
3534 // Each connection can only send one version message
3535 if (pfrom->nVersion != 0)
3537 pfrom->Misbehaving(1);
3544 uint64_t nNonce = 1;
3545 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3546 if (pfrom->nVersion < MIN_PROTO_VERSION)
3548 // Since February 20, 2012, the protocol is initiated at version 209,
3549 // and earlier versions are no longer supported
3550 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3551 pfrom->fDisconnect = true;
3555 if (pfrom->nVersion == 10300)
3556 pfrom->nVersion = 300;
3558 vRecv >> addrFrom >> nNonce;
3560 vRecv >> pfrom->strSubVer;
3562 vRecv >> pfrom->nStartingHeight;
3564 if (pfrom->fInbound && addrMe.IsRoutable())
3566 pfrom->addrLocal = addrMe;
3570 // Disconnect if we connected to ourself
3571 if (nNonce == nLocalHostNonce && nNonce > 1)
3573 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3574 pfrom->fDisconnect = true;
3578 if (pfrom->nVersion < 60010)
3580 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3581 pfrom->fDisconnect = true;
3585 // record my external IP reported by peer
3586 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3587 addrSeenByPeer = addrMe;
3589 // Be shy and don't send version until we hear
3590 if (pfrom->fInbound)
3591 pfrom->PushVersion();
3593 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3595 AddTimeData(pfrom->addr, nTime);
3598 pfrom->PushMessage("verack");
3599 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3601 if (!pfrom->fInbound)
3603 // Advertise our address
3604 if (fListen && !IsInitialBlockDownload())
3606 auto addr = GetLocalAddress(&pfrom->addr);
3607 if (addr.IsRoutable())
3608 pfrom->PushAddress(addr);
3611 // Get recent addresses
3612 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3614 pfrom->PushMessage("getaddr");
3615 pfrom->fGetAddr = true;
3617 addrman.Good(pfrom->addr);
3619 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3621 addrman.Add(addrFrom, addrFrom);
3622 addrman.Good(addrFrom);
3626 // Ask the first connected node for block updates
3627 static int nAskedForBlocks = 0;
3628 if (!pfrom->fClient && !pfrom->fOneShot &&
3629 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3630 (pfrom->nVersion < NOBLKS_VERSION_START ||
3631 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3632 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3635 pfrom->PushGetBlocks(pindexBest, uint256(0));
3641 for(auto& item : mapAlerts)
3642 item.second.RelayTo(pfrom);
3645 // Relay sync-checkpoint
3647 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3648 if (!Checkpoints::checkpointMessage.IsNull())
3649 Checkpoints::checkpointMessage.RelayTo(pfrom);
3652 pfrom->fSuccessfullyConnected = true;
3654 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());
3656 cPeerBlockCounts.input(pfrom->nStartingHeight);
3658 // ppcoin: ask for pending sync-checkpoint if any
3659 if (!IsInitialBlockDownload())
3660 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3664 else if (pfrom->nVersion == 0)
3666 // Must have a version message before anything else
3667 pfrom->Misbehaving(1);
3672 else if (strCommand == "verack")
3674 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3678 else if (strCommand == "addr")
3680 vector<CAddress> vAddr;
3683 // Don't want addr from older versions unless seeding
3684 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3686 if (vAddr.size() > 1000)
3688 pfrom->Misbehaving(20);
3689 return error("message addr size() = %" PRIszu "", vAddr.size());
3692 // Store the new addresses
3693 vector<CAddress> vAddrOk;
3694 auto nNow = GetAdjustedTime();
3695 auto nSince = nNow - 10 * 60;
3696 for(CAddress& addr : vAddr)
3700 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3701 addr.nTime = nNow - 5 * nOneDay;
3702 pfrom->AddAddressKnown(addr);
3703 bool fReachable = IsReachable(addr);
3704 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3706 // Relay to a limited number of other nodes
3709 // Use deterministic randomness to send to the same nodes for 24 hours
3710 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3711 static uint256 hashSalt;
3713 hashSalt = GetRandHash();
3714 uint64_t hashAddr = addr.GetHash();
3715 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/nOneDay);
3716 hashRand = Hash(hashRand.begin(), hashRand.end());
3717 multimap<uint256, CNode*> mapMix;
3718 for(CNode* pnode : vNodes)
3720 if (pnode->nVersion < CADDR_TIME_VERSION)
3722 unsigned int nPointer;
3723 memcpy(&nPointer, &pnode, sizeof(nPointer));
3724 uint256 hashKey = hashRand ^ nPointer;
3725 hashKey = Hash(hashKey.begin(), hashKey.end());
3726 mapMix.insert(make_pair(hashKey, pnode));
3728 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3729 for (auto mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3730 ((*mi).second)->PushAddress(addr);
3733 // Do not store addresses outside our network
3735 vAddrOk.push_back(addr);
3737 addrman.Add(vAddrOk, pfrom->addr, 2 * nOneHour);
3738 if (vAddr.size() < 1000)
3739 pfrom->fGetAddr = false;
3740 if (pfrom->fOneShot)
3741 pfrom->fDisconnect = true;
3744 else if (strCommand == "inv")
3748 if (vInv.size() > MAX_INV_SZ)
3750 pfrom->Misbehaving(20);
3751 return error("message inv size() = %" PRIszu "", vInv.size());
3754 // find last block in inv vector
3755 int nLastBlock = -1;
3756 for (size_t nInv = 0; nInv < vInv.size(); nInv++) {
3757 if (vInv[vInv.size() - 1 - nInv].GetType() == MSG_BLOCK) {
3758 nLastBlock = (int) (vInv.size() - 1 - nInv);
3763 for (size_t nInv = 0; nInv < vInv.size(); nInv++)
3765 const CInv &inv = vInv[nInv];
3766 int nType = inv.GetType();
3767 auto nHash = inv.GetHash();
3771 pfrom->AddInventoryKnown(inv);
3773 bool fAlreadyHave = AlreadyHave(txdb, inv);
3775 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3779 else if (nType == MSG_BLOCK && mapOrphanBlocks.count(nHash)) {
3780 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[nHash]));
3781 } else if (nType == nLastBlock) {
3782 // In case we are on a very long side-chain, it is possible that we already have
3783 // the last block in an inv bundle sent in response to getblocks. Try to detect
3784 // this situation and push another getblocks to continue.
3785 pfrom->PushGetBlocks(mapBlockIndex[nHash], uint256(0));
3787 printf("force request: %s\n", inv.ToString().c_str());
3790 // Track requests for our stuff
3796 else if (strCommand == "getdata")
3800 if (vInv.size() > MAX_INV_SZ)
3802 pfrom->Misbehaving(20);
3803 return error("message getdata size() = %" PRIszu "", vInv.size());
3806 if (fDebugNet || (vInv.size() != 1))
3807 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3809 for(const CInv& inv : vInv)
3813 if (fDebugNet || (vInv.size() == 1))
3814 printf("received getdata for: %s\n", inv.ToString().c_str());
3816 int nType = inv.GetType();
3817 auto nHash = inv.GetHash();
3819 if (nType == MSG_BLOCK)
3821 // Send block from disk
3822 auto mi = mapBlockIndex.find(nHash);
3823 if (mi != mapBlockIndex.end())
3826 block.ReadFromDisk((*mi).second);
3827 pfrom->PushMessage("block", block);
3829 // Trigger them to send a getblocks request for the next batch of inventory
3830 if (nHash == pfrom->hashContinue)
3832 // ppcoin: send latest proof-of-work block to allow the
3833 // download node to accept as orphan (proof-of-stake
3834 // block might be rejected by stake connection check)
3836 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3837 pfrom->PushMessage("inv", vInv);
3838 pfrom->hashContinue = 0;
3842 else if (inv.IsKnownType())
3844 // Send stream from relay memory
3845 bool pushed = false;
3848 auto mi = mapRelay.find(inv);
3849 if (mi != mapRelay.end()) {
3850 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3854 if (!pushed && nType == MSG_TX) {
3856 if (mempool.exists(nHash)) {
3857 CTransaction tx = mempool.lookup(nHash);
3858 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3861 pfrom->PushMessage("tx", ss);
3866 // Track requests for our stuff
3872 else if (strCommand == "getblocks")
3874 CBlockLocator locator;
3876 vRecv >> locator >> hashStop;
3878 // Find the last block the caller has in the main chain
3879 CBlockIndex* pindex = locator.GetBlockIndex();
3881 // Send the rest of the chain
3883 pindex = pindex->pnext;
3885 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3886 for (; pindex; pindex = pindex->pnext)
3888 if (pindex->GetBlockHash() == hashStop)
3890 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3891 // ppcoin: tell downloading node about the latest block if it's
3892 // without risk being rejected due to stake connection check
3893 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3894 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3897 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3900 // When this block is requested, we'll send an inv that'll make them
3901 // getblocks the next batch of inventory.
3902 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3903 pfrom->hashContinue = pindex->GetBlockHash();
3908 else if (strCommand == "checkpoint")
3910 CSyncCheckpoint checkpoint;
3911 vRecv >> checkpoint;
3913 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3916 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3918 for(CNode* pnode : vNodes)
3919 checkpoint.RelayTo(pnode);
3923 else if (strCommand == "getheaders")
3925 CBlockLocator locator;
3927 vRecv >> locator >> hashStop;
3929 CBlockIndex* pindex = NULL;
3930 if (locator.IsNull())
3932 // If locator is null, return the hashStop block
3933 auto mi = mapBlockIndex.find(hashStop);
3934 if (mi == mapBlockIndex.end())
3936 pindex = (*mi).second;
3940 // Find the last block the caller has in the main chain
3941 pindex = locator.GetBlockIndex();
3943 pindex = pindex->pnext;
3946 vector<CBlock> vHeaders;
3948 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3949 for (; pindex; pindex = pindex->pnext)
3951 vHeaders.push_back(pindex->GetBlockHeader());
3952 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3955 pfrom->PushMessage("headers", vHeaders);
3959 else if (strCommand == "tx")
3961 vector<uint256> vWorkQueue;
3962 vector<uint256> vEraseQueue;
3963 CDataStream vMsg(vRecv);
3968 CInv inv(MSG_TX, tx.GetHash());
3969 pfrom->AddInventoryKnown(inv);
3971 bool fMissingInputs = false;
3972 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3974 auto nHash = inv.GetHash();
3976 SyncWithWallets(tx, NULL, true);
3977 RelayTransaction(tx, nHash);
3978 mapAlreadyAskedFor.erase(inv);
3979 vWorkQueue.push_back(nHash);
3980 vEraseQueue.push_back(nHash);
3982 // Recursively process any orphan transactions that depended on this one
3983 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3985 auto hashPrev = vWorkQueue[i];
3986 for (auto mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3987 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3990 const uint256& orphanTxHash = *mi;
3991 auto& orphanTx = mapOrphanTransactions[orphanTxHash];
3992 bool fMissingInputs2 = false;
3994 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3996 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3997 SyncWithWallets(tx, NULL, true);
3998 RelayTransaction(orphanTx, orphanTxHash);
3999 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
4000 vWorkQueue.push_back(orphanTxHash);
4001 vEraseQueue.push_back(orphanTxHash);
4003 else if (!fMissingInputs2)
4006 vEraseQueue.push_back(orphanTxHash);
4007 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
4012 for(uint256 hash : vEraseQueue)
4013 EraseOrphanTx(hash);
4015 else if (fMissingInputs)
4019 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
4020 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
4022 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
4024 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
4028 else if (strCommand == "block")
4032 auto hashBlock = block.GetHash();
4034 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
4037 CInv inv(MSG_BLOCK, hashBlock);
4038 pfrom->AddInventoryKnown(inv);
4040 if (ProcessBlock(pfrom, &block))
4041 mapAlreadyAskedFor.erase(inv);
4042 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
4046 // This asymmetric behavior for inbound and outbound connections was introduced
4047 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
4048 // to users' AddrMan and later request them by sending getaddr messages.
4049 // Making users (which are behind NAT and can only make outgoing connections) ignore
4050 // getaddr message mitigates the attack.
4051 else if ((strCommand == "getaddr") && (pfrom->fInbound))
4053 // Don't return addresses older than nCutOff timestamp
4054 int64_t nCutOff = GetTime() - (nNodeLifespan * nOneDay);
4055 pfrom->vAddrToSend.clear();
4056 vector<CAddress> vAddr = addrman.GetAddr();
4057 for(const CAddress &addr : vAddr)
4058 if(addr.nTime > nCutOff)
4059 pfrom->PushAddress(addr);
4063 else if (strCommand == "mempool")
4065 std::vector<uint256> vtxid;
4066 mempool.queryHashes(vtxid);
4068 for (unsigned int i = 0; i < vtxid.size(); i++) {
4069 CInv inv(MSG_TX, vtxid[i]);
4070 vInv.push_back(inv);
4071 if (i == (MAX_INV_SZ - 1))
4074 if (vInv.size() > 0)
4075 pfrom->PushMessage("inv", vInv);
4079 else if (strCommand == "checkorder")
4084 if (!GetBoolArg("-allowreceivebyip"))
4086 pfrom->PushMessage("reply", hashReply, 2, string(""));
4093 /// we have a chance to check the order here
4095 // Keep giving the same key to the same ip until they use it
4096 if (!mapReuseKey.count(pfrom->addr))
4097 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
4099 // Send back approval of order and pubkey to use
4100 CScript scriptPubKey;
4101 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
4102 pfrom->PushMessage("reply", hashReply, 0, scriptPubKey);
4106 else if (strCommand == "reply")
4111 CRequestTracker tracker;
4113 LOCK(pfrom->cs_mapRequests);
4114 auto mi = pfrom->mapRequests.find(hashReply);
4115 if (mi != pfrom->mapRequests.end())
4117 tracker = (*mi).second;
4118 pfrom->mapRequests.erase(mi);
4121 if (!tracker.IsNull())
4122 tracker.fn(tracker.param1, vRecv);
4126 else if (strCommand == "ping")
4130 // Echo the message back with the nonce. This allows for two useful features:
4132 // 1) A remote node can quickly check if the connection is operational
4133 // 2) Remote nodes can measure the latency of the network thread. If this node
4134 // is overloaded it won't respond to pings quickly and the remote node can
4135 // avoid sending us more work, like chain download requests.
4137 // The nonce stops the remote getting confused between different pings: without
4138 // it, if the remote node sends a ping once per second and this node takes 5
4139 // seconds to respond to each, the 5th ping the remote sends would appear to
4140 // return very quickly.
4141 pfrom->PushMessage("pong", nonce);
4145 else if (strCommand == "alert")
4150 auto alertHash = alert.GetHash();
4151 if (pfrom->setKnown.count(alertHash) == 0)
4153 if (alert.ProcessAlert())
4156 pfrom->setKnown.insert(alertHash);
4159 for(CNode* pnode : vNodes)
4160 alert.RelayTo(pnode);
4164 // Small DoS penalty so peers that send us lots of
4165 // duplicate/expired/invalid-signature/whatever alerts
4166 // eventually get banned.
4167 // This isn't a Misbehaving(100) (immediate ban) because the
4168 // peer might be an older or different implementation with
4169 // a different signature key, etc.
4170 pfrom->Misbehaving(10);
4178 // Ignore unknown commands for extensibility
4182 // Update the last seen time for this node's address
4183 if (pfrom->fNetworkNode)
4184 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
4185 AddressCurrentlyConnected(pfrom->addr);
4191 bool ProcessMessages(CNode* pfrom)
4193 CDataStream& vRecv = pfrom->vRecv;
4197 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
4201 // (4) message start
4210 // Don't bother if send buffer is too full to respond anyway
4211 if (pfrom->vSend.size() >= SendBufferSize())
4214 // Scan for message start
4215 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(nNetworkID), END(nNetworkID));
4216 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
4217 if (vRecv.end() - pstart < nHeaderSize)
4219 if ((int)vRecv.size() > nHeaderSize)
4221 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
4222 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
4226 if (pstart - vRecv.begin() > 0)
4227 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
4228 vRecv.erase(vRecv.begin(), pstart);
4231 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
4236 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
4239 string strCommand = hdr.GetCommand();
4242 unsigned int nMessageSize = hdr.nMessageSize;
4243 if (nMessageSize > MAX_SIZE)
4245 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
4248 if (nMessageSize > vRecv.size())
4250 // Rewind and wait for rest of message
4251 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
4256 auto hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
4257 unsigned int nChecksum = 0;
4258 memcpy(&nChecksum, &hash, sizeof(nChecksum));
4259 if (nChecksum != hdr.nChecksum)
4261 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
4262 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
4266 // Copy message to its own buffer
4267 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
4268 vRecv.ignore(nMessageSize);
4276 fRet = ProcessMessage(pfrom, strCommand, vMsg);
4281 catch (std::ios_base::failure& e)
4283 if (strstr(e.what(), "end of data"))
4285 // Allow exceptions from under-length message on vRecv
4286 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());
4288 else if (strstr(e.what(), "size too large"))
4290 // Allow exceptions from over-long size
4291 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
4295 PrintExceptionContinue(&e, "ProcessMessages()");
4298 catch (std::exception& e) {
4299 PrintExceptionContinue(&e, "ProcessMessages()");
4301 PrintExceptionContinue(NULL, "ProcessMessages()");
4305 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
4313 bool SendMessages(CNode* pto)
4315 TRY_LOCK(cs_main, lockMain);
4317 // Current time in microseconds
4318 auto nNow = GetTimeMicros();
4320 // Don't send anything until we get their version message
4321 if (pto->nVersion == 0)
4324 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
4326 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
4328 pto->PushMessage("ping", nonce);
4332 if (pto->fStartSync) {
4333 pto->fStartSync = false;
4334 pto->PushGetBlocks(pindexBest, uint256(0));
4337 // Resend wallet transactions that haven't gotten in a block yet
4338 ResendWalletTransactions();
4340 // Address refresh broadcast
4341 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
4342 AdvertiseLocal(pto);
4343 pto->nNextLocalAddrSend = PoissonNextSend(nNow, nOneDay);
4349 if (pto->nNextAddrSend < nNow) {
4350 pto->nNextAddrSend = PoissonNextSend(nNow, 30);
4351 vector<CAddress> vAddr;
4352 vAddr.reserve(pto->vAddrToSend.size());
4353 for(const CAddress& addr : pto->vAddrToSend)
4355 if (pto->setAddrKnown.insert(addr).second)
4357 vAddr.push_back(addr);
4358 // receiver rejects addr messages larger than 1000
4359 if (vAddr.size() >= 1000)
4361 pto->PushMessage("addr", vAddr);
4366 pto->vAddrToSend.clear();
4368 pto->PushMessage("addr", vAddr);
4372 // Message: inventory
4375 vector<CInv> vInvWait;
4377 bool fSendTrickle = false;
4378 if (pto->nNextInvSend < nNow) {
4379 fSendTrickle = true;
4380 pto->nNextInvSend = PoissonNextSend(nNow, 5);
4382 LOCK(pto->cs_inventory);
4383 vInv.reserve(pto->vInventoryToSend.size());
4384 vInvWait.reserve(pto->vInventoryToSend.size());
4385 for(const CInv& inv : pto->vInventoryToSend)
4387 if (pto->setInventoryKnown.count(inv))
4390 // trickle out tx inv to protect privacy
4391 if (inv.GetType() == MSG_TX && !fSendTrickle)
4393 // 1/4 of tx invs blast to all immediately
4394 static uint256 hashSalt;
4396 hashSalt = GetRandHash();
4397 uint256 hashRand = inv.GetHash() ^ hashSalt;
4398 hashRand = Hash(hashRand.begin(), hashRand.end());
4399 bool fTrickleWait = ((hashRand & 3) != 0);
4403 vInvWait.push_back(inv);
4408 // returns true if wasn't already contained in the set
4409 if (pto->setInventoryKnown.insert(inv).second)
4411 vInv.push_back(inv);
4412 if (vInv.size() >= 1000)
4414 pto->PushMessage("inv", vInv);
4419 pto->vInventoryToSend = vInvWait;
4422 pto->PushMessage("inv", vInv);
4428 vector<CInv> vGetData;
4430 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4432 const CInv& inv = (*pto->mapAskFor.begin()).second;
4433 if (!AlreadyHave(txdb, inv))
4436 printf("sending getdata: %s\n", inv.ToString().c_str());
4437 vGetData.push_back(inv);
4438 if (vGetData.size() >= 1000)
4440 pto->PushMessage("getdata", vGetData);
4443 mapAlreadyAskedFor[inv] = nNow;
4445 pto->mapAskFor.erase(pto->mapAskFor.begin());
4447 if (!vGetData.empty())
4448 pto->PushMessage("getdata", vGetData);
4461 auto it1 = mapBlockIndex.begin();
4462 for (; it1 != mapBlockIndex.end(); it1++)
4463 delete (*it1).second;
4464 mapBlockIndex.clear();
4467 auto it2 = mapOrphanBlocks.begin();
4468 for (; it2 != mapOrphanBlocks.end(); it2++)
4469 delete (*it2).second;
4470 mapOrphanBlocks.clear();
4472 // orphan transactions
4474 } instance_of_cmaincleanup;