1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
11 #include "ui_interface.h"
12 #include "checkqueue.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
21 using namespace boost;
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
31 unsigned int nTransactionsUpdated = 0;
33 map<uint256, CBlockIndex*> mapBlockIndex;
34 set<pair<COutPoint, unsigned int> > setStakeSeen;
36 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
37 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
38 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
39 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
40 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
42 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
44 unsigned int nStakeMinAge = 30 * nOneDay; // 30 days as zero time weight
45 unsigned int nStakeMaxAge = 90 * nOneDay; // 90 days as full weight
46 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
47 unsigned int nModifierInterval = 6 * nOneHour; // time to elapse before new modifier is computed
49 int nCoinbaseMaturity = 500;
51 CBlockIndex* pindexGenesisBlock = NULL;
54 uint256 nBestChainTrust = 0;
55 uint256 nBestInvalidTrust = 0;
57 uint256 hashBestChain = 0;
58 CBlockIndex* pindexBest = NULL;
59 int64_t nTimeBestReceived = 0;
60 int nScriptCheckThreads = 0;
62 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
64 map<uint256, CBlock*> mapOrphanBlocks;
65 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
66 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
67 map<uint256, uint256> mapProofOfStake;
69 map<uint256, CTransaction> mapOrphanTransactions;
70 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
72 // Constant stuff for coinbase transactions we create:
73 CScript COINBASE_FLAGS;
75 const string strMessageMagic = "NovaCoin Signed Message:\n";
78 int64_t nTransactionFee = MIN_TX_FEE;
79 int64_t nMinimumInputValue = MIN_TXOUT_AMOUNT;
81 // Ping and address broadcast intervals
82 int64_t nPingInterval = 30 * 60;
84 extern enum Checkpoints::CPMode CheckpointsMode;
86 //////////////////////////////////////////////////////////////////////////////
88 // dispatching functions
91 // These functions dispatch to one or all registered wallets
94 void RegisterWallet(CWallet* pwalletIn)
97 LOCK(cs_setpwalletRegistered);
98 setpwalletRegistered.insert(pwalletIn);
102 void UnregisterWallet(CWallet* pwalletIn)
105 LOCK(cs_setpwalletRegistered);
106 setpwalletRegistered.erase(pwalletIn);
110 // check whether the passed transaction is from us
111 bool static IsFromMe(CTransaction& tx)
113 for(CWallet* pwallet : setpwalletRegistered)
114 if (pwallet->IsFromMe(tx))
119 // make sure all wallets know about the given transaction, in the given block
120 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
124 // wallets need to refund inputs when disconnecting coinstake
125 if (tx.IsCoinStake())
127 for(CWallet* pwallet : setpwalletRegistered)
128 if (pwallet->IsFromMe(tx))
129 pwallet->DisableTransaction(tx);
134 for(CWallet* pwallet : setpwalletRegistered)
135 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
138 // notify wallets about a new best chain
139 void static SetBestChain(const CBlockLocator& loc)
141 for(CWallet* pwallet : setpwalletRegistered)
142 pwallet->SetBestChain(loc);
145 // notify wallets about an updated transaction
146 void static UpdatedTransaction(const uint256& hashTx)
148 for(CWallet* pwallet : setpwalletRegistered)
149 pwallet->UpdatedTransaction(hashTx);
153 void static PrintWallets(const CBlock& block)
155 for(CWallet* pwallet : setpwalletRegistered)
156 pwallet->PrintWallet(block);
159 // notify wallets about an incoming inventory (for request counts)
160 void static Inventory(const uint256& hash)
162 for(CWallet* pwallet : setpwalletRegistered)
163 pwallet->Inventory(hash);
166 // ask wallets to resend their transactions
167 void ResendWalletTransactions(bool fForceResend)
169 for(CWallet* pwallet : setpwalletRegistered)
170 pwallet->ResendWalletTransactions(fForceResend);
179 //////////////////////////////////////////////////////////////////////////////
181 // mapOrphanTransactions
184 bool AddOrphanTx(const CTransaction& tx)
186 auto hash = tx.GetHash();
187 if (mapOrphanTransactions.count(hash))
190 // Ignore big transactions, to avoid a
191 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
192 // large transaction with a missing parent then we assume
193 // it will rebroadcast it later, after the parent transaction(s)
194 // have been mined or received.
195 // 10,000 orphans, each of which is at most 5,000 bytes big is
196 // at most 500 megabytes of orphans:
198 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
202 printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
206 mapOrphanTransactions[hash] = tx;
207 for(const CTxIn& txin : tx.vin)
208 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
210 printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
211 mapOrphanTransactions.size());
215 void static EraseOrphanTx(uint256 hash)
217 if (!mapOrphanTransactions.count(hash))
219 const auto& tx = mapOrphanTransactions[hash];
220 for(const auto& txin : tx.vin)
222 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
223 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
224 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
226 mapOrphanTransactions.erase(hash);
229 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
231 unsigned int nEvicted = 0;
232 while (mapOrphanTransactions.size() > nMaxOrphans)
234 // Evict a random orphan:
235 auto randomhash = GetRandHash();
236 auto it = mapOrphanTransactions.lower_bound(randomhash);
237 if (it == mapOrphanTransactions.end())
238 it = mapOrphanTransactions.begin();
239 EraseOrphanTx(it->first);
251 //////////////////////////////////////////////////////////////////////////////
253 // CTransaction and CTxIndex
256 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
259 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
261 if (!ReadFromDisk(txindexRet.pos))
263 if (prevout.n >= vout.size())
271 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
274 return ReadFromDisk(txdb, prevout, txindex);
277 bool CTransaction::ReadFromDisk(COutPoint prevout)
281 return ReadFromDisk(txdb, prevout, txindex);
284 bool CTransaction::IsStandard(string& strReason) const
286 if (nVersion > CTransaction::CURRENT_VERSION)
288 strReason = "version";
292 unsigned int nDataOut = 0;
293 txnouttype whichType;
294 for(const CTxIn& txin : vin)
296 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
297 // keys. (remember the 520 byte limit on redeemScript size) That works
298 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
299 // bytes of scriptSig, which we round off to 1650 bytes for some minor
300 // future-proofing. That's also enough to spend a 20-of-20
301 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
302 // considered standard)
303 if (txin.scriptSig.size() > 1650)
305 strReason = "scriptsig-size";
308 if (!txin.scriptSig.IsPushOnly())
310 strReason = "scriptsig-not-pushonly";
313 if (!txin.scriptSig.HasCanonicalPushes()) {
314 strReason = "txin-scriptsig-not-canonicalpushes";
318 for(const CTxOut& txout : vout) {
319 if (!::IsStandard(txout.scriptPubKey, whichType)) {
320 strReason = "scriptpubkey";
323 if (whichType == TX_NULL_DATA)
326 if (txout.nValue == 0) {
327 strReason = "txout-value=0";
330 if (!txout.scriptPubKey.HasCanonicalPushes()) {
331 strReason = "txout-scriptsig-not-canonicalpushes";
337 // only one OP_RETURN txout is permitted
339 strReason = "multi-op-return";
347 // Check transaction inputs, and make sure any
348 // pay-to-script-hash transactions are evaluating IsStandard scripts
350 // Why bother? To avoid denial-of-service attacks; an attacker
351 // can submit a standard HASH... OP_EQUAL transaction,
352 // which will get accepted into blocks. The redemption
353 // script can be anything; an attacker could use a very
354 // expensive-to-check-upon-redemption script like:
355 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
357 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
360 return true; // Coinbases don't use vin normally
362 for (uint32_t i = 0; i < vin.size(); i++)
364 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
366 vector<vector<unsigned char> > vSolutions;
367 txnouttype whichType;
368 // get the scriptPubKey corresponding to this input:
369 const CScript& prevScript = prev.scriptPubKey;
370 if (!Solver(prevScript, whichType, vSolutions))
372 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
373 if (nArgsExpected < 0)
376 // Transactions with extra stuff in their scriptSigs are
377 // non-standard. Note that this EvalScript() call will
378 // be quick, because if there are any operations
379 // beside "push data" in the scriptSig the
380 // IsStandard() call returns false
381 vector<vector<unsigned char> > stack;
382 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
385 if (whichType == TX_SCRIPTHASH)
389 CScript subscript(stack.back().begin(), stack.back().end());
390 vector<vector<unsigned char> > vSolutions2;
391 txnouttype whichType2;
392 if (!Solver(subscript, whichType2, vSolutions2))
394 if (whichType2 == TX_SCRIPTHASH)
398 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
401 nArgsExpected += tmpExpected;
404 if (stack.size() != (unsigned int)nArgsExpected)
412 CTransaction::GetLegacySigOpCount() const
414 unsigned int nSigOps = 0;
417 // Coinbase scriptsigs are never executed, so there is
418 // no sense in calculation of sigops.
419 for(const CTxIn& txin : vin)
421 nSigOps += txin.scriptSig.GetSigOpCount(false);
424 for(const CTxOut& txout : vout)
426 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
431 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
444 // Load the block this tx is in
446 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
448 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
453 // Update the tx's hashBlock
454 hashBlock = pblock->GetHash();
456 // Locate the transaction
457 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
458 if (pblock->vtx[nIndex] == *(CTransaction*)this)
460 if (nIndex == (int)pblock->vtx.size())
462 vMerkleBranch.clear();
464 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
468 // Fill in merkle branch
469 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
472 // Is the tx in a block that's in the main chain
473 auto mi = mapBlockIndex.find(hashBlock);
474 if (mi == mapBlockIndex.end())
476 const CBlockIndex* pindex = (*mi).second;
477 if (!pindex || !pindex->IsInMainChain())
480 return pindexBest->nHeight - pindex->nHeight + 1;
483 bool CTransaction::CheckTransaction() const
485 // Basic checks that don't depend on any context
487 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
489 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
491 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
492 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
494 // Check for negative or overflow output values
495 int64_t nValueOut = 0;
496 for (unsigned int i = 0; i < vout.size(); i++)
498 const CTxOut& txout = vout[i];
499 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
500 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
501 if (!MoneyRange(txout.nValue))
502 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is out of range"));
503 nValueOut += txout.nValue;
504 if (!MoneyRange(nValueOut))
505 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
508 // Check for duplicate inputs
509 set<COutPoint> vInOutPoints;
510 for(const CTxIn& txin : vin)
512 if (vInOutPoints.count(txin.prevout))
514 vInOutPoints.insert(txin.prevout);
519 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
520 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
524 for(const CTxIn& txin : vin)
525 if (txin.prevout.IsNull())
526 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
532 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
534 int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
538 // Enforce 0.01 as minimum fee for coinstake
540 nMinRelayTxFee = CENT;
543 // Base fee is either nMinTxFee or nMinRelayTxFee
544 auto nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
546 unsigned int nNewBlockSize = nBlockSize + nBytes;
547 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
553 // Transactions under 1K are free
559 // Free transaction area
560 if (nNewBlockSize < 27000)
565 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
566 // each non empty output which is less than 0.01
568 // It's safe to ignore empty outputs here, because these inputs are allowed
569 // only for coinbase and coinstake transactions.
570 for(const CTxOut& txout : vout)
571 if (txout.nValue < CENT && !txout.IsEmpty())
574 // Raise the price as the block approaches full
575 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
577 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
579 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
582 if (!MoneyRange(nMinFee))
589 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
590 bool* pfMissingInputs)
593 *pfMissingInputs = false;
595 // Time (prevent mempool memory exhaustion attack)
596 if (tx.nTime > FutureDrift(GetAdjustedTime()))
597 return tx.DoS(10, error("CTxMemPool::accept() : transaction timestamp is too far in the future"));
599 if (!tx.CheckTransaction())
600 return error("CTxMemPool::accept() : CheckTransaction failed");
602 // Coinbase is only valid in a block, not as a loose transaction
604 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
606 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
607 if (tx.IsCoinStake())
608 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
610 // To help v0.1.5 clients who would see it as a negative number
611 if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
612 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
614 // Rather not work on nonstandard transactions (unless -testnet)
616 if (!fTestNet && !tx.IsStandard(strNonStd))
617 return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
619 // Do we already have it?
620 auto hash = tx.GetHash();
623 if (mapTx.count(hash))
627 if (txdb.ContainsTx(hash))
630 // Check for conflicts with in-memory transactions
631 for (unsigned int i = 0; i < tx.vin.size(); i++)
633 auto outpoint = tx.vin[i].prevout;
634 if (mapNextTx.count(outpoint))
636 // Replacement feature isn't supported by Novacoin.
644 map<uint256, CTxIndex> mapUnused;
645 bool fInvalid = false;
646 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
649 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
651 *pfMissingInputs = true;
655 // Check for non-standard pay-to-script-hash in inputs
656 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
657 return error("CTxMemPool::accept() : nonstandard transaction input");
659 // Note: if you modify this code to accept non-standard transactions, then
660 // you should add code here to check that the transaction does a
661 // reasonable number of ECDSA signature verifications.
663 auto nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
664 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
666 // Don't accept it if it can't get into a block
667 auto txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
668 if (nFees < txMinFee)
669 return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
670 hash.ToString().c_str(),
673 // Continuously rate-limit free transactions
674 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
675 // be annoying or make others' transactions take longer to confirm.
676 if (nFees < MIN_RELAY_TX_FEE)
678 static CCriticalSection cs;
679 static double dFreeCount;
680 static int64_t nLastTime;
681 auto nNow = GetTime();
685 // Use an exponentially decaying ~10-minute window:
686 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
688 // -limitfreerelay unit is thousand-bytes-per-minute
689 // At default rate it would take over a month to fill 1GB
690 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
691 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
693 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
698 // Check against previous transactions
699 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
700 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, STRICT_FLAGS))
702 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
706 // Store transaction in memory
709 addUnchecked(hash, tx);
712 printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
713 hash.ToString().substr(0,10).c_str(),
718 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
720 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
723 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
725 // Add to memory pool without checking anything. Don't call this directly,
726 // call CTxMemPool::accept to properly check the transaction first.
729 for (unsigned int i = 0; i < tx.vin.size(); i++)
730 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
731 nTransactionsUpdated++;
737 bool CTxMemPool::remove(CTransaction &tx)
739 // Remove transaction from memory pool
742 auto hash = tx.GetHash();
743 if (mapTx.count(hash))
745 for(const CTxIn& txin : tx.vin)
746 mapNextTx.erase(txin.prevout);
748 nTransactionsUpdated++;
754 void CTxMemPool::clear()
759 ++nTransactionsUpdated;
762 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
767 vtxid.reserve(mapTx.size());
768 for (auto mi = mapTx.begin(); mi != mapTx.end(); ++mi)
769 vtxid.push_back((*mi).first);
775 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
777 if (hashBlock == 0 || nIndex == -1)
780 // Find the block it claims to be in
781 auto mi = mapBlockIndex.find(hashBlock);
782 if (mi == mapBlockIndex.end())
784 CBlockIndex* pindex = (*mi).second;
785 if (!pindex || !pindex->IsInMainChain())
788 // Make sure the merkle branch connects to this block
789 if (!fMerkleVerified)
791 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
793 fMerkleVerified = true;
797 return pindexBest->nHeight - pindex->nHeight + 1;
801 int CMerkleTx::GetBlocksToMaturity() const
803 if (!(IsCoinBase() || IsCoinStake()))
805 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
809 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
813 if (!IsInMainChain() && !ClientConnectInputs())
815 return CTransaction::AcceptToMemoryPool(txdb, false);
819 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
823 bool CMerkleTx::AcceptToMemoryPool()
826 return AcceptToMemoryPool(txdb);
831 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
836 // Add previous supporting transactions first
837 for(CMerkleTx& tx : vtxPrev)
839 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
841 auto hash = tx.GetHash();
842 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
843 tx.AcceptToMemoryPool(txdb, fCheckInputs);
846 return AcceptToMemoryPool(txdb, fCheckInputs);
851 bool CWalletTx::AcceptWalletTransaction()
854 return AcceptWalletTransaction(txdb);
857 int CTxIndex::GetDepthInMainChain() const
861 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
863 // Find the block in the index
864 auto mi = mapBlockIndex.find(block.GetHash());
865 if (mi == mapBlockIndex.end())
867 auto pindex = (*mi).second;
868 if (!pindex || !pindex->IsInMainChain())
870 return 1 + nBestHeight - pindex->nHeight;
873 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
874 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
880 if (mempool.exists(hash))
882 tx = mempool.lookup(hash);
888 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
891 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
892 hashBlock = block.GetHash();
906 //////////////////////////////////////////////////////////////////////////////
908 // CBlock and CBlockIndex
911 static CBlockIndex* pblockindexFBBHLast;
912 CBlockIndex* FindBlockByHeight(int nHeight)
914 CBlockIndex *pblockindex;
915 if (nHeight < nBestHeight / 2)
916 pblockindex = pindexGenesisBlock;
918 pblockindex = pindexBest;
919 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
920 pblockindex = pblockindexFBBHLast;
921 while (pblockindex->nHeight > nHeight)
922 pblockindex = pblockindex->pprev;
923 while (pblockindex->nHeight < nHeight)
924 pblockindex = pblockindex->pnext;
925 pblockindexFBBHLast = pblockindex;
929 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
931 if (!fReadTransactions)
933 *this = pindex->GetBlockHeader();
936 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
938 if (GetHash() != pindex->GetBlockHash())
939 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
943 uint256 static GetOrphanRoot(const CBlock* pblock)
945 // Work back to the first block in the orphan chain
946 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
947 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
948 return pblock->GetHash();
951 // ppcoin: find block wanted by given orphan block
952 uint256 WantedByOrphan(const CBlock* pblockOrphan)
954 // Work back to the first block in the orphan chain
955 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
956 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
957 return pblockOrphan->hashPrevBlock;
960 // select stake target limit according to hard-coded conditions
961 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
963 if(fTestNet) // separate proof of stake target limit for testnet
964 return bnProofOfStakeLimit;
965 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
966 return bnProofOfStakeLimit;
967 if(nHeight + 1 > 15000) // 24 bits since block 15000
968 return bnProofOfStakeLegacyLimit;
969 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
970 return bnProofOfStakeHardLimit;
972 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
975 // miner's coin base reward based on nBits
976 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees)
978 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
981 bnTarget.SetCompact(nBits);
982 CBigNum bnTargetLimit = bnProofOfWorkLimit;
983 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
985 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
986 // A reasonably continuous curve is used to avoid shock to market
987 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
989 // Human readable form:
991 // nSubsidy = 100 / (diff ^ 1/6)
993 // Please note that we're using bisection to find an approximate solutuion
994 CBigNum bnLowerBound = CENT;
995 CBigNum bnUpperBound = bnSubsidyLimit;
996 while (bnLowerBound + CENT <= bnUpperBound)
998 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
999 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1000 bnUpperBound = bnMidValue;
1002 bnLowerBound = bnMidValue;
1005 int64_t nSubsidy = bnUpperBound.getuint64();
1007 nSubsidy = (nSubsidy / CENT) * CENT;
1008 if (fDebug && GetBoolArg("-printcreation"))
1009 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1011 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1014 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1015 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1017 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1019 // Stage 2 of emission process is mostly PoS-based.
1021 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1023 bnTarget.SetCompact(nBits);
1024 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1025 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1027 // A reasonably continuous curve is used to avoid shock to market
1029 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1030 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1031 bnMidPart, bnRewardPart;
1033 while (bnLowerBound + CENT <= bnUpperBound)
1035 auto bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1038 // Reward for coin-year is cut in half every 8x multiply of PoS difficulty
1040 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1042 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1045 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1046 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1048 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1049 bnUpperBound = bnMidValue;
1051 bnLowerBound = bnMidValue;
1054 nRewardCoinYear = bnUpperBound.getuint64();
1055 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1058 return nRewardCoinYear;
1060 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1062 // Set reasonable reward limit for large inputs
1064 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1066 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1067 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1069 nSubsidy = min(nSubsidy, nSubsidyLimit);
1071 if (fDebug && GetBoolArg("-printcreation"))
1072 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1077 static const int64_t nTargetTimespan = 7 * nOneDay; // one week
1079 // get proof of work blocks max spacing according to hard-coded conditions
1080 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1082 if(nTime > TARGETS_SWITCH_TIME)
1083 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1086 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1088 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1092 // maximum nBits value could possible be required nTime after
1094 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1097 bnResult.SetCompact(nBase);
1099 while (nTime > 0 && bnResult < bnTargetLimit)
1101 // Maximum 200% adjustment per day...
1105 if (bnResult > bnTargetLimit)
1106 bnResult = bnTargetLimit;
1107 return bnResult.GetCompact();
1111 // minimum amount of work that could possibly be required nTime after
1112 // minimum proof-of-work required was nBase
1114 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1116 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1120 // minimum amount of stake that could possibly be required nTime after
1121 // minimum proof-of-stake required was nBase
1123 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1125 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1129 // ppcoin: find last block index up to pindex
1130 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1132 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1133 pindex = pindex->pprev;
1137 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1139 if (pindexLast == NULL)
1140 return bnProofOfWorkLimit.GetCompact(); // genesis block
1142 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1144 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1145 if (pindexPrev->pprev == NULL)
1146 return bnTargetLimit.GetCompact(); // first block
1147 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1148 if (pindexPrevPrev->pprev == NULL)
1149 return bnTargetLimit.GetCompact(); // second block
1151 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1153 // ppcoin: target change every block
1154 // ppcoin: retarget with exponential moving toward target spacing
1156 bnNew.SetCompact(pindexPrev->nBits);
1157 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1158 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1159 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1160 bnNew /= ((nInterval + 1) * nTargetSpacing);
1162 if (bnNew > bnTargetLimit)
1163 bnNew = bnTargetLimit;
1165 return bnNew.GetCompact();
1168 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1171 bnTarget.SetCompact(nBits);
1174 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1175 return error("CheckProofOfWork() : nBits below minimum work");
1177 // Check proof of work matches claimed amount
1178 if (hash > bnTarget.getuint256())
1179 return error("CheckProofOfWork() : hash doesn't match nBits");
1184 // Return maximum amount of blocks that other nodes claim to have
1185 int GetNumBlocksOfPeers()
1187 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1190 bool IsInitialBlockDownload()
1192 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1194 static int64_t nLastUpdate;
1195 static CBlockIndex* pindexLastBest;
1196 auto nCurrentTime = GetTime();
1197 if (pindexBest != pindexLastBest)
1199 pindexLastBest = pindexBest;
1200 nLastUpdate = nCurrentTime;
1202 return (nCurrentTime - nLastUpdate < 10 &&
1203 pindexBest->GetBlockTime() < nCurrentTime - nOneDay);
1206 void static InvalidChainFound(CBlockIndex* pindexNew)
1208 if (pindexNew->nChainTrust > nBestInvalidTrust)
1210 nBestInvalidTrust = pindexNew->nChainTrust;
1211 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1212 uiInterface.NotifyBlocksChanged();
1215 auto nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1216 auto nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1218 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1219 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1220 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1221 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1222 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1223 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1224 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1225 nBestBlockTrust.Get64(),
1226 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1230 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1232 nTime = max(GetBlockTime(), GetAdjustedTime());
1245 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1247 // Relinquish previous transactions' spent pointers
1250 for(const CTxIn& txin : vin)
1252 auto prevout = txin.prevout;
1254 // Get prev txindex from disk
1256 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1257 return error("DisconnectInputs() : ReadTxIndex failed");
1259 if (prevout.n >= txindex.vSpent.size())
1260 return error("DisconnectInputs() : prevout.n out of range");
1262 // Mark outpoint as not spent
1263 txindex.vSpent[prevout.n].SetNull();
1266 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1267 return error("DisconnectInputs() : UpdateTxIndex failed");
1271 // Remove transaction from index
1272 // This can fail if a duplicate of this transaction was in a chain that got
1273 // reorganized away. This is only possible if this transaction was completely
1274 // spent, so erasing it would be a no-op anyway.
1275 txdb.EraseTxIndex(*this);
1281 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1282 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1284 // FetchInputs can return false either because we just haven't seen some inputs
1285 // (in which case the transaction should be stored as an orphan)
1286 // or because the transaction is malformed (in which case the transaction should
1287 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1291 return true; // Coinbase transactions have no inputs to fetch.
1293 for (unsigned int i = 0; i < vin.size(); i++)
1295 auto prevout = vin[i].prevout;
1296 if (inputsRet.count(prevout.hash))
1297 continue; // Got it already
1300 CTxIndex& txindex = inputsRet[prevout.hash].first;
1302 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1304 // Get txindex from current proposed changes
1305 txindex = mapTestPool.find(prevout.hash)->second;
1309 // Read txindex from txdb
1310 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1312 if (!fFound && (fBlock || fMiner))
1313 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());
1316 CTransaction& txPrev = inputsRet[prevout.hash].second;
1317 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1319 // Get prev tx from single transactions in memory
1322 if (!mempool.exists(prevout.hash))
1323 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());
1324 txPrev = mempool.lookup(prevout.hash);
1327 txindex.vSpent.resize(txPrev.vout.size());
1331 // Get prev tx from disk
1332 if (!txPrev.ReadFromDisk(txindex.pos))
1333 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1337 // Make sure all prevout.n indexes are valid:
1338 for (unsigned int i = 0; i < vin.size(); i++)
1340 const COutPoint prevout = vin[i].prevout;
1341 assert(inputsRet.count(prevout.hash) != 0);
1342 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1343 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1344 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1346 // Revisit this if/when transaction replacement is implemented and allows
1349 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()));
1356 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1358 auto mi = inputs.find(input.prevout.hash);
1359 if (mi == inputs.end())
1360 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1362 const auto& txPrev = (mi->second).second;
1363 if (input.prevout.n >= txPrev.vout.size())
1364 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1366 return txPrev.vout[input.prevout.n];
1369 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1374 int64_t nResult = 0;
1375 for (unsigned int i = 0; i < vin.size(); i++)
1377 nResult += GetOutputFor(vin[i], inputs).nValue;
1383 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1388 unsigned int nSigOps = 0;
1389 for (unsigned int i = 0; i < vin.size(); i++)
1391 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1392 if (prevout.scriptPubKey.IsPayToScriptHash())
1393 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1398 bool CScriptCheck::operator()() const {
1399 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1400 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1401 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1405 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1407 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1410 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1411 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1413 // Take over previous transactions' spent pointers
1414 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1415 // fMiner is true when called from the internal bitcoin miner
1416 // ... both are false when called from CTransaction::AcceptToMemoryPool
1420 int64_t nValueIn = 0;
1422 for (unsigned int i = 0; i < vin.size(); i++)
1424 auto prevout = vin[i].prevout;
1425 assert(inputs.count(prevout.hash) > 0);
1426 CTxIndex& txindex = inputs[prevout.hash].first;
1427 CTransaction& txPrev = inputs[prevout.hash].second;
1429 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1430 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()));
1432 // If prev is coinbase or coinstake, check that it's matured
1433 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1434 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1435 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1436 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1438 // ppcoin: check transaction timestamp
1439 if (txPrev.nTime > nTime)
1440 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1442 // Check for negative or overflow input values
1443 nValueIn += txPrev.vout[prevout.n].nValue;
1444 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1445 return DoS(100, error("ConnectInputs() : txin values out of range"));
1450 pvChecks->reserve(vin.size());
1452 // The first loop above does all the inexpensive checks.
1453 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1454 // Helps prevent CPU exhaustion attacks.
1455 for (unsigned int i = 0; i < vin.size(); i++)
1457 auto prevout = vin[i].prevout;
1458 assert(inputs.count(prevout.hash) > 0);
1459 CTxIndex& txindex = inputs[prevout.hash].first;
1460 CTransaction& txPrev = inputs[prevout.hash].second;
1462 // Check for conflicts (double-spend)
1463 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1464 // for an attacker to attempt to split the network.
1465 if (!txindex.vSpent[prevout.n].IsNull())
1466 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());
1468 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1469 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1470 // still computed and checked, and any change will be caught at the next checkpoint.
1474 CScriptCheck check(txPrev, *this, i, flags, 0);
1477 pvChecks->push_back(CScriptCheck());
1478 check.swap(pvChecks->back());
1482 if (flags & STRICT_FLAGS)
1484 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1485 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1487 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1489 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1493 // Mark outpoints as spent
1494 txindex.vSpent[prevout.n] = posThisTx;
1497 if (fBlock || fMiner)
1499 mapTestPool[prevout.hash] = txindex;
1505 if (nTime > Checkpoints::GetLastCheckpointTime())
1507 unsigned int nTxSize = GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
1509 // coin stake tx earns reward instead of paying fee
1511 if (!GetCoinAge(txdb, nCoinAge))
1512 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1514 auto nReward = GetValueOut() - nValueIn;
1515 auto nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1517 if (nReward > nCalculatedReward)
1518 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1523 if (nValueIn < GetValueOut())
1524 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1526 // Tally transaction fees
1527 auto nTxFee = nValueIn - GetValueOut();
1529 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1532 if (!MoneyRange(nFees))
1533 return DoS(100, error("ConnectInputs() : nFees out of range"));
1541 bool CTransaction::ClientConnectInputs()
1546 // Take over previous transactions' spent pointers
1549 int64_t nValueIn = 0;
1550 for (unsigned int i = 0; i < vin.size(); i++)
1552 // Get prev tx from single transactions in memory
1553 auto prevout = vin[i].prevout;
1554 if (!mempool.exists(prevout.hash))
1556 CTransaction& txPrev = mempool.lookup(prevout.hash);
1558 if (prevout.n >= txPrev.vout.size())
1562 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1563 return error("ClientConnectInputs() : VerifySignature failed");
1565 ///// this is redundant with the mempool.mapNextTx stuff,
1566 ///// not sure which I want to get rid of
1567 ///// this has to go away now that posNext is gone
1568 // // Check for conflicts
1569 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1570 // return error("ConnectInputs() : prev tx already used");
1572 // // Flag outpoints as used
1573 // txPrev.vout[prevout.n].posNext = posThisTx;
1575 nValueIn += txPrev.vout[prevout.n].nValue;
1577 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1578 return error("ClientConnectInputs() : txin values out of range");
1580 if (GetValueOut() > nValueIn)
1590 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1592 // Disconnect in reverse order
1593 for (int i = vtx.size()-1; i >= 0; i--)
1594 if (!vtx[i].DisconnectInputs(txdb))
1597 // Update block index on disk without changing it in memory.
1598 // The memory index structure will be changed after the db commits.
1601 CDiskBlockIndex blockindexPrev(pindex->pprev);
1602 blockindexPrev.hashNext = 0;
1603 if (!txdb.WriteBlockIndex(blockindexPrev))
1604 return error("DisconnectBlock() : WriteBlockIndex failed");
1607 // ppcoin: clean up wallet after disconnecting coinstake
1608 for(CTransaction& tx : vtx)
1609 SyncWithWallets(tx, this, false, false);
1614 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1616 void ThreadScriptCheck(void*) {
1617 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1618 RenameThread("novacoin-scriptch");
1619 scriptcheckqueue.Thread();
1620 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1623 void ThreadScriptCheckQuit() {
1624 scriptcheckqueue.Quit();
1627 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1629 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1630 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1633 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1634 // unless those are already completely spent.
1635 // If such overwrites are allowed, coinbases and transactions depending upon those
1636 // can be duplicated to remove the ability to spend the first instance -- even after
1637 // being sent to another address.
1638 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1639 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1640 // already refuses previously-known transaction ids entirely.
1641 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1642 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1643 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1644 // initial block download.
1645 bool fEnforceBIP30 = true; // Always active in NovaCoin
1646 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1648 //// issue here: it doesn't know the version
1649 unsigned int nTxPos;
1651 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1652 // 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
1655 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1657 map<uint256, CTxIndex> mapQueuedChanges;
1658 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1661 int64_t nValueIn = 0;
1662 int64_t nValueOut = 0;
1663 unsigned int nSigOps = 0;
1666 auto hashTx = tx.GetHash();
1668 if (fEnforceBIP30) {
1669 CTxIndex txindexOld;
1670 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1671 for(CDiskTxPos &pos : txindexOld.vSpent)
1677 nSigOps += tx.GetLegacySigOpCount();
1678 if (nSigOps > MAX_BLOCK_SIGOPS)
1679 return DoS(100, error("ConnectBlock() : too many sigops"));
1681 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1683 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1685 MapPrevTx mapInputs;
1686 if (tx.IsCoinBase())
1687 nValueOut += tx.GetValueOut();
1691 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1694 // Add in sigops done by pay-to-script-hash inputs;
1695 // this is to prevent a "rogue miner" from creating
1696 // an incredibly-expensive-to-validate block.
1697 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1698 if (nSigOps > MAX_BLOCK_SIGOPS)
1699 return DoS(100, error("ConnectBlock() : too many sigops"));
1701 auto nTxValueIn = tx.GetValueIn(mapInputs);
1702 auto nTxValueOut = tx.GetValueOut();
1703 nValueIn += nTxValueIn;
1704 nValueOut += nTxValueOut;
1705 if (!tx.IsCoinStake())
1706 nFees += nTxValueIn - nTxValueOut;
1708 unsigned int nFlags = SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH;
1710 if (tx.nTime >= CHECKLOCKTIMEVERIFY_SWITCH_TIME) {
1711 nFlags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1712 // OP_CHECKSEQUENCEVERIFY is senseless without BIP68, so we're going disable it for now.
1713 // nFlags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1716 std::vector<CScriptCheck> vChecks;
1717 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, nFlags, nScriptCheckThreads ? &vChecks : NULL))
1719 control.Add(vChecks);
1722 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1725 if (!control.Wait())
1726 return DoS(100, false);
1728 if (IsProofOfWork())
1730 auto nBlockReward = GetProofOfWorkReward(nBits, nFees);
1732 // Check coinbase reward
1733 if (vtx[0].GetValueOut() > nBlockReward)
1734 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1735 vtx[0].GetValueOut(),
1739 // track money supply and mint amount info
1740 pindex->nMint = nValueOut - nValueIn + nFees;
1741 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1742 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1743 return error("Connect() : WriteBlockIndex for pindex failed");
1745 // fees are not collected by proof-of-stake miners
1746 // fees are destroyed to compensate the entire network
1747 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1748 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
1753 // Write queued txindex changes
1754 for (auto mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1756 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1757 return error("ConnectBlock() : UpdateTxIndex failed");
1760 // Update block index on disk without changing it in memory.
1761 // The memory index structure will be changed after the db commits.
1764 CDiskBlockIndex blockindexPrev(pindex->pprev);
1765 blockindexPrev.hashNext = pindex->GetBlockHash();
1766 if (!txdb.WriteBlockIndex(blockindexPrev))
1767 return error("ConnectBlock() : WriteBlockIndex failed");
1770 // Watch for transactions paying to me
1771 for(CTransaction& tx : vtx)
1772 SyncWithWallets(tx, this, true);
1778 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1780 printf("REORGANIZE\n");
1783 CBlockIndex* pfork = pindexBest;
1784 CBlockIndex* plonger = pindexNew;
1785 while (pfork != plonger)
1787 while (plonger->nHeight > pfork->nHeight)
1788 if ((plonger = plonger->pprev) == NULL)
1789 return error("Reorganize() : plonger->pprev is null");
1790 if (pfork == plonger)
1792 if ((pfork = pfork->pprev) == NULL)
1793 return error("Reorganize() : pfork->pprev is null");
1796 // List of what to disconnect
1797 vector<CBlockIndex*> vDisconnect;
1798 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1799 vDisconnect.push_back(pindex);
1801 // List of what to connect
1802 vector<CBlockIndex*> vConnect;
1803 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1804 vConnect.push_back(pindex);
1805 reverse(vConnect.begin(), vConnect.end());
1807 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());
1808 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());
1810 // Disconnect shorter branch
1811 vector<CTransaction> vResurrect;
1812 for(CBlockIndex* pindex : vDisconnect)
1815 if (!block.ReadFromDisk(pindex))
1816 return error("Reorganize() : ReadFromDisk for disconnect failed");
1817 if (!block.DisconnectBlock(txdb, pindex))
1818 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1820 // Queue memory transactions to resurrect
1821 for(const CTransaction& tx : block.vtx)
1822 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1823 vResurrect.push_back(tx);
1826 // Connect longer branch
1827 vector<CTransaction> vDelete;
1828 for (unsigned int i = 0; i < vConnect.size(); i++)
1830 CBlockIndex* pindex = vConnect[i];
1832 if (!block.ReadFromDisk(pindex))
1833 return error("Reorganize() : ReadFromDisk for connect failed");
1834 if (!block.ConnectBlock(txdb, pindex))
1837 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1840 // Queue memory transactions to delete
1841 for(const CTransaction& tx : block.vtx)
1842 vDelete.push_back(tx);
1844 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1845 return error("Reorganize() : WriteHashBestChain failed");
1847 // Make sure it's successfully written to disk before changing memory structure
1848 if (!txdb.TxnCommit())
1849 return error("Reorganize() : TxnCommit failed");
1851 // Disconnect shorter branch
1852 for(CBlockIndex* pindex : vDisconnect)
1854 pindex->pprev->pnext = NULL;
1856 // Connect longer branch
1857 for(CBlockIndex* pindex : vConnect)
1859 pindex->pprev->pnext = pindex;
1861 // Resurrect memory transactions that were in the disconnected branch
1862 for(CTransaction& tx : vResurrect)
1863 tx.AcceptToMemoryPool(txdb, false);
1865 // Delete redundant memory transactions that are in the connected branch
1866 for(CTransaction& tx : vDelete)
1869 printf("REORGANIZE: done\n");
1875 // Called from inside SetBestChain: attaches a block to the new best chain being built
1876 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1878 auto hash = GetHash();
1880 // Adding to current best branch
1881 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1884 InvalidChainFound(pindexNew);
1887 if (!txdb.TxnCommit())
1888 return error("SetBestChain() : TxnCommit failed");
1890 // Add to current best branch
1891 pindexNew->pprev->pnext = pindexNew;
1893 // Delete redundant memory transactions
1894 for(CTransaction& tx : vtx)
1900 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1902 auto hash = GetHash();
1904 if (!txdb.TxnBegin())
1905 return error("SetBestChain() : TxnBegin failed");
1907 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1909 txdb.WriteHashBestChain(hash);
1910 if (!txdb.TxnCommit())
1911 return error("SetBestChain() : TxnCommit failed");
1912 pindexGenesisBlock = pindexNew;
1914 else if (hashPrevBlock == hashBestChain)
1916 if (!SetBestChainInner(txdb, pindexNew))
1917 return error("SetBestChain() : SetBestChainInner failed");
1921 // the first block in the new chain that will cause it to become the new best chain
1922 CBlockIndex *pindexIntermediate = pindexNew;
1924 // list of blocks that need to be connected afterwards
1925 std::vector<CBlockIndex*> vpindexSecondary;
1927 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1928 // Try to limit how much needs to be done inside
1929 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1931 vpindexSecondary.push_back(pindexIntermediate);
1932 pindexIntermediate = pindexIntermediate->pprev;
1935 if (!vpindexSecondary.empty())
1936 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
1938 // Switch to new best branch
1939 if (!Reorganize(txdb, pindexIntermediate))
1942 InvalidChainFound(pindexNew);
1943 return error("SetBestChain() : Reorganize failed");
1946 // Connect further blocks
1947 for (std::vector<CBlockIndex*>::reverse_iterator rit = vpindexSecondary.rbegin(); rit != vpindexSecondary.rend(); ++rit)
1950 if (!block.ReadFromDisk(*rit))
1952 printf("SetBestChain() : ReadFromDisk failed\n");
1955 if (!txdb.TxnBegin()) {
1956 printf("SetBestChain() : TxnBegin 2 failed\n");
1959 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1960 if (!block.SetBestChainInner(txdb, *rit))
1965 // Update best block in wallet (so we can detect restored wallets)
1966 bool fIsInitialDownload = IsInitialBlockDownload();
1967 if (!fIsInitialDownload)
1969 const CBlockLocator locator(pindexNew);
1970 ::SetBestChain(locator);
1974 hashBestChain = hash;
1975 pindexBest = pindexNew;
1976 pblockindexFBBHLast = NULL;
1977 nBestHeight = pindexBest->nHeight;
1978 nBestChainTrust = pindexNew->nChainTrust;
1979 nTimeBestReceived = GetTime();
1980 nTransactionsUpdated++;
1982 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1984 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1985 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1986 CBigNum(nBestChainTrust).ToString().c_str(),
1987 nBestBlockTrust.Get64(),
1988 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1990 // Check the version of the last 100 blocks to see if we need to upgrade:
1991 if (!fIsInitialDownload)
1994 const CBlockIndex* pindex = pindexBest;
1995 for (int i = 0; i < 100 && pindex != NULL; i++)
1997 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1999 pindex = pindex->pprev;
2002 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2003 if (nUpgraded > 100/2)
2004 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2005 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2008 auto strCmd = GetArg("-blocknotify", "");
2010 if (!fIsInitialDownload && !strCmd.empty())
2012 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
2013 boost::thread t(runCommand, strCmd); // thread runs free
2019 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2020 // Only those coins meeting minimum age requirement counts. As those
2021 // transactions not in main chain are not currently indexed so we
2022 // might not find out about their coin age. Older transactions are
2023 // guaranteed to be in main chain by sync-checkpoint. This rule is
2024 // introduced to help nodes establish a consistent view of the coin
2025 // age (trust score) of competing branches.
2026 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2028 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2034 for(const CTxIn& txin : vin)
2036 // First try finding the previous transaction in database
2037 CTransaction txPrev;
2039 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2040 continue; // previous transaction not in main chain
2041 if (nTime < txPrev.nTime)
2042 return false; // Transaction timestamp violation
2044 // Read block header
2046 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2047 return false; // unable to read block of previous transaction
2048 if (block.GetBlockTime() + nStakeMinAge > nTime)
2049 continue; // only count coins meeting min age requirement
2051 auto nValueIn = txPrev.vout[txin.prevout.n].nValue;
2052 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2054 if (fDebug && GetBoolArg("-printcoinage"))
2055 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2058 auto bnCoinDay = bnCentSecond * CENT / COIN / nOneDay;
2059 if (fDebug && GetBoolArg("-printcoinage"))
2060 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2061 nCoinAge = bnCoinDay.getuint64();
2065 // ppcoin: total coin age spent in block, in the unit of coin-days.
2066 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2071 for(const CTransaction& tx : vtx)
2073 uint64_t nTxCoinAge;
2074 if (tx.GetCoinAge(txdb, nTxCoinAge))
2075 nCoinAge += nTxCoinAge;
2080 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2082 if (fDebug && GetBoolArg("-printcoinage"))
2083 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2087 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2089 // Check for duplicate
2090 auto hash = GetHash();
2091 if (mapBlockIndex.count(hash))
2092 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2094 // Construct new block index object
2095 CBlockIndex* pindexNew = new(nothrow) CBlockIndex(nFile, nBlockPos, *this);
2097 return error("AddToBlockIndex() : new CBlockIndex failed");
2098 pindexNew->phashBlock = &hash;
2099 auto miPrev = mapBlockIndex.find(hashPrevBlock);
2100 if (miPrev != mapBlockIndex.end())
2102 pindexNew->pprev = (*miPrev).second;
2103 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2106 // ppcoin: compute chain trust score
2107 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2109 // ppcoin: compute stake entropy bit for stake modifier
2110 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2111 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2113 // ppcoin: record proof-of-stake hash value
2114 if (pindexNew->IsProofOfStake())
2116 if (!mapProofOfStake.count(hash))
2117 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2118 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2121 // ppcoin: compute stake modifier
2122 uint64_t nStakeModifier = 0;
2123 bool fGeneratedStakeModifier = false;
2124 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2125 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2126 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2127 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2128 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2129 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2131 // Add to mapBlockIndex
2132 auto mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2133 if (pindexNew->IsProofOfStake())
2134 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2135 pindexNew->phashBlock = &((*mi).first);
2137 // Write to disk block index
2139 if (!txdb.TxnBegin())
2141 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2142 if (!txdb.TxnCommit())
2146 if (pindexNew->nChainTrust > nBestChainTrust)
2147 if (!SetBestChain(txdb, pindexNew))
2150 if (pindexNew == pindexBest)
2152 // Notify UI to display prev block's coinbase if it was ours
2153 static uint256 hashPrevBestCoinBase;
2154 UpdatedTransaction(hashPrevBestCoinBase);
2155 hashPrevBestCoinBase = vtx[0].GetHash();
2158 static int8_t counter = 0;
2159 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2160 uiInterface.NotifyBlocksChanged();
2167 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2169 // These are checks that are independent of context
2170 // that can be verified before saving an orphan block.
2172 set<uint256> uniqueTx; // tx hashes
2173 unsigned int nSigOps = 0; // total sigops
2176 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2177 return DoS(100, error("CheckBlock() : size limits failed"));
2179 bool fProofOfStake = IsProofOfStake();
2181 // First transaction must be coinbase, the rest must not be
2182 if (!vtx[0].IsCoinBase())
2183 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2185 if (!vtx[0].CheckTransaction())
2186 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2188 uniqueTx.insert(vtx[0].GetHash());
2189 nSigOps += vtx[0].GetLegacySigOpCount();
2193 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2194 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2196 // nNonce must be zero for proof-of-stake blocks
2198 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2200 // Coinbase output should be empty if proof-of-stake block
2201 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2202 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2204 // Check coinstake timestamp
2205 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2206 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2208 // NovaCoin: check proof-of-stake block signature
2209 if (fCheckSig && !CheckBlockSignature())
2210 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2212 if (!vtx[1].CheckTransaction())
2213 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2215 uniqueTx.insert(vtx[1].GetHash());
2216 nSigOps += vtx[1].GetLegacySigOpCount();
2220 // Check proof of work matches claimed amount
2221 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2222 return DoS(50, error("CheckBlock() : proof of work failed"));
2225 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2226 return error("CheckBlock() : block timestamp too far in the future");
2228 // Check coinbase timestamp
2229 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2230 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2233 // Iterate all transactions starting from second for proof-of-stake block
2234 // or first for proof-of-work block
2235 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2237 const CTransaction& tx = vtx[i];
2239 // Reject coinbase transactions at non-zero index
2240 if (tx.IsCoinBase())
2241 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2243 // Reject coinstake transactions at index != 1
2244 if (tx.IsCoinStake())
2245 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2247 // Check transaction timestamp
2248 if (GetBlockTime() < (int64_t)tx.nTime)
2249 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2251 // Check transaction consistency
2252 if (!tx.CheckTransaction())
2253 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2255 // Add transaction hash into list of unique transaction IDs
2256 uniqueTx.insert(tx.GetHash());
2258 // Calculate sigops count
2259 nSigOps += tx.GetLegacySigOpCount();
2262 // Check for duplicate txids. This is caught by ConnectInputs(),
2263 // but catching it earlier avoids a potential DoS attack:
2264 if (uniqueTx.size() != vtx.size())
2265 return DoS(100, error("CheckBlock() : duplicate transaction"));
2267 // Reject block if validation would consume too much resources.
2268 if (nSigOps > MAX_BLOCK_SIGOPS)
2269 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2271 // Check merkle root
2272 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2273 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2278 bool CBlock::AcceptBlock()
2280 // Check for duplicate
2281 auto hash = GetHash();
2282 if (mapBlockIndex.count(hash))
2283 return error("AcceptBlock() : block already in mapBlockIndex");
2285 // Get prev block index
2286 auto mi = mapBlockIndex.find(hashPrevBlock);
2287 if (mi == mapBlockIndex.end())
2288 return DoS(10, error("AcceptBlock() : prev block not found"));
2289 CBlockIndex* pindexPrev = (*mi).second;
2290 int nHeight = pindexPrev->nHeight+1;
2292 // Check proof-of-work or proof-of-stake
2293 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2294 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2296 int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
2297 int nMaxOffset = 12 * nOneHour; // 12 hours
2298 if (fTestNet || pindexPrev->nTime < 1450569600)
2299 nMaxOffset = 7 * nOneWeek; // One week (permanently on testNet or until 20 Dec, 2015 on mainNet)
2301 // Check timestamp against prev
2302 if (GetBlockTime() <= nMedianTimePast || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2303 return error("AcceptBlock() : block's timestamp is too early");
2305 // Don't accept blocks with future timestamps
2306 if (pindexPrev->nHeight > 1 && nMedianTimePast + nMaxOffset < GetBlockTime())
2307 return error("AcceptBlock() : block's timestamp is too far in the future");
2309 // Check that all transactions are finalized
2310 for(const CTransaction& tx : vtx)
2311 if (!tx.IsFinal(nHeight, GetBlockTime()))
2312 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2314 // Check that the block chain matches the known block chain up to a checkpoint
2315 if (!Checkpoints::CheckHardened(nHeight, hash))
2316 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2318 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2320 // Check that the block satisfies synchronized checkpoint
2321 if (CheckpointsMode == Checkpoints::CP_STRICT && !cpSatisfies)
2322 return error("AcceptBlock() : rejected by synchronized checkpoint");
2324 if (CheckpointsMode == Checkpoints::CP_ADVISORY && !cpSatisfies)
2325 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2327 // Enforce rule that the coinbase starts with serialized block height
2328 auto expect = CScript() << nHeight;
2329 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2330 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2331 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2333 // Write block to history file
2334 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2335 return error("AcceptBlock() : out of disk space");
2336 unsigned int nFile = std::numeric_limits<unsigned int>::max();
2337 unsigned int nBlockPos = 0;
2338 if (!WriteToDisk(nFile, nBlockPos))
2339 return error("AcceptBlock() : WriteToDisk failed");
2340 if (!AddToBlockIndex(nFile, nBlockPos))
2341 return error("AcceptBlock() : AddToBlockIndex failed");
2343 // Relay inventory, but don't relay old inventory during initial block download
2344 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2345 if (hashBestChain == hash)
2348 for(CNode* pnode : vNodes)
2349 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2350 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2353 // ppcoin: check pending sync-checkpoint
2354 Checkpoints::AcceptPendingSyncCheckpoint();
2359 uint256 CBlockIndex::GetBlockTrust() const
2362 bnTarget.SetCompact(nBits);
2367 // Return 1 for the first 12 blocks
2368 if (pprev == NULL || pprev->nHeight < 12)
2371 const CBlockIndex* currentIndex = pprev;
2373 if(IsProofOfStake())
2375 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2377 // Return 1/3 of score if parent block is not the PoW block
2378 if (!pprev->IsProofOfWork())
2379 return (bnNewTrust / 3).getuint256();
2383 // Check last 12 blocks type
2384 while (pprev->nHeight - currentIndex->nHeight < 12)
2386 if (currentIndex->IsProofOfWork())
2388 currentIndex = currentIndex->pprev;
2391 // Return 1/3 of score if less than 3 PoW blocks found
2393 return (bnNewTrust / 3).getuint256();
2395 return bnNewTrust.getuint256();
2399 // Calculate work amount for block
2400 CBigNum bnPoWTrust = CBigNum(nPoWBase) / (bnTarget+1);
2402 // Set nPowTrust to 1 if PoW difficulty is too low
2406 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2408 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2409 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2410 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2414 // Check last 12 blocks type
2415 while (pprev->nHeight - currentIndex->nHeight < 12)
2417 if (currentIndex->IsProofOfStake())
2419 currentIndex = currentIndex->pprev;
2422 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2424 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2426 bnTarget.SetCompact(pprev->nBits);
2431 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2433 // Return nPoWTrust + full trust score for previous block nBits
2434 return (bnPoWTrust + bnNewTrust).getuint256();
2438 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2440 unsigned int nFound = 0;
2441 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2443 if (pstart->nVersion >= minVersion)
2445 pstart = pstart->pprev;
2447 return (nFound >= nRequired);
2450 bool static ReserealizeBlockSignature(CBlock* pblock)
2452 if (pblock->IsProofOfWork())
2454 pblock->vchBlockSig.clear();
2458 return CPubKey::ReserealizeSignature(pblock->vchBlockSig);
2461 bool static IsCanonicalBlockSignature(CBlock* pblock)
2463 if (pblock->IsProofOfWork())
2464 return pblock->vchBlockSig.empty();
2466 return IsDERSignature(pblock->vchBlockSig);
2469 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2471 // Check for duplicate
2472 auto hash = pblock->GetHash();
2473 if (mapBlockIndex.count(hash))
2474 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2475 if (mapOrphanBlocks.count(hash))
2476 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2478 // Check that block isn't listed as unconditionally banned.
2479 if (!Checkpoints::CheckBanned(hash)) {
2481 pfrom->Misbehaving(100);
2482 return error("ProcessBlock() : block %s is rejected by hard-coded banlist", hash.GetHex().substr(0,20).c_str());
2485 // Check proof-of-stake
2486 // Limited duplicity on stake: prevents block flood attack
2487 // Duplicate stake allowed only when there is orphan child block
2488 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2489 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());
2491 // Strip the garbage from newly received blocks, if we found some
2492 if (!IsCanonicalBlockSignature(pblock)) {
2493 if (!ReserealizeBlockSignature(pblock))
2494 printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2497 // Preliminary checks
2498 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2499 return error("ProcessBlock() : CheckBlock FAILED");
2501 // ppcoin: verify hash target and signature of coinstake tx
2502 if (pblock->IsProofOfStake())
2504 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2505 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2507 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2508 return false; // do not error here as we expect this during initial block download
2510 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2511 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2514 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2515 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2517 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2518 auto deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2520 bnNewBlock.SetCompact(pblock->nBits);
2523 if (pblock->IsProofOfStake())
2524 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2526 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2528 if (bnNewBlock > bnRequired)
2531 pfrom->Misbehaving(100);
2532 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2536 // ppcoin: ask for pending sync-checkpoint if any
2537 if (!IsInitialBlockDownload())
2538 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2540 // If don't already have its previous block, shunt it off to holding area until we get it
2541 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2543 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2544 // ppcoin: check proof-of-stake
2545 if (pblock->IsProofOfStake())
2547 // Limited duplicity on stake: prevents block flood attack
2548 // Duplicate stake allowed only when there is orphan child block
2549 if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2550 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());
2552 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2554 CBlock* pblock2 = new CBlock(*pblock);
2555 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2556 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2558 // Ask this guy to fill in what we're missing
2561 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2562 // ppcoin: getblocks may not obtain the ancestor block rejected
2563 // earlier by duplicate-stake check so we ask for it again directly
2564 if (!IsInitialBlockDownload())
2565 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2571 if (!pblock->AcceptBlock())
2572 return error("ProcessBlock() : AcceptBlock FAILED");
2574 // Recursively process any orphan blocks that depended on this one
2575 vector<uint256> vWorkQueue;
2576 vWorkQueue.push_back(hash);
2577 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2579 auto hashPrev = vWorkQueue[i];
2580 for (auto mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2581 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2584 CBlock* pblockOrphan = (*mi).second;
2585 if (pblockOrphan->AcceptBlock())
2586 vWorkQueue.push_back(pblockOrphan->GetHash());
2587 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2588 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2589 delete pblockOrphan;
2591 mapOrphanBlocksByPrev.erase(hashPrev);
2594 printf("ProcessBlock: ACCEPTED\n");
2596 // ppcoin: if responsible for sync-checkpoint send it
2597 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2598 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2603 // ppcoin: check block signature
2604 bool CBlock::CheckBlockSignature() const
2606 if (vchBlockSig.empty())
2609 txnouttype whichType;
2610 vector<valtype> vSolutions;
2611 if (!Solver(vtx[1].vout[1].scriptPubKey, whichType, vSolutions))
2614 if (whichType == TX_PUBKEY)
2616 auto& vchPubKey = vSolutions[0];
2617 CPubKey key(vchPubKey);
2620 return key.Verify(GetHash(), vchBlockSig);
2626 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2628 uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2630 // Check for nMinDiskSpace bytes (currently 50MB)
2631 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2634 string strMessage = _("Warning: Disk space is low!");
2635 strMiscWarning = strMessage;
2636 printf("*** %s\n", strMessage.c_str());
2637 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2644 static filesystem::path BlockFilePath(unsigned int nFile)
2646 string strBlockFn = strprintf("blk%04u.dat", nFile);
2647 return GetDataDir() / strBlockFn;
2650 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2652 if ((nFile < 1) || (nFile == std::numeric_limits<uint32_t>::max()))
2654 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2657 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2659 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2668 static unsigned int nCurrentBlockFile = 1;
2670 FILE* AppendBlockFile(unsigned int& nFileRet)
2675 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2678 if (fseek(file, 0, SEEK_END) != 0)
2680 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2681 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2683 nFileRet = nCurrentBlockFile;
2687 nCurrentBlockFile++;
2691 void UnloadBlockIndex()
2693 mapBlockIndex.clear();
2694 setStakeSeen.clear();
2695 pindexGenesisBlock = NULL;
2697 nBestChainTrust = 0;
2698 nBestInvalidTrust = 0;
2703 bool LoadBlockIndex(bool fAllowNew)
2707 nNetworkID = 0xefc0f2cd;
2709 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2710 nStakeMinAge = 2 * nOneHour; // test net min age is 2 hours
2711 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2712 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2713 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2720 if (!txdb.LoadBlockIndex())
2724 // Init with genesis block
2726 if (mapBlockIndex.empty())
2735 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2736 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2737 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2739 // vMerkleTree: 4cb33b3b6a
2743 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2744 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2745 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2747 // vMerkleTree: 4cb33b3b6a
2749 const string strTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2751 txNew.nTime = 1360105017;
2752 txNew.vin.resize(1);
2753 txNew.vout.resize(1);
2754 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>(strTimestamp.begin(), strTimestamp.end());
2755 txNew.vout[0].SetEmpty();
2757 block.vtx.push_back(txNew);
2758 block.hashPrevBlock = 0;
2759 block.hashMerkleRoot = block.BuildMerkleTree();
2761 block.nTime = 1360105017;
2762 block.nBits = bnProofOfWorkLimit.GetCompact();
2763 block.nNonce = !fTestNet ? 1575379 : 46534;
2766 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2768 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2769 assert(block.CheckBlock());
2771 // Start new block file
2773 unsigned int nBlockPos;
2774 if (!block.WriteToDisk(nFile, nBlockPos))
2775 return error("LoadBlockIndex() : writing genesis block to disk failed");
2776 if (!block.AddToBlockIndex(nFile, nBlockPos))
2777 return error("LoadBlockIndex() : genesis block not accepted");
2779 // initialize synchronized checkpoint
2780 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2781 return error("LoadBlockIndex() : failed to init sync checkpoint");
2783 // upgrade time set to zero if txdb initialized
2785 if (!txdb.WriteModifierUpgradeTime(0))
2786 return error("LoadBlockIndex() : failed to init upgrade info");
2787 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2793 string strPubKey = "";
2794 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2796 // write checkpoint master key to db
2798 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2799 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2800 if (!txdb.TxnCommit())
2801 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2802 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2803 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2806 // upgrade time set to zero if blocktreedb initialized
2807 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2809 if (nModifierUpgradeTime)
2810 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2812 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2816 nModifierUpgradeTime = GetTime();
2817 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2818 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2819 return error("LoadBlockIndex() : failed to write upgrade info");
2832 void PrintBlockTree()
2834 // pre-compute tree structure
2835 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2836 for (auto mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2838 CBlockIndex* pindex = (*mi).second;
2839 mapNext[pindex->pprev].push_back(pindex);
2841 //while (rand() % 3 == 0)
2842 // mapNext[pindex->pprev].push_back(pindex);
2845 vector<pair<int, CBlockIndex*> > vStack;
2846 vStack.push_back(make_pair(0, pindexGenesisBlock));
2849 while (!vStack.empty())
2851 int nCol = vStack.back().first;
2852 CBlockIndex* pindex = vStack.back().second;
2855 // print split or gap
2856 if (nCol > nPrevCol)
2858 for (int i = 0; i < nCol-1; i++)
2862 else if (nCol < nPrevCol)
2864 for (int i = 0; i < nCol; i++)
2871 for (int i = 0; i < nCol; i++)
2876 block.ReadFromDisk(pindex);
2877 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
2881 block.GetHash().ToString().c_str(),
2883 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2884 FormatMoney(pindex->nMint).c_str(),
2887 PrintWallets(block);
2889 // put the main time-chain first
2890 vector<CBlockIndex*>& vNext = mapNext[pindex];
2891 for (unsigned int i = 0; i < vNext.size(); i++)
2893 if (vNext[i]->pnext)
2895 swap(vNext[0], vNext[i]);
2901 for (unsigned int i = 0; i < vNext.size(); i++)
2902 vStack.push_back(make_pair(nCol+i, vNext[i]));
2906 bool LoadExternalBlockFile(FILE* fileIn, CClientUIInterface& uiInterface)
2908 auto nStart = GetTimeMillis();
2909 vector<uint8_t> pchData(10 * (8+MAX_BLOCK_SIZE));
2910 int32_t nLoaded = 0;
2914 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2916 while (nPos != std::numeric_limits<uint32_t>::max() && blkdat.good() && !fRequestShutdown)
2920 fseek(blkdat, nPos, SEEK_SET);
2921 auto nRead = fread(&pchData[0], 1, pchData.size(), blkdat);
2924 nPos = numeric_limits<uint32_t>::max();
2927 auto it = pchData.begin();
2928 while(it != pchData.end() && !fRequestShutdown)
2930 auto nBlockLength = *reinterpret_cast<const uint32_t*>(&(*(it+4)));
2931 auto SeekToNext = [&pchData, &it, &nPos, &nBlockLength]() {
2933 it = search(it+8, pchData.end(), BEGIN(nNetworkID), END(nNetworkID));
2934 if (it != pchData.end())
2935 nPos += (it - previt);
2937 if (nBlockLength > 0)
2939 if (nBlockLength > (uint32_t)distance(it, pchData.end()))
2942 break; // We've reached the end of buffer
2949 vector<unsigned char> vchBlockBytes(it+8, it+8+nBlockLength);
2950 CDataStream blockData(vchBlockBytes, SER_NETWORK, PROTOCOL_VERSION);
2953 catch (const std::exception&)
2955 printf("LoadExternalBlockFile() : Deserialize error caught at the position %" PRIu32 ", this block may be truncated.", nPos);
2959 if (ProcessBlock(NULL, &block))
2961 advance(it, 8 + nBlockLength);
2962 nPos += (8 + nBlockLength);
2964 static int64_t nLastUpdate = 0;
2965 if (GetTimeMillis() - nLastUpdate > 1000)
2967 uiInterface.InitMessage(strprintf(_("%" PRId32 " blocks were read."), nLoaded));
2968 nLastUpdate = GetTimeMillis();
2979 while(!fRequestShutdown);
2982 catch (const std::exception&) {
2983 printf("%s() : I/O error caught during load\n",
2984 BOOST_CURRENT_FUNCTION);
2987 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
2991 //////////////////////////////////////////////////////////////////////////////
2996 extern map<uint256, CAlert> mapAlerts;
2997 extern CCriticalSection cs_mapAlerts;
2999 string GetWarnings(string strFor)
3002 string strStatusBar;
3005 if (GetBoolArg("-testsafemode"))
3008 // Misc warnings like out of disk space and clock is wrong
3009 if (!strMiscWarning.empty())
3012 strStatusBar = strMiscWarning;
3015 // if detected unmet upgrade requirement enter safe mode
3016 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3017 if (IsFixedModifierInterval(nModifierUpgradeTime + nOneDay)) // 1 day margin
3020 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3023 // if detected invalid checkpoint enter safe mode
3024 if (Checkpoints::hashInvalidCheckpoint != 0)
3027 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3033 for(auto& item : mapAlerts)
3035 const CAlert& alert = item.second;
3036 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3038 nPriority = alert.nPriority;
3039 strStatusBar = alert.strStatusBar;
3040 if (nPriority > 1000)
3041 strRPC = strStatusBar;
3046 if (strFor == "statusbar")
3047 return strStatusBar;
3048 else if (strFor == "rpc")
3050 assert(!"GetWarnings() : invalid parameter");
3061 //////////////////////////////////////////////////////////////////////////////
3067 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3069 int nType = inv.GetType();
3070 auto nHash = inv.GetHash();
3076 bool txInMap = false;
3079 txInMap = (mempool.exists(nHash));
3082 mapOrphanTransactions.count(nHash) ||
3083 txdb.ContainsTx(nHash);
3087 return mapBlockIndex.count(nHash) ||
3088 mapOrphanBlocks.count(nHash);
3090 // Don't know what it is, just say we already got one
3094 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3096 static map<CService, CPubKey> mapReuseKey;
3097 RandAddSeedPerfmon();
3099 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3100 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3102 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3106 if (strCommand == "version")
3108 // Each connection can only send one version message
3109 if (pfrom->nVersion != 0)
3111 pfrom->Misbehaving(1);
3118 uint64_t nNonce = 1;
3119 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3120 if (pfrom->nVersion < MIN_PROTO_VERSION)
3122 // Since February 20, 2012, the protocol is initiated at version 209,
3123 // and earlier versions are no longer supported
3124 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3125 pfrom->fDisconnect = true;
3129 if (pfrom->nVersion == 10300)
3130 pfrom->nVersion = 300;
3132 vRecv >> addrFrom >> nNonce;
3134 vRecv >> pfrom->strSubVer;
3136 vRecv >> pfrom->nStartingHeight;
3138 if (pfrom->fInbound && addrMe.IsRoutable())
3140 pfrom->addrLocal = addrMe;
3144 // Disconnect if we connected to ourself
3145 if (nNonce == nLocalHostNonce && nNonce > 1)
3147 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3148 pfrom->fDisconnect = true;
3152 if (pfrom->nVersion < 60010)
3154 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3155 pfrom->fDisconnect = true;
3159 // record my external IP reported by peer
3160 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3161 addrSeenByPeer = addrMe;
3163 // Be shy and don't send version until we hear
3164 if (pfrom->fInbound)
3165 pfrom->PushVersion();
3167 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3169 AddTimeData(pfrom->addr, nTime);
3172 pfrom->PushMessage("verack");
3173 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3175 if (!pfrom->fInbound)
3177 // Advertise our address
3178 if (!fNoListen && !IsInitialBlockDownload())
3180 auto addr = GetLocalAddress(&pfrom->addr);
3181 if (addr.IsRoutable())
3182 pfrom->PushAddress(addr);
3185 // Get recent addresses
3186 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3188 pfrom->PushMessage("getaddr");
3189 pfrom->fGetAddr = true;
3191 addrman.Good(pfrom->addr);
3193 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3195 addrman.Add(addrFrom, addrFrom);
3196 addrman.Good(addrFrom);
3200 // Ask the first connected node for block updates
3201 static int nAskedForBlocks = 0;
3202 if (!pfrom->fClient && !pfrom->fOneShot &&
3203 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3204 (pfrom->nVersion < NOBLKS_VERSION_START ||
3205 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3206 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3209 pfrom->PushGetBlocks(pindexBest, uint256(0));
3215 for(auto& item : mapAlerts)
3216 item.second.RelayTo(pfrom);
3219 // Relay sync-checkpoint
3221 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3222 if (!Checkpoints::checkpointMessage.IsNull())
3223 Checkpoints::checkpointMessage.RelayTo(pfrom);
3226 pfrom->fSuccessfullyConnected = true;
3228 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());
3230 cPeerBlockCounts.input(pfrom->nStartingHeight);
3232 // ppcoin: ask for pending sync-checkpoint if any
3233 if (!IsInitialBlockDownload())
3234 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3238 else if (pfrom->nVersion == 0)
3240 // Must have a version message before anything else
3241 pfrom->Misbehaving(1);
3246 else if (strCommand == "verack")
3248 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3252 else if (strCommand == "addr")
3254 vector<CAddress> vAddr;
3257 // Don't want addr from older versions unless seeding
3258 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3260 if (vAddr.size() > 1000)
3262 pfrom->Misbehaving(20);
3263 return error("message addr size() = %" PRIszu "", vAddr.size());
3266 // Store the new addresses
3267 vector<CAddress> vAddrOk;
3268 auto nNow = GetAdjustedTime();
3269 auto nSince = nNow - 10 * 60;
3270 for(CAddress& addr : vAddr)
3274 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3275 addr.nTime = nNow - 5 * nOneDay;
3276 pfrom->AddAddressKnown(addr);
3277 bool fReachable = IsReachable(addr);
3278 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3280 // Relay to a limited number of other nodes
3283 // Use deterministic randomness to send to the same nodes for 24 hours
3284 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3285 static uint256 hashSalt;
3287 hashSalt = GetRandHash();
3288 uint64_t hashAddr = addr.GetHash();
3289 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/nOneDay);
3290 hashRand = Hash(hashRand.begin(), hashRand.end());
3291 multimap<uint256, CNode*> mapMix;
3292 for(CNode* pnode : vNodes)
3294 if (pnode->nVersion < CADDR_TIME_VERSION)
3296 unsigned int nPointer;
3297 memcpy(&nPointer, &pnode, sizeof(nPointer));
3298 uint256 hashKey = hashRand ^ nPointer;
3299 hashKey = Hash(hashKey.begin(), hashKey.end());
3300 mapMix.insert(make_pair(hashKey, pnode));
3302 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3303 for (auto mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3304 ((*mi).second)->PushAddress(addr);
3307 // Do not store addresses outside our network
3309 vAddrOk.push_back(addr);
3311 addrman.Add(vAddrOk, pfrom->addr, 2 * nOneHour);
3312 if (vAddr.size() < 1000)
3313 pfrom->fGetAddr = false;
3314 if (pfrom->fOneShot)
3315 pfrom->fDisconnect = true;
3318 else if (strCommand == "inv")
3322 if (vInv.size() > MAX_INV_SZ)
3324 pfrom->Misbehaving(20);
3325 return error("message inv size() = %" PRIszu "", vInv.size());
3328 // find last block in inv vector
3329 int nLastBlock = -1;
3330 for (size_t nInv = 0; nInv < vInv.size(); nInv++) {
3331 if (vInv[vInv.size() - 1 - nInv].GetType() == MSG_BLOCK) {
3332 nLastBlock = (int) (vInv.size() - 1 - nInv);
3337 for (size_t nInv = 0; nInv < vInv.size(); nInv++)
3339 const CInv &inv = vInv[nInv];
3340 int nType = inv.GetType();
3341 auto nHash = inv.GetHash();
3345 pfrom->AddInventoryKnown(inv);
3347 bool fAlreadyHave = AlreadyHave(txdb, inv);
3349 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3353 else if (nType == MSG_BLOCK && mapOrphanBlocks.count(nHash)) {
3354 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[nHash]));
3355 } else if (nType == nLastBlock) {
3356 // In case we are on a very long side-chain, it is possible that we already have
3357 // the last block in an inv bundle sent in response to getblocks. Try to detect
3358 // this situation and push another getblocks to continue.
3359 pfrom->PushGetBlocks(mapBlockIndex[nHash], uint256(0));
3361 printf("force request: %s\n", inv.ToString().c_str());
3364 // Track requests for our stuff
3370 else if (strCommand == "getdata")
3374 if (vInv.size() > MAX_INV_SZ)
3376 pfrom->Misbehaving(20);
3377 return error("message getdata size() = %" PRIszu "", vInv.size());
3380 if (fDebugNet || (vInv.size() != 1))
3381 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3383 for(const CInv& inv : vInv)
3387 if (fDebugNet || (vInv.size() == 1))
3388 printf("received getdata for: %s\n", inv.ToString().c_str());
3390 int nType = inv.GetType();
3391 auto nHash = inv.GetHash();
3393 if (nType == MSG_BLOCK)
3395 // Send block from disk
3396 auto mi = mapBlockIndex.find(nHash);
3397 if (mi != mapBlockIndex.end())
3400 block.ReadFromDisk((*mi).second);
3401 pfrom->PushMessage("block", block);
3403 // Trigger them to send a getblocks request for the next batch of inventory
3404 if (nHash == pfrom->hashContinue)
3406 // ppcoin: send latest proof-of-work block to allow the
3407 // download node to accept as orphan (proof-of-stake
3408 // block might be rejected by stake connection check)
3410 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3411 pfrom->PushMessage("inv", vInv);
3412 pfrom->hashContinue = 0;
3416 else if (inv.IsKnownType())
3418 // Send stream from relay memory
3419 bool pushed = false;
3422 auto mi = mapRelay.find(inv);
3423 if (mi != mapRelay.end()) {
3424 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3428 if (!pushed && nType == MSG_TX) {
3430 if (mempool.exists(nHash)) {
3431 CTransaction tx = mempool.lookup(nHash);
3432 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3435 pfrom->PushMessage("tx", ss);
3440 // Track requests for our stuff
3446 else if (strCommand == "getblocks")
3448 CBlockLocator locator;
3450 vRecv >> locator >> hashStop;
3452 // Find the last block the caller has in the main chain
3453 CBlockIndex* pindex = locator.GetBlockIndex();
3455 // Send the rest of the chain
3457 pindex = pindex->pnext;
3459 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3460 for (; pindex; pindex = pindex->pnext)
3462 if (pindex->GetBlockHash() == hashStop)
3464 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3465 // ppcoin: tell downloading node about the latest block if it's
3466 // without risk being rejected due to stake connection check
3467 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3468 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3471 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3474 // When this block is requested, we'll send an inv that'll make them
3475 // getblocks the next batch of inventory.
3476 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3477 pfrom->hashContinue = pindex->GetBlockHash();
3482 else if (strCommand == "checkpoint")
3484 CSyncCheckpoint checkpoint;
3485 vRecv >> checkpoint;
3487 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3490 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3492 for(CNode* pnode : vNodes)
3493 checkpoint.RelayTo(pnode);
3497 else if (strCommand == "getheaders")
3499 CBlockLocator locator;
3501 vRecv >> locator >> hashStop;
3503 CBlockIndex* pindex = NULL;
3504 if (locator.IsNull())
3506 // If locator is null, return the hashStop block
3507 auto mi = mapBlockIndex.find(hashStop);
3508 if (mi == mapBlockIndex.end())
3510 pindex = (*mi).second;
3514 // Find the last block the caller has in the main chain
3515 pindex = locator.GetBlockIndex();
3517 pindex = pindex->pnext;
3520 vector<CBlock> vHeaders;
3522 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3523 for (; pindex; pindex = pindex->pnext)
3525 vHeaders.push_back(pindex->GetBlockHeader());
3526 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3529 pfrom->PushMessage("headers", vHeaders);
3533 else if (strCommand == "tx")
3535 vector<uint256> vWorkQueue;
3536 vector<uint256> vEraseQueue;
3537 CDataStream vMsg(vRecv);
3542 CInv inv(MSG_TX, tx.GetHash());
3543 pfrom->AddInventoryKnown(inv);
3545 bool fMissingInputs = false;
3546 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3548 auto nHash = inv.GetHash();
3550 SyncWithWallets(tx, NULL, true);
3551 RelayTransaction(tx, nHash);
3552 mapAlreadyAskedFor.erase(inv);
3553 vWorkQueue.push_back(nHash);
3554 vEraseQueue.push_back(nHash);
3556 // Recursively process any orphan transactions that depended on this one
3557 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3559 auto hashPrev = vWorkQueue[i];
3560 for (auto mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3561 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3564 const uint256& orphanTxHash = *mi;
3565 auto& orphanTx = mapOrphanTransactions[orphanTxHash];
3566 bool fMissingInputs2 = false;
3568 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3570 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3571 SyncWithWallets(tx, NULL, true);
3572 RelayTransaction(orphanTx, orphanTxHash);
3573 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3574 vWorkQueue.push_back(orphanTxHash);
3575 vEraseQueue.push_back(orphanTxHash);
3577 else if (!fMissingInputs2)
3580 vEraseQueue.push_back(orphanTxHash);
3581 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3586 for(uint256 hash : vEraseQueue)
3587 EraseOrphanTx(hash);
3589 else if (fMissingInputs)
3593 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3594 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3596 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3598 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3602 else if (strCommand == "block")
3606 auto hashBlock = block.GetHash();
3608 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3611 CInv inv(MSG_BLOCK, hashBlock);
3612 pfrom->AddInventoryKnown(inv);
3614 if (ProcessBlock(pfrom, &block))
3615 mapAlreadyAskedFor.erase(inv);
3616 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3620 // This asymmetric behavior for inbound and outbound connections was introduced
3621 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
3622 // to users' AddrMan and later request them by sending getaddr messages.
3623 // Making users (which are behind NAT and can only make outgoing connections) ignore
3624 // getaddr message mitigates the attack.
3625 else if ((strCommand == "getaddr") && (pfrom->fInbound))
3627 // Don't return addresses older than nCutOff timestamp
3628 int64_t nCutOff = GetTime() - (nNodeLifespan * nOneDay);
3629 pfrom->vAddrToSend.clear();
3630 vector<CAddress> vAddr = addrman.GetAddr();
3631 for(const CAddress &addr : vAddr)
3632 if(addr.nTime > nCutOff)
3633 pfrom->PushAddress(addr);
3637 else if (strCommand == "mempool")
3639 std::vector<uint256> vtxid;
3640 mempool.queryHashes(vtxid);
3642 for (unsigned int i = 0; i < vtxid.size(); i++) {
3643 CInv inv(MSG_TX, vtxid[i]);
3644 vInv.push_back(inv);
3645 if (i == (MAX_INV_SZ - 1))
3648 if (vInv.size() > 0)
3649 pfrom->PushMessage("inv", vInv);
3653 else if (strCommand == "checkorder")
3658 if (!GetBoolArg("-allowreceivebyip"))
3660 pfrom->PushMessage("reply", hashReply, 2, string(""));
3667 /// we have a chance to check the order here
3669 // Keep giving the same key to the same ip until they use it
3670 if (!mapReuseKey.count(pfrom->addr))
3671 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3673 // Send back approval of order and pubkey to use
3674 CScript scriptPubKey;
3675 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3676 pfrom->PushMessage("reply", hashReply, 0, scriptPubKey);
3680 else if (strCommand == "reply")
3685 CRequestTracker tracker;
3687 LOCK(pfrom->cs_mapRequests);
3688 auto mi = pfrom->mapRequests.find(hashReply);
3689 if (mi != pfrom->mapRequests.end())
3691 tracker = (*mi).second;
3692 pfrom->mapRequests.erase(mi);
3695 if (!tracker.IsNull())
3696 tracker.fn(tracker.param1, vRecv);
3700 else if (strCommand == "ping")
3704 // Echo the message back with the nonce. This allows for two useful features:
3706 // 1) A remote node can quickly check if the connection is operational
3707 // 2) Remote nodes can measure the latency of the network thread. If this node
3708 // is overloaded it won't respond to pings quickly and the remote node can
3709 // avoid sending us more work, like chain download requests.
3711 // The nonce stops the remote getting confused between different pings: without
3712 // it, if the remote node sends a ping once per second and this node takes 5
3713 // seconds to respond to each, the 5th ping the remote sends would appear to
3714 // return very quickly.
3715 pfrom->PushMessage("pong", nonce);
3719 else if (strCommand == "alert")
3724 auto alertHash = alert.GetHash();
3725 if (pfrom->setKnown.count(alertHash) == 0)
3727 if (alert.ProcessAlert())
3730 pfrom->setKnown.insert(alertHash);
3733 for(CNode* pnode : vNodes)
3734 alert.RelayTo(pnode);
3738 // Small DoS penalty so peers that send us lots of
3739 // duplicate/expired/invalid-signature/whatever alerts
3740 // eventually get banned.
3741 // This isn't a Misbehaving(100) (immediate ban) because the
3742 // peer might be an older or different implementation with
3743 // a different signature key, etc.
3744 pfrom->Misbehaving(10);
3752 // Ignore unknown commands for extensibility
3756 // Update the last seen time for this node's address
3757 if (pfrom->fNetworkNode)
3758 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3759 AddressCurrentlyConnected(pfrom->addr);
3765 bool ProcessMessages(CNode* pfrom)
3767 CDataStream& vRecv = pfrom->vRecv;
3771 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3775 // (4) message start
3784 // Don't bother if send buffer is too full to respond anyway
3785 if (pfrom->vSend.size() >= SendBufferSize())
3788 // Scan for message start
3789 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(nNetworkID), END(nNetworkID));
3790 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3791 if (vRecv.end() - pstart < nHeaderSize)
3793 if ((int)vRecv.size() > nHeaderSize)
3795 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3796 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3800 if (pstart - vRecv.begin() > 0)
3801 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
3802 vRecv.erase(vRecv.begin(), pstart);
3805 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3810 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3813 string strCommand = hdr.GetCommand();
3816 unsigned int nMessageSize = hdr.nMessageSize;
3817 if (nMessageSize > MAX_SIZE)
3819 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3822 if (nMessageSize > vRecv.size())
3824 // Rewind and wait for rest of message
3825 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3830 auto hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3831 unsigned int nChecksum = 0;
3832 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3833 if (nChecksum != hdr.nChecksum)
3835 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3836 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3840 // Copy message to its own buffer
3841 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3842 vRecv.ignore(nMessageSize);
3850 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3855 catch (std::ios_base::failure& e)
3857 if (strstr(e.what(), "end of data"))
3859 // Allow exceptions from under-length message on vRecv
3860 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());
3862 else if (strstr(e.what(), "size too large"))
3864 // Allow exceptions from over-long size
3865 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3869 PrintExceptionContinue(&e, "ProcessMessages()");
3872 catch (std::exception& e) {
3873 PrintExceptionContinue(&e, "ProcessMessages()");
3875 PrintExceptionContinue(NULL, "ProcessMessages()");
3879 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3887 bool SendMessages(CNode* pto)
3889 TRY_LOCK(cs_main, lockMain);
3891 // Current time in microseconds
3892 auto nNow = GetTimeMicros();
3894 // Don't send anything until we get their version message
3895 if (pto->nVersion == 0)
3898 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3900 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
3902 pto->PushMessage("ping", nonce);
3906 if (pto->fStartSync) {
3907 pto->fStartSync = false;
3908 pto->PushGetBlocks(pindexBest, uint256(0));
3911 // Resend wallet transactions that haven't gotten in a block yet
3912 ResendWalletTransactions();
3914 // Address refresh broadcast
3915 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3916 AdvertiseLocal(pto);
3917 pto->nNextLocalAddrSend = PoissonNextSend(nNow, nOneDay);
3923 if (pto->nNextAddrSend < nNow) {
3924 pto->nNextAddrSend = PoissonNextSend(nNow, 30);
3925 vector<CAddress> vAddr;
3926 vAddr.reserve(pto->vAddrToSend.size());
3927 for(const CAddress& addr : pto->vAddrToSend)
3929 if (pto->setAddrKnown.insert(addr).second)
3931 vAddr.push_back(addr);
3932 // receiver rejects addr messages larger than 1000
3933 if (vAddr.size() >= 1000)
3935 pto->PushMessage("addr", vAddr);
3940 pto->vAddrToSend.clear();
3942 pto->PushMessage("addr", vAddr);
3946 // Message: inventory
3949 vector<CInv> vInvWait;
3951 bool fSendTrickle = false;
3952 if (pto->nNextInvSend < nNow) {
3953 fSendTrickle = true;
3954 pto->nNextInvSend = PoissonNextSend(nNow, 5);
3956 LOCK(pto->cs_inventory);
3957 vInv.reserve(pto->vInventoryToSend.size());
3958 vInvWait.reserve(pto->vInventoryToSend.size());
3959 for(const CInv& inv : pto->vInventoryToSend)
3961 if (pto->setInventoryKnown.count(inv))
3964 // trickle out tx inv to protect privacy
3965 if (inv.GetType() == MSG_TX && !fSendTrickle)
3967 // 1/4 of tx invs blast to all immediately
3968 static uint256 hashSalt;
3970 hashSalt = GetRandHash();
3971 uint256 hashRand = inv.GetHash() ^ hashSalt;
3972 hashRand = Hash(hashRand.begin(), hashRand.end());
3973 bool fTrickleWait = ((hashRand & 3) != 0);
3977 vInvWait.push_back(inv);
3982 // returns true if wasn't already contained in the set
3983 if (pto->setInventoryKnown.insert(inv).second)
3985 vInv.push_back(inv);
3986 if (vInv.size() >= 1000)
3988 pto->PushMessage("inv", vInv);
3993 pto->vInventoryToSend = vInvWait;
3996 pto->PushMessage("inv", vInv);
4002 vector<CInv> vGetData;
4004 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4006 const CInv& inv = (*pto->mapAskFor.begin()).second;
4007 if (!AlreadyHave(txdb, inv))
4010 printf("sending getdata: %s\n", inv.ToString().c_str());
4011 vGetData.push_back(inv);
4012 if (vGetData.size() >= 1000)
4014 pto->PushMessage("getdata", vGetData);
4017 mapAlreadyAskedFor[inv] = nNow;
4019 pto->mapAskFor.erase(pto->mapAskFor.begin());
4021 if (!vGetData.empty())
4022 pto->PushMessage("getdata", vGetData);
4035 auto it1 = mapBlockIndex.begin();
4036 for (; it1 != mapBlockIndex.end(); it1++)
4037 delete (*it1).second;
4038 mapBlockIndex.clear();
4041 auto it2 = mapOrphanBlocks.begin();
4042 for (; it2 != mapOrphanBlocks.end(); it2++)
4043 delete (*it2).second;
4044 mapOrphanBlocks.clear();
4046 // orphan transactions
4048 } instance_of_cmaincleanup;