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.
8 #include "checkpoints.h"
10 #include "txdb-leveldb.h"
12 #include "interface.h"
13 #include "checkqueue.h"
17 #include <boost/filesystem.hpp>
18 #include <boost/filesystem/fstream.hpp>
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
31 unsigned int nTransactionsUpdated = 0;
33 map<uint256, CBlockIndex*> mapBlockIndex;
34 set<pair<COutPoint, unsigned int> > setStakeSeen;
36 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
37 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
38 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
39 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
40 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
42 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
44 unsigned int nStakeMinAge = 30 * nOneDay; // 30 days as zero time weight
45 unsigned int nStakeMaxAge = 90 * nOneDay; // 90 days as full weight
46 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
47 unsigned int nModifierInterval = 6 * nOneHour; // time to elapse before new modifier is computed
49 int nCoinbaseMaturity = 500;
51 CBlockIndex* pindexGenesisBlock = NULL;
54 uint256 nBestChainTrust = 0;
55 uint256 nBestInvalidTrust = 0;
57 uint256 hashBestChain = 0;
58 CBlockIndex* pindexBest = NULL;
59 int64_t nTimeBestReceived = 0;
60 int nScriptCheckThreads = 0;
62 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
64 map<uint256, CBlock*> mapOrphanBlocks;
65 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
66 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
67 map<uint256, uint256> mapProofOfStake;
69 map<uint256, CTransaction> mapOrphanTransactions;
70 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
72 // Constant stuff for coinbase transactions we create:
73 CScript COINBASE_FLAGS;
75 const string strMessageMagic = "NovaCoin Signed Message:\n";
78 int64_t nTransactionFee = MIN_TX_FEE;
79 int64_t nMinimumInputValue = MIN_TXOUT_AMOUNT;
81 // Ping and address broadcast intervals
82 int64_t nPingInterval = 30 * 60;
84 extern enum Checkpoints::CPMode CheckpointsMode;
86 //////////////////////////////////////////////////////////////////////////////
88 // dispatching functions
91 // These functions dispatch to one or all registered wallets
94 void RegisterWallet(CWallet* pwalletIn)
97 LOCK(cs_setpwalletRegistered);
98 setpwalletRegistered.insert(pwalletIn);
102 void UnregisterWallet(CWallet* pwalletIn)
105 LOCK(cs_setpwalletRegistered);
106 setpwalletRegistered.erase(pwalletIn);
110 // check whether the passed transaction is from us
111 bool static IsFromMe(CTransaction& tx)
113 for (CWallet* pwallet : setpwalletRegistered)
114 if (pwallet->IsFromMe(tx))
119 // erases transaction with the given hash from all wallets
120 void static EraseFromWallets(uint256 hash)
122 for (CWallet* pwallet : setpwalletRegistered)
123 pwallet->EraseFromWallet(hash);
126 // make sure all wallets know about the given transaction, in the given block
127 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
131 // wallets need to refund inputs when disconnecting coinstake
132 if (tx.IsCoinStake())
134 for (CWallet* pwallet : setpwalletRegistered)
135 if (pwallet->IsFromMe(tx))
136 pwallet->DisableTransaction(tx);
141 for (CWallet* pwallet : setpwalletRegistered)
142 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
145 // notify wallets about a new best chain
146 void static SetBestChain(const CBlockLocator& loc)
148 for (CWallet* pwallet : setpwalletRegistered)
149 pwallet->SetBestChain(loc);
152 // notify wallets about an updated transaction
153 void static UpdatedTransaction(const uint256& hashTx)
155 for (CWallet* pwallet : setpwalletRegistered)
156 pwallet->UpdatedTransaction(hashTx);
160 void static PrintWallets(const CBlock& block)
162 for (CWallet* pwallet : setpwalletRegistered)
163 pwallet->PrintWallet(block);
166 // notify wallets about an incoming inventory (for request counts)
167 void static Inventory(const uint256& hash)
169 for (CWallet* pwallet : setpwalletRegistered)
170 pwallet->Inventory(hash);
173 // ask wallets to resend their transactions
174 void ResendWalletTransactions(bool fForceResend)
176 for (CWallet* pwallet : setpwalletRegistered)
177 pwallet->ResendWalletTransactions(fForceResend);
186 //////////////////////////////////////////////////////////////////////////////
188 // mapOrphanTransactions
191 bool AddOrphanTx(const CTransaction& tx)
193 uint256 hash = tx.GetHash();
194 if (mapOrphanTransactions.count(hash))
197 // Ignore big transactions, to avoid a
198 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
199 // large transaction with a missing parent then we assume
200 // it will rebroadcast it later, after the parent transaction(s)
201 // have been mined or received.
202 // 10,000 orphans, each of which is at most 5,000 bytes big is
203 // at most 500 megabytes of orphans:
205 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
209 printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
213 mapOrphanTransactions[hash] = tx;
214 for (const CTxIn& txin : tx.vin)
215 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
217 printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
218 mapOrphanTransactions.size());
222 void static EraseOrphanTx(uint256 hash)
224 if (!mapOrphanTransactions.count(hash))
226 const CTransaction& tx = mapOrphanTransactions[hash];
227 for (const CTxIn& txin : tx.vin)
229 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
230 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
231 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
233 mapOrphanTransactions.erase(hash);
236 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
238 unsigned int nEvicted = 0;
239 while (mapOrphanTransactions.size() > nMaxOrphans)
241 // Evict a random orphan:
242 uint256 randomhash = GetRandHash();
243 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
244 if (it == mapOrphanTransactions.end())
245 it = mapOrphanTransactions.begin();
246 EraseOrphanTx(it->first);
258 //////////////////////////////////////////////////////////////////////////////
260 // CTransaction and CTxIndex
263 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
266 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
268 if (!ReadFromDisk(txindexRet.pos))
270 if (prevout.n >= vout.size())
278 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
281 return ReadFromDisk(txdb, prevout, txindex);
284 bool CTransaction::ReadFromDisk(COutPoint prevout)
288 return ReadFromDisk(txdb, prevout, txindex);
291 bool CTransaction::IsStandard(string& strReason) const
293 if (nVersion > CTransaction::CURRENT_VERSION)
295 strReason = "version";
299 unsigned int nDataOut = 0;
300 txnouttype whichType;
301 for (const CTxIn& txin : vin)
303 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
304 // keys. (remember the 520 byte limit on redeemScript size) That works
305 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
306 // bytes of scriptSig, which we round off to 1650 bytes for some minor
307 // future-proofing. That's also enough to spend a 20-of-20
308 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
309 // considered standard)
310 if (txin.scriptSig.size() > 1650)
312 strReason = "scriptsig-size";
315 if (!txin.scriptSig.IsPushOnly())
317 strReason = "scriptsig-not-pushonly";
320 if (!txin.scriptSig.HasCanonicalPushes()) {
321 strReason = "txin-scriptsig-not-canonicalpushes";
325 for (const CTxOut& txout : vout) {
326 if (!::IsStandard(txout.scriptPubKey, whichType)) {
327 strReason = "scriptpubkey";
330 if (whichType == TX_NULL_DATA)
333 if (txout.nValue == 0) {
334 strReason = "txout-value=0";
337 if (!txout.scriptPubKey.HasCanonicalPushes()) {
338 strReason = "txout-scriptsig-not-canonicalpushes";
344 // only one OP_RETURN txout is permitted
346 strReason = "multi-op-return";
354 // Check transaction inputs, and make sure any
355 // pay-to-script-hash transactions are evaluating IsStandard scripts
357 // Why bother? To avoid denial-of-service attacks; an attacker
358 // can submit a standard HASH... OP_EQUAL transaction,
359 // which will get accepted into blocks. The redemption
360 // script can be anything; an attacker could use a very
361 // expensive-to-check-upon-redemption script like:
362 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
364 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
367 return true; // Coinbases don't use vin normally
369 for (unsigned int i = 0; i < vin.size(); i++)
371 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
373 vector<vector<unsigned char> > vSolutions;
374 txnouttype whichType;
375 // get the scriptPubKey corresponding to this input:
376 const CScript& prevScript = prev.scriptPubKey;
377 if (!Solver(prevScript, whichType, vSolutions))
379 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
380 if (nArgsExpected < 0)
383 // Transactions with extra stuff in their scriptSigs are
384 // non-standard. Note that this EvalScript() call will
385 // be quick, because if there are any operations
386 // beside "push data" in the scriptSig the
387 // IsStandard() call returns false
388 vector<vector<unsigned char> > stack;
389 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
392 if (whichType == TX_SCRIPTHASH)
396 CScript subscript(stack.back().begin(), stack.back().end());
397 vector<vector<unsigned char> > vSolutions2;
398 txnouttype whichType2;
399 if (!Solver(subscript, whichType2, vSolutions2))
401 if (whichType2 == TX_SCRIPTHASH)
405 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
408 nArgsExpected += tmpExpected;
411 if (stack.size() != (unsigned int)nArgsExpected)
419 CTransaction::GetLegacySigOpCount() const
421 unsigned int nSigOps = 0;
424 // Coinbase scriptsigs are never executed, so there is
425 // no sense in calculation of sigops.
426 for (const CTxIn& txin : vin)
428 nSigOps += txin.scriptSig.GetSigOpCount(false);
431 for (const CTxOut& txout : vout)
433 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
438 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
451 // Load the block this tx is in
453 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
455 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
460 // Update the tx's hashBlock
461 hashBlock = pblock->GetHash();
463 // Locate the transaction
464 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
465 if (pblock->vtx[nIndex] == *(CTransaction*)this)
467 if (nIndex == (int)pblock->vtx.size())
469 vMerkleBranch.clear();
471 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
475 // Fill in merkle branch
476 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
479 // Is the tx in a block that's in the main chain
480 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
481 if (mi == mapBlockIndex.end())
483 const CBlockIndex* pindex = (*mi).second;
484 if (!pindex || !pindex->IsInMainChain())
487 return pindexBest->nHeight - pindex->nHeight + 1;
490 bool CTransaction::CheckTransaction() const
492 // Basic checks that don't depend on any context
494 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
496 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
498 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
499 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
501 // Check for negative or overflow output values
502 int64_t nValueOut = 0;
503 for (unsigned int i = 0; i < vout.size(); i++)
505 const CTxOut& txout = vout[i];
506 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
507 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
509 if (txout.nValue < 0)
510 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
511 if (txout.nValue > MAX_MONEY)
512 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
513 nValueOut += txout.nValue;
514 if (!MoneyRange(nValueOut))
515 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
518 // Check for duplicate inputs
519 set<COutPoint> vInOutPoints;
520 for (const CTxIn& txin : vin)
522 if (vInOutPoints.count(txin.prevout))
524 vInOutPoints.insert(txin.prevout);
529 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
530 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
534 for (const CTxIn& txin : vin)
535 if (txin.prevout.IsNull())
536 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
542 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
544 int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
548 // Enforce 0.01 as minimum fee for coinstake
550 nMinRelayTxFee = CENT;
553 // Base fee is either nMinTxFee or nMinRelayTxFee
554 int64_t nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
556 unsigned int nNewBlockSize = nBlockSize + nBytes;
557 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
563 // Transactions under 1K are free
569 // Free transaction area
570 if (nNewBlockSize < 27000)
575 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
576 // each non empty output which is less than 0.01
578 // It's safe to ignore empty outputs here, because these inputs are allowed
579 // only for coinbase and coinstake transactions.
580 for (const CTxOut& txout : vout)
581 if (txout.nValue < CENT && !txout.IsEmpty())
584 // Raise the price as the block approaches full
585 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
587 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
589 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
592 if (!MoneyRange(nMinFee))
599 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
600 bool* pfMissingInputs)
603 *pfMissingInputs = false;
605 // Time (prevent mempool memory exhaustion attack)
606 if (tx.nTime > FutureDrift(GetAdjustedTime()))
607 return tx.DoS(10, error("CTxMemPool::accept() : transaction timestamp is too far in the future"));
609 if (!tx.CheckTransaction())
610 return error("CTxMemPool::accept() : CheckTransaction failed");
612 // Coinbase is only valid in a block, not as a loose transaction
614 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
616 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
617 if (tx.IsCoinStake())
618 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
620 // To help v0.1.5 clients who would see it as a negative number
621 if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
622 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
624 // Rather not work on nonstandard transactions (unless -testnet)
626 if (!fTestNet && !tx.IsStandard(strNonStd))
627 return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
629 // Do we already have it?
630 uint256 hash = tx.GetHash();
633 if (mapTx.count(hash))
637 if (txdb.ContainsTx(hash))
640 // Check for conflicts with in-memory transactions
641 CTransaction* ptxOld = NULL;
642 for (unsigned int i = 0; i < tx.vin.size(); i++)
644 COutPoint outpoint = tx.vin[i].prevout;
645 if (mapNextTx.count(outpoint))
647 // Disable replacement feature for now
650 // Allow replacing with a newer version of the same transaction
653 ptxOld = mapNextTx[outpoint].ptx;
654 if (ptxOld->IsFinal())
656 if (!tx.IsNewerThan(*ptxOld))
658 for (unsigned int i = 0; i < tx.vin.size(); i++)
660 COutPoint outpoint = tx.vin[i].prevout;
661 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
671 map<uint256, CTxIndex> mapUnused;
672 bool fInvalid = false;
673 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
676 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
678 *pfMissingInputs = true;
682 // Check for non-standard pay-to-script-hash in inputs
683 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
684 return error("CTxMemPool::accept() : nonstandard transaction input");
686 // Note: if you modify this code to accept non-standard transactions, then
687 // you should add code here to check that the transaction does a
688 // reasonable number of ECDSA signature verifications.
690 int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
691 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
693 // Don't accept it if it can't get into a block
694 int64_t txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
695 if (nFees < txMinFee)
696 return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
697 hash.ToString().c_str(),
700 // Continuously rate-limit free transactions
701 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
702 // be annoying or make others' transactions take longer to confirm.
703 if (nFees < MIN_RELAY_TX_FEE)
705 static CCriticalSection cs;
706 static double dFreeCount;
707 static int64_t nLastTime;
708 int64_t nNow = GetTime();
712 // Use an exponentially decaying ~10-minute window:
713 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
715 // -limitfreerelay unit is thousand-bytes-per-minute
716 // At default rate it would take over a month to fill 1GB
717 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
718 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
720 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
725 // Check against previous transactions
726 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
727 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, STRICT_FLAGS))
729 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
733 // Store transaction in memory
738 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
741 addUnchecked(hash, tx);
744 ///// are we sure this is ok when loading transactions or restoring block txes
745 // If updated, erase old tx from wallet
747 EraseFromWallets(ptxOld->GetHash());
749 printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
750 hash.ToString().substr(0,10).c_str(),
755 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
757 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
760 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
762 // Add to memory pool without checking anything. Don't call this directly,
763 // call CTxMemPool::accept to properly check the transaction first.
766 for (unsigned int i = 0; i < tx.vin.size(); i++)
767 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
768 nTransactionsUpdated++;
774 bool CTxMemPool::remove(CTransaction &tx)
776 // Remove transaction from memory pool
779 uint256 hash = tx.GetHash();
780 if (mapTx.count(hash))
782 for (const CTxIn& txin : tx.vin)
783 mapNextTx.erase(txin.prevout);
785 nTransactionsUpdated++;
791 void CTxMemPool::clear()
796 ++nTransactionsUpdated;
799 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
804 vtxid.reserve(mapTx.size());
805 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
806 vtxid.push_back((*mi).first);
812 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
814 if (hashBlock == 0 || nIndex == -1)
817 // Find the block it claims to be in
818 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
819 if (mi == mapBlockIndex.end())
821 CBlockIndex* pindex = (*mi).second;
822 if (!pindex || !pindex->IsInMainChain())
825 // Make sure the merkle branch connects to this block
826 if (!fMerkleVerified)
828 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
830 fMerkleVerified = true;
834 return pindexBest->nHeight - pindex->nHeight + 1;
838 int CMerkleTx::GetBlocksToMaturity() const
840 if (!(IsCoinBase() || IsCoinStake()))
842 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
846 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
850 if (!IsInMainChain() && !ClientConnectInputs())
852 return CTransaction::AcceptToMemoryPool(txdb, false);
856 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
860 bool CMerkleTx::AcceptToMemoryPool()
863 return AcceptToMemoryPool(txdb);
866 int CTxIndex::GetDepthInMainChain() const
870 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
872 // Find the block in the index
873 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
874 if (mi == mapBlockIndex.end())
876 CBlockIndex* pindex = (*mi).second;
877 if (!pindex || !pindex->IsInMainChain())
879 return 1 + nBestHeight - pindex->nHeight;
882 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
883 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
889 if (mempool.exists(hash))
891 tx = mempool.lookup(hash);
897 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
900 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
901 hashBlock = block.GetHash();
915 //////////////////////////////////////////////////////////////////////////////
917 // CBlock and CBlockIndex
920 static CBlockIndex* pblockindexFBBHLast;
921 CBlockIndex* FindBlockByHeight(int nHeight)
923 CBlockIndex *pblockindex;
924 if (nHeight < nBestHeight / 2)
925 pblockindex = pindexGenesisBlock;
927 pblockindex = pindexBest;
928 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
929 pblockindex = pblockindexFBBHLast;
930 while (pblockindex->nHeight > nHeight)
931 pblockindex = pblockindex->pprev;
932 while (pblockindex->nHeight < nHeight)
933 pblockindex = pblockindex->pnext;
934 pblockindexFBBHLast = pblockindex;
938 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
940 if (!fReadTransactions)
942 *this = pindex->GetBlockHeader();
945 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
947 if (GetHash() != pindex->GetBlockHash())
948 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
952 uint256 static GetOrphanRoot(const CBlock* pblock)
954 // Work back to the first block in the orphan chain
955 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
956 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
957 return pblock->GetHash();
960 // ppcoin: find block wanted by given orphan block
961 uint256 WantedByOrphan(const CBlock* pblockOrphan)
963 // Work back to the first block in the orphan chain
964 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
965 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
966 return pblockOrphan->hashPrevBlock;
969 // select stake target limit according to hard-coded conditions
970 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
972 if(fTestNet) // separate proof of stake target limit for testnet
973 return bnProofOfStakeLimit;
974 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
975 return bnProofOfStakeLimit;
976 if(nHeight + 1 > 15000) // 24 bits since block 15000
977 return bnProofOfStakeLegacyLimit;
978 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
979 return bnProofOfStakeHardLimit;
981 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
984 // miner's coin base reward based on nBits
985 int64_t GetProofOfWorkReward(unsigned int nBits)
987 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
990 bnTarget.SetCompact(nBits);
991 CBigNum bnTargetLimit = bnProofOfWorkLimit;
992 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
994 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
995 // A reasonably continuous curve is used to avoid shock to market
996 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
998 // Human readable form:
1000 // nSubsidy = 100 / (diff ^ 1/6)
1002 // Please note that we're using bisection to find an approximate solutuion
1003 CBigNum bnLowerBound = CENT;
1004 CBigNum bnUpperBound = bnSubsidyLimit;
1005 while (bnLowerBound + CENT <= bnUpperBound)
1007 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1008 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1009 bnUpperBound = bnMidValue;
1011 bnLowerBound = bnMidValue;
1014 int64_t nSubsidy = bnUpperBound.getuint64();
1016 nSubsidy = (nSubsidy / CENT) * CENT;
1017 if (fDebug && GetBoolArg("-printcreation"))
1018 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1020 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
1023 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1024 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1026 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1028 // Stage 2 of emission process is mostly PoS-based.
1030 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1032 bnTarget.SetCompact(nBits);
1033 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1034 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1036 // A reasonably continuous curve is used to avoid shock to market
1038 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1039 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1040 bnMidPart, bnRewardPart;
1042 while (bnLowerBound + CENT <= bnUpperBound)
1044 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1047 // Reward for coin-year is cut in half every 8x multiply of PoS difficulty
1049 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1051 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1054 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1055 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1057 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1058 bnUpperBound = bnMidValue;
1060 bnLowerBound = bnMidValue;
1063 nRewardCoinYear = bnUpperBound.getuint64();
1064 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1067 return nRewardCoinYear;
1069 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1071 // Set reasonable reward limit for large inputs
1073 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1075 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1076 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1078 nSubsidy = min(nSubsidy, nSubsidyLimit);
1080 if (fDebug && GetBoolArg("-printcreation"))
1081 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1086 static const int64_t nTargetTimespan = 7 * nOneDay; // one week
1088 // get proof of work blocks max spacing according to hard-coded conditions
1089 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1091 if(nTime > TARGETS_SWITCH_TIME)
1092 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1095 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1097 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1101 // maximum nBits value could possible be required nTime after
1103 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1106 bnResult.SetCompact(nBase);
1108 while (nTime > 0 && bnResult < bnTargetLimit)
1110 // Maximum 200% adjustment per day...
1114 if (bnResult > bnTargetLimit)
1115 bnResult = bnTargetLimit;
1116 return bnResult.GetCompact();
1120 // minimum amount of work that could possibly be required nTime after
1121 // minimum proof-of-work required was nBase
1123 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1125 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1129 // minimum amount of stake that could possibly be required nTime after
1130 // minimum proof-of-stake required was nBase
1132 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1134 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1138 // ppcoin: find last block index up to pindex
1139 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1141 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1142 pindex = pindex->pprev;
1146 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1148 if (pindexLast == NULL)
1149 return bnProofOfWorkLimit.GetCompact(); // genesis block
1151 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1153 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1154 if (pindexPrev->pprev == NULL)
1155 return bnTargetLimit.GetCompact(); // first block
1156 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1157 if (pindexPrevPrev->pprev == NULL)
1158 return bnTargetLimit.GetCompact(); // second block
1160 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1162 // ppcoin: target change every block
1163 // ppcoin: retarget with exponential moving toward target spacing
1165 bnNew.SetCompact(pindexPrev->nBits);
1166 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1167 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1168 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1169 bnNew /= ((nInterval + 1) * nTargetSpacing);
1171 if (bnNew > bnTargetLimit)
1172 bnNew = bnTargetLimit;
1174 return bnNew.GetCompact();
1177 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1180 bnTarget.SetCompact(nBits);
1183 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1184 return error("CheckProofOfWork() : nBits below minimum work");
1186 // Check proof of work matches claimed amount
1187 if (hash > bnTarget.getuint256())
1188 return error("CheckProofOfWork() : hash doesn't match nBits");
1193 // Return maximum amount of blocks that other nodes claim to have
1194 int GetNumBlocksOfPeers()
1196 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1199 bool IsInitialBlockDownload()
1201 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1203 static int64_t nLastUpdate;
1204 static CBlockIndex* pindexLastBest;
1205 int64_t nCurrentTime = GetTime();
1206 if (pindexBest != pindexLastBest)
1208 pindexLastBest = pindexBest;
1209 nLastUpdate = nCurrentTime;
1211 return (nCurrentTime - nLastUpdate < 10 &&
1212 pindexBest->GetBlockTime() < nCurrentTime - nOneDay);
1215 void static InvalidChainFound(CBlockIndex* pindexNew)
1217 if (pindexNew->nChainTrust > nBestInvalidTrust)
1219 nBestInvalidTrust = pindexNew->nChainTrust;
1220 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1221 uiInterface.NotifyBlocksChanged();
1224 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1225 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1227 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1228 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1229 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1230 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1231 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1232 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1233 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1234 nBestBlockTrust.Get64(),
1235 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1239 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1241 nTime = max(GetBlockTime(), GetAdjustedTime());
1254 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1256 // Relinquish previous transactions' spent pointers
1259 for (const CTxIn& txin : vin)
1261 COutPoint prevout = txin.prevout;
1263 // Get prev txindex from disk
1265 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1266 return error("DisconnectInputs() : ReadTxIndex failed");
1268 if (prevout.n >= txindex.vSpent.size())
1269 return error("DisconnectInputs() : prevout.n out of range");
1271 // Mark outpoint as not spent
1272 txindex.vSpent[prevout.n].SetNull();
1275 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1276 return error("DisconnectInputs() : UpdateTxIndex failed");
1280 // Remove transaction from index
1281 // This can fail if a duplicate of this transaction was in a chain that got
1282 // reorganized away. This is only possible if this transaction was completely
1283 // spent, so erasing it would be a no-op anyway.
1284 txdb.EraseTxIndex(*this);
1290 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1291 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1293 // FetchInputs can return false either because we just haven't seen some inputs
1294 // (in which case the transaction should be stored as an orphan)
1295 // or because the transaction is malformed (in which case the transaction should
1296 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1300 return true; // Coinbase transactions have no inputs to fetch.
1302 for (unsigned int i = 0; i < vin.size(); i++)
1304 COutPoint prevout = vin[i].prevout;
1305 if (inputsRet.count(prevout.hash))
1306 continue; // Got it already
1309 CTxIndex& txindex = inputsRet[prevout.hash].first;
1311 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1313 // Get txindex from current proposed changes
1314 txindex = mapTestPool.find(prevout.hash)->second;
1318 // Read txindex from txdb
1319 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1321 if (!fFound && (fBlock || fMiner))
1322 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());
1325 CTransaction& txPrev = inputsRet[prevout.hash].second;
1326 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1328 // Get prev tx from single transactions in memory
1331 if (!mempool.exists(prevout.hash))
1332 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());
1333 txPrev = mempool.lookup(prevout.hash);
1336 txindex.vSpent.resize(txPrev.vout.size());
1340 // Get prev tx from disk
1341 if (!txPrev.ReadFromDisk(txindex.pos))
1342 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1346 // Make sure all prevout.n indexes are valid:
1347 for (unsigned int i = 0; i < vin.size(); i++)
1349 const COutPoint prevout = vin[i].prevout;
1350 assert(inputsRet.count(prevout.hash) != 0);
1351 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1352 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1353 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1355 // Revisit this if/when transaction replacement is implemented and allows
1358 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()));
1365 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1367 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1368 if (mi == inputs.end())
1369 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1371 const CTransaction& txPrev = (mi->second).second;
1372 if (input.prevout.n >= txPrev.vout.size())
1373 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1375 return txPrev.vout[input.prevout.n];
1378 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1383 int64_t nResult = 0;
1384 for (unsigned int i = 0; i < vin.size(); i++)
1386 nResult += GetOutputFor(vin[i], inputs).nValue;
1392 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1397 unsigned int nSigOps = 0;
1398 for (unsigned int i = 0; i < vin.size(); i++)
1400 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1401 if (prevout.scriptPubKey.IsPayToScriptHash())
1402 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1407 bool CScriptCheck::operator()() const {
1408 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1409 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1410 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1414 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1416 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1419 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1420 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1422 // Take over previous transactions' spent pointers
1423 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1424 // fMiner is true when called from the internal bitcoin miner
1425 // ... both are false when called from CTransaction::AcceptToMemoryPool
1429 int64_t nValueIn = 0;
1431 for (unsigned int i = 0; i < vin.size(); i++)
1433 COutPoint prevout = vin[i].prevout;
1434 assert(inputs.count(prevout.hash) > 0);
1435 CTxIndex& txindex = inputs[prevout.hash].first;
1436 CTransaction& txPrev = inputs[prevout.hash].second;
1438 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1439 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()));
1441 // If prev is coinbase or coinstake, check that it's matured
1442 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1443 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1444 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1445 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1447 // ppcoin: check transaction timestamp
1448 if (txPrev.nTime > nTime)
1449 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1451 // Check for negative or overflow input values
1452 nValueIn += txPrev.vout[prevout.n].nValue;
1453 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1454 return DoS(100, error("ConnectInputs() : txin values out of range"));
1459 pvChecks->reserve(vin.size());
1461 // The first loop above does all the inexpensive checks.
1462 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1463 // Helps prevent CPU exhaustion attacks.
1464 for (unsigned int i = 0; i < vin.size(); i++)
1466 COutPoint prevout = vin[i].prevout;
1467 assert(inputs.count(prevout.hash) > 0);
1468 CTxIndex& txindex = inputs[prevout.hash].first;
1469 CTransaction& txPrev = inputs[prevout.hash].second;
1471 // Check for conflicts (double-spend)
1472 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1473 // for an attacker to attempt to split the network.
1474 if (!txindex.vSpent[prevout.n].IsNull())
1475 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());
1477 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1478 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1479 // still computed and checked, and any change will be caught at the next checkpoint.
1483 CScriptCheck check(txPrev, *this, i, flags, 0);
1486 pvChecks->push_back(CScriptCheck());
1487 check.swap(pvChecks->back());
1491 if (flags & STRICT_FLAGS)
1493 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1494 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1496 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1498 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1502 // Mark outpoints as spent
1503 txindex.vSpent[prevout.n] = posThisTx;
1506 if (fBlock || fMiner)
1508 mapTestPool[prevout.hash] = txindex;
1514 if (nTime > Checkpoints::GetLastCheckpointTime())
1516 unsigned int nTxSize = GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
1518 // coin stake tx earns reward instead of paying fee
1520 if (!GetCoinAge(txdb, nCoinAge))
1521 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1523 int64_t nReward = GetValueOut() - nValueIn;
1524 int64_t nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1526 if (nReward > nCalculatedReward)
1527 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1532 if (nValueIn < GetValueOut())
1533 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1535 // Tally transaction fees
1536 int64_t nTxFee = nValueIn - GetValueOut();
1538 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1541 if (!MoneyRange(nFees))
1542 return DoS(100, error("ConnectInputs() : nFees out of range"));
1550 bool CTransaction::ClientConnectInputs()
1555 // Take over previous transactions' spent pointers
1558 int64_t nValueIn = 0;
1559 for (unsigned int i = 0; i < vin.size(); i++)
1561 // Get prev tx from single transactions in memory
1562 COutPoint prevout = vin[i].prevout;
1563 if (!mempool.exists(prevout.hash))
1565 CTransaction& txPrev = mempool.lookup(prevout.hash);
1567 if (prevout.n >= txPrev.vout.size())
1571 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1572 return error("ClientConnectInputs() : VerifySignature failed");
1574 ///// this is redundant with the mempool.mapNextTx stuff,
1575 ///// not sure which I want to get rid of
1576 ///// this has to go away now that posNext is gone
1577 // // Check for conflicts
1578 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1579 // return error("ConnectInputs() : prev tx already used");
1581 // // Flag outpoints as used
1582 // txPrev.vout[prevout.n].posNext = posThisTx;
1584 nValueIn += txPrev.vout[prevout.n].nValue;
1586 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1587 return error("ClientConnectInputs() : txin values out of range");
1589 if (GetValueOut() > nValueIn)
1599 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1601 // Disconnect in reverse order
1602 for (int i = vtx.size()-1; i >= 0; i--)
1603 if (!vtx[i].DisconnectInputs(txdb))
1606 // Update block index on disk without changing it in memory.
1607 // The memory index structure will be changed after the db commits.
1610 CDiskBlockIndex blockindexPrev(pindex->pprev);
1611 blockindexPrev.hashNext = 0;
1612 if (!txdb.WriteBlockIndex(blockindexPrev))
1613 return error("DisconnectBlock() : WriteBlockIndex failed");
1616 // ppcoin: clean up wallet after disconnecting coinstake
1617 for (CTransaction& tx : vtx)
1618 SyncWithWallets(tx, this, false, false);
1623 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1625 void ThreadScriptCheck(void*) {
1626 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1627 RenameThread("novacoin-scriptch");
1628 scriptcheckqueue.Thread();
1629 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1632 void ThreadScriptCheckQuit() {
1633 scriptcheckqueue.Quit();
1636 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1638 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1639 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1642 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1643 // unless those are already completely spent.
1644 // If such overwrites are allowed, coinbases and transactions depending upon those
1645 // can be duplicated to remove the ability to spend the first instance -- even after
1646 // being sent to another address.
1647 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1648 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1649 // already refuses previously-known transaction ids entirely.
1650 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1651 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1652 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1653 // initial block download.
1654 bool fEnforceBIP30 = true; // Always active in NovaCoin
1655 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1657 //// issue here: it doesn't know the version
1658 unsigned int nTxPos;
1660 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1661 // 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
1664 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1666 map<uint256, CTxIndex> mapQueuedChanges;
1667 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1670 int64_t nValueIn = 0;
1671 int64_t nValueOut = 0;
1672 unsigned int nSigOps = 0;
1673 for (CTransaction& tx : vtx)
1675 uint256 hashTx = tx.GetHash();
1677 if (fEnforceBIP30) {
1678 CTxIndex txindexOld;
1679 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1680 for (CDiskTxPos &pos : txindexOld.vSpent)
1686 nSigOps += tx.GetLegacySigOpCount();
1687 if (nSigOps > MAX_BLOCK_SIGOPS)
1688 return DoS(100, error("ConnectBlock() : too many sigops"));
1690 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1692 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1694 MapPrevTx mapInputs;
1695 if (tx.IsCoinBase())
1696 nValueOut += tx.GetValueOut();
1700 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1703 // Add in sigops done by pay-to-script-hash inputs;
1704 // this is to prevent a "rogue miner" from creating
1705 // an incredibly-expensive-to-validate block.
1706 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1707 if (nSigOps > MAX_BLOCK_SIGOPS)
1708 return DoS(100, error("ConnectBlock() : too many sigops"));
1710 int64_t nTxValueIn = tx.GetValueIn(mapInputs);
1711 int64_t nTxValueOut = tx.GetValueOut();
1712 nValueIn += nTxValueIn;
1713 nValueOut += nTxValueOut;
1714 if (!tx.IsCoinStake())
1715 nFees += nTxValueIn - nTxValueOut;
1717 unsigned int nFlags = SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH;
1719 if (tx.nTime >= CHECKLOCKTIMEVERIFY_SWITCH_TIME) {
1720 nFlags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1723 if (tx.nTime >= CHECKSEQUENCEVERIFY_SWITCH_TIME) {
1724 nFlags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1727 std::vector<CScriptCheck> vChecks;
1728 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, nFlags, nScriptCheckThreads ? &vChecks : NULL))
1730 control.Add(vChecks);
1733 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1736 if (!control.Wait())
1737 return DoS(100, false);
1739 if (IsProofOfWork())
1741 int64_t nBlockReward = GetProofOfWorkReward(nBits) + nFees;
1743 // Check coinbase reward
1744 if (vtx[0].GetValueOut() > nBlockReward)
1745 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1746 vtx[0].GetValueOut(),
1750 // track money supply and mint amount info
1751 pindex->nMint = nValueOut - nValueIn + nFees;
1752 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1753 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1754 return error("Connect() : WriteBlockIndex for pindex failed");
1756 // fees are not collected by proof-of-stake miners
1757 // fees are destroyed to compensate the entire network
1758 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1759 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
1764 // Write queued txindex changes
1765 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1767 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1768 return error("ConnectBlock() : UpdateTxIndex failed");
1771 // Update block index on disk without changing it in memory.
1772 // The memory index structure will be changed after the db commits.
1775 CDiskBlockIndex blockindexPrev(pindex->pprev);
1776 blockindexPrev.hashNext = pindex->GetBlockHash();
1777 if (!txdb.WriteBlockIndex(blockindexPrev))
1778 return error("ConnectBlock() : WriteBlockIndex failed");
1781 // Watch for transactions paying to me
1782 for (CTransaction& tx : vtx)
1783 SyncWithWallets(tx, this, true);
1789 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1791 printf("REORGANIZE\n");
1794 CBlockIndex* pfork = pindexBest;
1795 CBlockIndex* plonger = pindexNew;
1796 while (pfork != plonger)
1798 while (plonger->nHeight > pfork->nHeight)
1799 if ((plonger = plonger->pprev) == NULL)
1800 return error("Reorganize() : plonger->pprev is null");
1801 if (pfork == plonger)
1803 if ((pfork = pfork->pprev) == NULL)
1804 return error("Reorganize() : pfork->pprev is null");
1807 // List of what to disconnect
1808 vector<CBlockIndex*> vDisconnect;
1809 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1810 vDisconnect.push_back(pindex);
1812 // List of what to connect
1813 vector<CBlockIndex*> vConnect;
1814 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1815 vConnect.push_back(pindex);
1816 reverse(vConnect.begin(), vConnect.end());
1818 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());
1819 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());
1821 // Disconnect shorter branch
1822 vector<CTransaction> vResurrect;
1823 for (CBlockIndex* pindex : vDisconnect)
1826 if (!block.ReadFromDisk(pindex))
1827 return error("Reorganize() : ReadFromDisk for disconnect failed");
1828 if (!block.DisconnectBlock(txdb, pindex))
1829 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1831 // Queue memory transactions to resurrect
1832 for (const CTransaction& tx : block.vtx)
1833 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1834 vResurrect.push_back(tx);
1837 // Connect longer branch
1838 vector<CTransaction> vDelete;
1839 for (unsigned int i = 0; i < vConnect.size(); i++)
1841 CBlockIndex* pindex = vConnect[i];
1843 if (!block.ReadFromDisk(pindex))
1844 return error("Reorganize() : ReadFromDisk for connect failed");
1845 if (!block.ConnectBlock(txdb, pindex))
1848 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1851 // Queue memory transactions to delete
1852 for (const CTransaction& tx : block.vtx)
1853 vDelete.push_back(tx);
1855 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1856 return error("Reorganize() : WriteHashBestChain failed");
1858 // Make sure it's successfully written to disk before changing memory structure
1859 if (!txdb.TxnCommit())
1860 return error("Reorganize() : TxnCommit failed");
1862 // Disconnect shorter branch
1863 for (CBlockIndex* pindex : vDisconnect)
1865 pindex->pprev->pnext = NULL;
1867 // Connect longer branch
1868 for (CBlockIndex* pindex : vConnect)
1870 pindex->pprev->pnext = pindex;
1872 // Resurrect memory transactions that were in the disconnected branch
1873 for (CTransaction& tx : vResurrect)
1874 tx.AcceptToMemoryPool(txdb, false);
1876 // Delete redundant memory transactions that are in the connected branch
1877 for (CTransaction& tx : vDelete)
1880 printf("REORGANIZE: done\n");
1886 // Called from inside SetBestChain: attaches a block to the new best chain being built
1887 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1889 uint256 hash = GetHash();
1891 // Adding to current best branch
1892 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1895 InvalidChainFound(pindexNew);
1898 if (!txdb.TxnCommit())
1899 return error("SetBestChain() : TxnCommit failed");
1901 // Add to current best branch
1902 pindexNew->pprev->pnext = pindexNew;
1904 // Delete redundant memory transactions
1905 for (CTransaction& tx : vtx)
1911 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1913 uint256 hash = GetHash();
1915 if (!txdb.TxnBegin())
1916 return error("SetBestChain() : TxnBegin failed");
1918 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1920 txdb.WriteHashBestChain(hash);
1921 if (!txdb.TxnCommit())
1922 return error("SetBestChain() : TxnCommit failed");
1923 pindexGenesisBlock = pindexNew;
1925 else if (hashPrevBlock == hashBestChain)
1927 if (!SetBestChainInner(txdb, pindexNew))
1928 return error("SetBestChain() : SetBestChainInner failed");
1932 // the first block in the new chain that will cause it to become the new best chain
1933 CBlockIndex *pindexIntermediate = pindexNew;
1935 // list of blocks that need to be connected afterwards
1936 std::vector<CBlockIndex*> vpindexSecondary;
1938 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1939 // Try to limit how much needs to be done inside
1940 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1942 vpindexSecondary.push_back(pindexIntermediate);
1943 pindexIntermediate = pindexIntermediate->pprev;
1946 if (!vpindexSecondary.empty())
1947 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
1949 // Switch to new best branch
1950 if (!Reorganize(txdb, pindexIntermediate))
1953 InvalidChainFound(pindexNew);
1954 return error("SetBestChain() : Reorganize failed");
1957 // Connect further blocks
1958 for (std::vector<CBlockIndex*>::reverse_iterator rit = vpindexSecondary.rbegin(); rit != vpindexSecondary.rend(); ++rit)
1961 if (!block.ReadFromDisk(*rit))
1963 printf("SetBestChain() : ReadFromDisk failed\n");
1966 if (!txdb.TxnBegin()) {
1967 printf("SetBestChain() : TxnBegin 2 failed\n");
1970 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1971 if (!block.SetBestChainInner(txdb, *rit))
1976 // Update best block in wallet (so we can detect restored wallets)
1977 bool fIsInitialDownload = IsInitialBlockDownload();
1978 if (!fIsInitialDownload)
1980 const CBlockLocator locator(pindexNew);
1981 ::SetBestChain(locator);
1985 hashBestChain = hash;
1986 pindexBest = pindexNew;
1987 pblockindexFBBHLast = NULL;
1988 nBestHeight = pindexBest->nHeight;
1989 nBestChainTrust = pindexNew->nChainTrust;
1990 nTimeBestReceived = GetTime();
1991 nTransactionsUpdated++;
1993 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1995 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1996 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1997 CBigNum(nBestChainTrust).ToString().c_str(),
1998 nBestBlockTrust.Get64(),
1999 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2001 // Check the version of the last 100 blocks to see if we need to upgrade:
2002 if (!fIsInitialDownload)
2005 const CBlockIndex* pindex = pindexBest;
2006 for (int i = 0; i < 100 && pindex != NULL; i++)
2008 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2010 pindex = pindex->pprev;
2013 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2014 if (nUpgraded > 100/2)
2015 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2016 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2019 std::string strCmd = GetArg("-blocknotify", "");
2021 if (!fIsInitialDownload && !strCmd.empty())
2023 boost::thread t(runCommand, regex_replace(strCmd, static_cast<std::regex>("%s"), hashBestChain.GetHex()));
2028 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2029 // Only those coins meeting minimum age requirement counts. As those
2030 // transactions not in main chain are not currently indexed so we
2031 // might not find out about their coin age. Older transactions are
2032 // guaranteed to be in main chain by sync-checkpoint. This rule is
2033 // introduced to help nodes establish a consistent view of the coin
2034 // age (trust score) of competing branches.
2035 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2037 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2043 for (const CTxIn& txin : vin)
2045 // First try finding the previous transaction in database
2046 CTransaction txPrev;
2048 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2049 continue; // previous transaction not in main chain
2050 if (nTime < txPrev.nTime)
2051 return false; // Transaction timestamp violation
2053 // Read block header
2055 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2056 return false; // unable to read block of previous transaction
2057 if (block.GetBlockTime() + nStakeMinAge > nTime)
2058 continue; // only count coins meeting min age requirement
2060 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
2061 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2063 if (fDebug && GetBoolArg("-printcoinage"))
2064 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2067 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / nOneDay;
2068 if (fDebug && GetBoolArg("-printcoinage"))
2069 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2070 nCoinAge = bnCoinDay.getuint64();
2074 // ppcoin: total coin age spent in block, in the unit of coin-days.
2075 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2080 for (const CTransaction& tx : vtx)
2082 uint64_t nTxCoinAge;
2083 if (tx.GetCoinAge(txdb, nTxCoinAge))
2084 nCoinAge += nTxCoinAge;
2089 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2091 if (fDebug && GetBoolArg("-printcoinage"))
2092 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2096 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2098 // Check for duplicate
2099 uint256 hash = GetHash();
2100 if (mapBlockIndex.count(hash))
2101 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2103 // Construct new block index object
2104 CBlockIndex* pindexNew = new(nothrow) CBlockIndex(nFile, nBlockPos, *this);
2106 return error("AddToBlockIndex() : new CBlockIndex failed");
2107 pindexNew->phashBlock = &hash;
2108 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2109 if (miPrev != mapBlockIndex.end())
2111 pindexNew->pprev = (*miPrev).second;
2112 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2115 // ppcoin: compute chain trust score
2116 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2118 // ppcoin: compute stake entropy bit for stake modifier
2119 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2120 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2122 // ppcoin: record proof-of-stake hash value
2123 if (pindexNew->IsProofOfStake())
2125 if (!mapProofOfStake.count(hash))
2126 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2127 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2130 // ppcoin: compute stake modifier
2131 uint64_t nStakeModifier = 0;
2132 bool fGeneratedStakeModifier = false;
2133 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2134 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2135 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2136 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2137 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2138 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2140 // Add to mapBlockIndex
2141 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2142 if (pindexNew->IsProofOfStake())
2143 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2144 pindexNew->phashBlock = &((*mi).first);
2146 // Write to disk block index
2148 if (!txdb.TxnBegin())
2150 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2151 if (!txdb.TxnCommit())
2155 if (pindexNew->nChainTrust > nBestChainTrust)
2156 if (!SetBestChain(txdb, pindexNew))
2159 if (pindexNew == pindexBest)
2161 // Notify UI to display prev block's coinbase if it was ours
2162 static uint256 hashPrevBestCoinBase;
2163 UpdatedTransaction(hashPrevBestCoinBase);
2164 hashPrevBestCoinBase = vtx[0].GetHash();
2167 static int8_t counter = 0;
2168 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2169 uiInterface.NotifyBlocksChanged();
2176 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2178 // These are checks that are independent of context
2179 // that can be verified before saving an orphan block.
2181 set<uint256> uniqueTx; // tx hashes
2182 unsigned int nSigOps = 0; // total sigops
2185 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2186 return DoS(100, error("CheckBlock() : size limits failed"));
2188 bool fProofOfStake = IsProofOfStake();
2190 // First transaction must be coinbase, the rest must not be
2191 if (!vtx[0].IsCoinBase())
2192 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2194 if (!vtx[0].CheckTransaction())
2195 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2197 uniqueTx.insert(vtx[0].GetHash());
2198 nSigOps += vtx[0].GetLegacySigOpCount();
2202 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2203 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2205 // nNonce must be zero for proof-of-stake blocks
2207 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2209 // Coinbase output should be empty if proof-of-stake block
2210 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2211 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2213 // Check coinstake timestamp
2214 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2215 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2217 // NovaCoin: check proof-of-stake block signature
2218 if (fCheckSig && !CheckBlockSignature())
2219 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2221 if (!vtx[1].CheckTransaction())
2222 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2224 uniqueTx.insert(vtx[1].GetHash());
2225 nSigOps += vtx[1].GetLegacySigOpCount();
2229 // Check proof of work matches claimed amount
2230 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2231 return DoS(50, error("CheckBlock() : proof of work failed"));
2234 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2235 return error("CheckBlock() : block timestamp too far in the future");
2237 // Check coinbase timestamp
2238 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2239 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2242 // Iterate all transactions starting from second for proof-of-stake block
2243 // or first for proof-of-work block
2244 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2246 const CTransaction& tx = vtx[i];
2248 // Reject coinbase transactions at non-zero index
2249 if (tx.IsCoinBase())
2250 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2252 // Reject coinstake transactions at index != 1
2253 if (tx.IsCoinStake())
2254 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2256 // Check transaction timestamp
2257 if (GetBlockTime() < (int64_t)tx.nTime)
2258 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2260 // Check transaction consistency
2261 if (!tx.CheckTransaction())
2262 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2264 // Add transaction hash into list of unique transaction IDs
2265 uniqueTx.insert(tx.GetHash());
2267 // Calculate sigops count
2268 nSigOps += tx.GetLegacySigOpCount();
2271 // Check for duplicate txids. This is caught by ConnectInputs(),
2272 // but catching it earlier avoids a potential DoS attack:
2273 if (uniqueTx.size() != vtx.size())
2274 return DoS(100, error("CheckBlock() : duplicate transaction"));
2276 // Reject block if validation would consume too much resources.
2277 if (nSigOps > MAX_BLOCK_SIGOPS)
2278 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2280 // Check merkle root
2281 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2282 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2287 bool CBlock::AcceptBlock()
2289 // Check for duplicate
2290 uint256 hash = GetHash();
2291 if (mapBlockIndex.count(hash))
2292 return error("AcceptBlock() : block already in mapBlockIndex");
2294 // Get prev block index
2295 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2296 if (mi == mapBlockIndex.end())
2297 return DoS(10, error("AcceptBlock() : prev block not found"));
2298 CBlockIndex* pindexPrev = (*mi).second;
2299 int nHeight = pindexPrev->nHeight+1;
2301 // Check proof-of-work or proof-of-stake
2302 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2303 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2305 int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
2306 int nMaxOffset = 12 * nOneHour; // 12 hours
2307 if (fTestNet || pindexPrev->nTime < 1450569600)
2308 nMaxOffset = 7 * nOneWeek; // One week (permanently on testNet or until 20 Dec, 2015 on mainNet)
2310 // Check timestamp against prev
2311 if (GetBlockTime() <= nMedianTimePast || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2312 return error("AcceptBlock() : block's timestamp is too early");
2314 // Don't accept blocks with future timestamps
2315 if (pindexPrev->nHeight > 1 && nMedianTimePast + nMaxOffset < GetBlockTime())
2316 return error("AcceptBlock() : block's timestamp is too far in the future");
2318 // Check that all transactions are finalized
2319 for (const CTransaction& tx : vtx)
2320 if (!tx.IsFinal(nHeight, GetBlockTime()))
2321 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2323 // Check that the block chain matches the known block chain up to a checkpoint
2324 if (!Checkpoints::CheckHardened(nHeight, hash))
2325 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2327 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2329 // Check that the block satisfies synchronized checkpoint
2330 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2331 return error("AcceptBlock() : rejected by synchronized checkpoint");
2333 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2334 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2336 // Enforce rule that the coinbase starts with serialized block height
2337 CScript expect = CScript() << nHeight;
2338 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2339 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2340 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2342 // Write block to history file
2343 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2344 return error("AcceptBlock() : out of disk space");
2345 unsigned int nFile = std::numeric_limits<unsigned int>::max();
2346 unsigned int nBlockPos = 0;
2347 if (!WriteToDisk(nFile, nBlockPos))
2348 return error("AcceptBlock() : WriteToDisk failed");
2349 if (!AddToBlockIndex(nFile, nBlockPos))
2350 return error("AcceptBlock() : AddToBlockIndex failed");
2352 // Relay inventory, but don't relay old inventory during initial block download
2353 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2354 if (hashBestChain == hash)
2357 for (CNode* pnode : vNodes)
2358 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2359 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2362 // ppcoin: check pending sync-checkpoint
2363 Checkpoints::AcceptPendingSyncCheckpoint();
2368 uint256 CBlockIndex::GetBlockTrust() const
2371 bnTarget.SetCompact(nBits);
2376 // Return 1 for the first 12 blocks
2377 if (pprev == NULL || pprev->nHeight < 12)
2380 const CBlockIndex* currentIndex = pprev;
2382 if(IsProofOfStake())
2384 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2386 // Return 1/3 of score if parent block is not the PoW block
2387 if (!pprev->IsProofOfWork())
2388 return (bnNewTrust / 3).getuint256();
2392 // Check last 12 blocks type
2393 while (pprev->nHeight - currentIndex->nHeight < 12)
2395 if (currentIndex->IsProofOfWork())
2397 currentIndex = currentIndex->pprev;
2400 // Return 1/3 of score if less than 3 PoW blocks found
2402 return (bnNewTrust / 3).getuint256();
2404 return bnNewTrust.getuint256();
2408 // Calculate work amount for block
2409 CBigNum bnPoWTrust = CBigNum(nPoWBase) / (bnTarget+1);
2411 // Set nPowTrust to 1 if PoW difficulty is too low
2415 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2417 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2418 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2419 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2423 // Check last 12 blocks type
2424 while (pprev->nHeight - currentIndex->nHeight < 12)
2426 if (currentIndex->IsProofOfStake())
2428 currentIndex = currentIndex->pprev;
2431 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2433 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2435 bnTarget.SetCompact(pprev->nBits);
2440 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2442 // Return nPoWTrust + full trust score for previous block nBits
2443 return (bnPoWTrust + bnNewTrust).getuint256();
2447 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2449 unsigned int nFound = 0;
2450 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2452 if (pstart->nVersion >= minVersion)
2454 pstart = pstart->pprev;
2456 return (nFound >= nRequired);
2459 bool static ReserealizeBlockSignature(CBlock* pblock)
2461 if (pblock->IsProofOfWork())
2463 pblock->vchBlockSig.clear();
2467 return CPubKey::ReserealizeSignature(pblock->vchBlockSig);
2470 bool static IsCanonicalBlockSignature(CBlock* pblock)
2472 if (pblock->IsProofOfWork())
2473 return pblock->vchBlockSig.empty();
2475 return IsDERSignature(pblock->vchBlockSig);
2478 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2480 // Check for duplicate
2481 uint256 hash = pblock->GetHash();
2482 if (mapBlockIndex.count(hash))
2483 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2484 if (mapOrphanBlocks.count(hash))
2485 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2487 // Check that block isn't listed as unconditionally banned.
2488 if (!Checkpoints::CheckBanned(hash)) {
2490 pfrom->Misbehaving(100);
2491 return error("ProcessBlock() : block %s is rejected by hard-coded banlist", hash.GetHex().substr(0,20).c_str());
2494 // Check proof-of-stake
2495 // Limited duplicity on stake: prevents block flood attack
2496 // Duplicate stake allowed only when there is orphan child block
2497 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2498 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());
2500 // Strip the garbage from newly received blocks, if we found some
2501 if (!IsCanonicalBlockSignature(pblock)) {
2502 if (!ReserealizeBlockSignature(pblock))
2503 printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2506 // Preliminary checks
2507 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2508 return error("ProcessBlock() : CheckBlock FAILED");
2510 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2511 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2513 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2514 int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2516 bnNewBlock.SetCompact(pblock->nBits);
2519 if (pblock->IsProofOfStake())
2520 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2522 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2524 if (bnNewBlock > bnRequired)
2527 pfrom->Misbehaving(100);
2528 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2533 // ppcoin: ask for pending sync-checkpoint if any
2534 if (!IsInitialBlockDownload())
2535 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2537 // If don't already have its previous block, shunt it off to holding area until we get it
2538 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2540 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2541 // ppcoin: check proof-of-stake
2542 if (pblock->IsProofOfStake())
2544 // Limited duplicity on stake: prevents block flood attack
2545 // Duplicate stake allowed only when there is orphan child block
2546 if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2547 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());
2549 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2551 CBlock* pblock2 = new CBlock(*pblock);
2552 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2553 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2555 // Ask this guy to fill in what we're missing
2558 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2559 // ppcoin: getblocks may not obtain the ancestor block rejected
2560 // earlier by duplicate-stake check so we ask for it again directly
2561 if (!IsInitialBlockDownload())
2562 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2567 // ppcoin: verify hash target and signature of coinstake tx
2568 if (pblock->IsProofOfStake())
2570 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2571 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2573 // Having prev block in index should be enough for validation
2574 if (mapBlockIndex.count(pblock->hashPrevBlock))
2575 return error("ProcessBlock(): check proof-of-stake (%s, %d) failed for block %s\n", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
2577 // Orphan blocks should be validated later once all parents successfully added to local chain
2578 printf("ProcessBlock(): delaying proof-of-stake validation for orphan block %s\n", hash.ToString().c_str());
2579 return false; // do not error here as we expect this to happen here
2582 // Needed for AcceptBlock()
2583 if (!mapProofOfStake.count(hash))
2584 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2588 if (!pblock->AcceptBlock())
2589 return error("ProcessBlock() : AcceptBlock FAILED");
2591 // Process any orphan blocks that depended on this one
2592 vector<uint256> vWorkQueue;
2593 vWorkQueue.push_back(hash);
2594 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2596 uint256 hashPrev = vWorkQueue[i];
2597 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2598 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2601 CBlock* pblockOrphan = (*mi).second;
2602 uint256 hashOrphanBlock = pblockOrphan->GetHash();
2604 if (pblockOrphan->IsProofOfStake()) {
2605 // Check proof-of-stake and do other contextual
2606 // preparations before running AcceptBlock()
2607 uint256 hashOrphanProofOfStake = 0;
2608 uint256 targetOrphanProofOfStake = 0;
2610 if (CheckProofOfStake(pblockOrphan->vtx[1], pblockOrphan->nBits, hashOrphanProofOfStake, targetOrphanProofOfStake))
2612 // Needed for AcceptBlock()
2613 if (!mapProofOfStake.count(hashOrphanBlock))
2614 mapProofOfStake.insert(make_pair(hashOrphanBlock, hashOrphanProofOfStake));
2616 // Finally, we're ready to run AcceptBlock()
2617 if (pblockOrphan->AcceptBlock())
2618 vWorkQueue.push_back(hashOrphanBlock);
2619 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2622 // proof-of-work verification
2623 // is notoriously simpler
2624 if (pblockOrphan->AcceptBlock())
2625 vWorkQueue.push_back(hashOrphanBlock);
2628 mapOrphanBlocks.erase(hashOrphanBlock);
2629 delete pblockOrphan;
2632 mapOrphanBlocksByPrev.erase(hashPrev);
2635 printf("ProcessBlock: ACCEPTED\n");
2637 // ppcoin: if responsible for sync-checkpoint send it
2638 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2639 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2644 // ppcoin: check block signature
2645 bool CBlock::CheckBlockSignature() const
2647 if (vchBlockSig.empty())
2650 txnouttype whichType;
2651 vector<valtype> vSolutions;
2652 if (!Solver(vtx[1].vout[1].scriptPubKey, whichType, vSolutions))
2655 if (whichType == TX_PUBKEY)
2657 valtype& vchPubKey = vSolutions[0];
2658 CPubKey key(vchPubKey);
2661 return key.Verify(GetHash(), vchBlockSig);
2667 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2669 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
2671 // Check for nMinDiskSpace bytes (currently 50MB)
2672 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2675 string strMessage = _("Warning: Disk space is low!");
2676 strMiscWarning = strMessage;
2677 printf("*** %s\n", strMessage.c_str());
2678 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2685 static boost::filesystem::path BlockFilePath(unsigned int nFile)
2687 string strBlockFn = strprintf("blk%04u.dat", nFile);
2688 return GetDataDir() / strBlockFn;
2691 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2693 if ((nFile < 1) || (nFile == std::numeric_limits<uint32_t>::max()))
2695 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2698 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2700 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2709 static unsigned int nCurrentBlockFile = 1;
2711 FILE* AppendBlockFile(unsigned int& nFileRet)
2716 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2719 if (fseek(file, 0, SEEK_END) != 0)
2721 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2722 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2724 nFileRet = nCurrentBlockFile;
2728 nCurrentBlockFile++;
2732 void UnloadBlockIndex()
2734 mapBlockIndex.clear();
2735 setStakeSeen.clear();
2736 pindexGenesisBlock = NULL;
2738 nBestChainTrust = 0;
2739 nBestInvalidTrust = 0;
2744 bool LoadBlockIndex(bool fAllowNew)
2748 pchMessageStart[0] = 0xcd;
2749 pchMessageStart[1] = 0xf2;
2750 pchMessageStart[2] = 0xc0;
2751 pchMessageStart[3] = 0xef;
2753 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2754 nStakeMinAge = 2 * nOneHour; // test net min age is 2 hours
2755 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2756 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2757 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2764 if (!txdb.LoadBlockIndex())
2768 // Init with genesis block
2770 if (mapBlockIndex.empty())
2779 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2780 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2781 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2783 // vMerkleTree: 4cb33b3b6a
2787 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2788 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2789 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2791 // vMerkleTree: 4cb33b3b6a
2793 const string strTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2795 txNew.nTime = 1360105017;
2796 txNew.vin.resize(1);
2797 txNew.vout.resize(1);
2798 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>(strTimestamp.begin(), strTimestamp.end());
2799 txNew.vout[0].SetEmpty();
2801 block.vtx.push_back(txNew);
2802 block.hashPrevBlock = 0;
2803 block.hashMerkleRoot = block.BuildMerkleTree();
2805 block.nTime = 1360105017;
2806 block.nBits = bnProofOfWorkLimit.GetCompact();
2807 block.nNonce = !fTestNet ? 1575379 : 46534;
2810 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2812 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2813 assert(block.CheckBlock());
2815 // Start new block file
2817 unsigned int nBlockPos;
2818 if (!block.WriteToDisk(nFile, nBlockPos))
2819 return error("LoadBlockIndex() : writing genesis block to disk failed");
2820 if (!block.AddToBlockIndex(nFile, nBlockPos))
2821 return error("LoadBlockIndex() : genesis block not accepted");
2823 // initialize synchronized checkpoint
2824 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2825 return error("LoadBlockIndex() : failed to init sync checkpoint");
2827 // upgrade time set to zero if txdb initialized
2829 if (!txdb.WriteModifierUpgradeTime(0))
2830 return error("LoadBlockIndex() : failed to init upgrade info");
2831 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2837 string strPubKey = "";
2838 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2840 // write checkpoint master key to db
2842 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2843 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2844 if (!txdb.TxnCommit())
2845 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2846 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2847 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2850 // upgrade time set to zero if blocktreedb initialized
2851 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2853 if (nModifierUpgradeTime)
2854 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2856 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2860 nModifierUpgradeTime = GetTime();
2861 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2862 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2863 return error("LoadBlockIndex() : failed to write upgrade info");
2872 void PrintBlockTree()
2874 // pre-compute tree structure
2875 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2876 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2878 CBlockIndex* pindex = (*mi).second;
2879 mapNext[pindex->pprev].push_back(pindex);
2881 //while (rand() % 3 == 0)
2882 // mapNext[pindex->pprev].push_back(pindex);
2885 vector<pair<int, CBlockIndex*> > vStack;
2886 vStack.push_back(make_pair(0, pindexGenesisBlock));
2889 while (!vStack.empty())
2891 int nCol = vStack.back().first;
2892 CBlockIndex* pindex = vStack.back().second;
2895 // print split or gap
2896 if (nCol > nPrevCol)
2898 for (int i = 0; i < nCol-1; i++)
2902 else if (nCol < nPrevCol)
2904 for (int i = 0; i < nCol; i++)
2911 for (int i = 0; i < nCol; i++)
2916 block.ReadFromDisk(pindex);
2917 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
2921 block.GetHash().ToString().c_str(),
2923 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2924 FormatMoney(pindex->nMint).c_str(),
2927 PrintWallets(block);
2929 // put the main time-chain first
2930 vector<CBlockIndex*>& vNext = mapNext[pindex];
2931 for (unsigned int i = 0; i < vNext.size(); i++)
2933 if (vNext[i]->pnext)
2935 swap(vNext[0], vNext[i]);
2941 for (unsigned int i = 0; i < vNext.size(); i++)
2942 vStack.push_back(make_pair(nCol+i, vNext[i]));
2946 bool LoadExternalBlockFile(FILE* fileIn)
2948 int64_t nStart = GetTimeMillis();
2954 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2955 unsigned int nPos = 0;
2956 while (nPos != std::numeric_limits<uint32_t>::max() && blkdat.good() && !fRequestShutdown)
2958 unsigned char pchData[65536];
2960 fseek(blkdat, nPos, SEEK_SET);
2961 size_t nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2964 nPos = std::numeric_limits<uint32_t>::max();
2967 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2970 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2972 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2975 nPos += ((unsigned char*)nFind - pchData) + 1;
2978 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2979 } while(!fRequestShutdown);
2980 if (nPos == std::numeric_limits<uint32_t>::max())
2982 fseek(blkdat, nPos, SEEK_SET);
2985 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2989 if (ProcessBlock(NULL,&block))
2997 catch (const std::exception&) {
2998 printf("%s() : Deserialize or I/O error caught during load\n",
2999 BOOST_CURRENT_FUNCTION);
3002 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3006 //////////////////////////////////////////////////////////////////////////////
3011 extern map<uint256, CAlert> mapAlerts;
3012 extern CCriticalSection cs_mapAlerts;
3014 string GetWarnings(string strFor)
3017 string strStatusBar;
3020 if (GetBoolArg("-testsafemode"))
3023 // Misc warnings like out of disk space and clock is wrong
3024 if (!strMiscWarning.empty())
3027 strStatusBar = strMiscWarning;
3030 // if detected unmet upgrade requirement enter safe mode
3031 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3032 if (IsFixedModifierInterval(nModifierUpgradeTime + nOneDay)) // 1 day margin
3035 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3038 // if detected invalid checkpoint enter safe mode
3039 if (Checkpoints::hashInvalidCheckpoint != 0)
3042 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3048 for (auto& item : mapAlerts)
3050 const CAlert& alert = item.second;
3051 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3053 nPriority = alert.nPriority;
3054 strStatusBar = alert.strStatusBar;
3055 if (nPriority > 1000)
3056 strRPC = strStatusBar;
3061 if (strFor == "statusbar")
3062 return strStatusBar;
3063 else if (strFor == "rpc")
3065 assert(!"GetWarnings() : invalid parameter");
3076 //////////////////////////////////////////////////////////////////////////////
3082 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3088 bool txInMap = false;
3091 txInMap = (mempool.exists(inv.hash));
3094 mapOrphanTransactions.count(inv.hash) ||
3095 txdb.ContainsTx(inv.hash);
3099 return mapBlockIndex.count(inv.hash) ||
3100 mapOrphanBlocks.count(inv.hash);
3102 // Don't know what it is, just say we already got one
3109 // The message start string is designed to be unlikely to occur in normal data.
3110 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3111 // a large 4-byte int at any alignment.
3112 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3114 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3116 static map<CService, CPubKey> mapReuseKey;
3117 RandAddSeedPerfmon();
3119 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3120 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3122 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3126 if (strCommand == "version")
3128 // Each connection can only send one version message
3129 if (pfrom->nVersion != 0)
3131 pfrom->Misbehaving(1);
3138 uint64_t nNonce = 1;
3139 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3140 if (pfrom->nVersion < MIN_PROTO_VERSION)
3142 // Since February 20, 2012, the protocol is initiated at version 209,
3143 // and earlier versions are no longer supported
3144 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3145 pfrom->fDisconnect = true;
3149 if (pfrom->nVersion == 10300)
3150 pfrom->nVersion = 300;
3152 vRecv >> addrFrom >> nNonce;
3154 vRecv >> pfrom->strSubVer;
3156 vRecv >> pfrom->nStartingHeight;
3158 if (pfrom->fInbound && addrMe.IsRoutable())
3160 pfrom->addrLocal = addrMe;
3164 // Disconnect if we connected to ourself
3165 if (nNonce == nLocalHostNonce && nNonce > 1)
3167 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3168 pfrom->fDisconnect = true;
3172 if (pfrom->nVersion < 60010)
3174 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3175 pfrom->fDisconnect = true;
3179 // record my external IP reported by peer
3180 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3181 addrSeenByPeer = addrMe;
3183 // Be shy and don't send version until we hear
3184 if (pfrom->fInbound)
3185 pfrom->PushVersion();
3187 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3189 AddTimeData(pfrom->addr, nTime);
3192 pfrom->PushMessage("verack");
3193 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3195 if (!pfrom->fInbound)
3197 // Advertise our address
3198 if (!fNoListen && !IsInitialBlockDownload())
3200 CAddress addr = GetLocalAddress(&pfrom->addr);
3201 if (addr.IsRoutable())
3202 pfrom->PushAddress(addr);
3205 // Get recent addresses
3206 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3208 pfrom->PushMessage("getaddr");
3209 pfrom->fGetAddr = true;
3211 addrman.Good(pfrom->addr);
3213 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3215 addrman.Add(addrFrom, addrFrom);
3216 addrman.Good(addrFrom);
3220 // Ask the first connected node for block updates
3221 static int nAskedForBlocks = 0;
3222 if (!pfrom->fClient && !pfrom->fOneShot &&
3223 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3224 (pfrom->nVersion < NOBLKS_VERSION_START ||
3225 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3226 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3229 pfrom->PushGetBlocks(pindexBest, uint256(0));
3235 for (auto& item : mapAlerts)
3236 item.second.RelayTo(pfrom);
3239 // Relay sync-checkpoint
3241 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3242 if (!Checkpoints::checkpointMessage.IsNull())
3243 Checkpoints::checkpointMessage.RelayTo(pfrom);
3246 pfrom->fSuccessfullyConnected = true;
3248 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());
3250 cPeerBlockCounts.input(pfrom->nStartingHeight);
3252 // ppcoin: ask for pending sync-checkpoint if any
3253 if (!IsInitialBlockDownload())
3254 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3258 else if (pfrom->nVersion == 0)
3260 // Must have a version message before anything else
3261 pfrom->Misbehaving(1);
3266 else if (strCommand == "verack")
3268 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3272 else if (strCommand == "addr")
3274 vector<CAddress> vAddr;
3277 // Don't want addr from older versions unless seeding
3278 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3280 if (vAddr.size() > 1000)
3282 pfrom->Misbehaving(20);
3283 return error("message addr size() = %" PRIszu "", vAddr.size());
3286 // Store the new addresses
3287 vector<CAddress> vAddrOk;
3288 int64_t nNow = GetAdjustedTime();
3289 int64_t nSince = nNow - 10 * 60;
3290 for (CAddress& addr : vAddr)
3294 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3295 addr.nTime = nNow - 5 * nOneDay;
3296 pfrom->AddAddressKnown(addr);
3297 bool fReachable = IsReachable(addr);
3298 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3300 // Relay to a limited number of other nodes
3303 // Use deterministic randomness to send to the same nodes for 24 hours
3304 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3305 static uint256 hashSalt;
3307 hashSalt = GetRandHash();
3308 uint64_t hashAddr = addr.GetHash();
3309 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/nOneDay);
3310 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3311 multimap<uint256, CNode*> mapMix;
3312 for (CNode* pnode : vNodes)
3314 if (pnode->nVersion < CADDR_TIME_VERSION)
3316 unsigned int nPointer;
3317 memcpy(&nPointer, &pnode, sizeof(nPointer));
3318 uint256 hashKey = hashRand ^ nPointer;
3319 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3320 mapMix.insert(make_pair(hashKey, pnode));
3322 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3323 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3324 ((*mi).second)->PushAddress(addr);
3327 // Do not store addresses outside our network
3329 vAddrOk.push_back(addr);
3331 addrman.Add(vAddrOk, pfrom->addr, 2 * nOneHour);
3332 if (vAddr.size() < 1000)
3333 pfrom->fGetAddr = false;
3334 if (pfrom->fOneShot)
3335 pfrom->fDisconnect = true;
3338 else if (strCommand == "inv")
3342 if (vInv.size() > MAX_INV_SZ)
3344 pfrom->Misbehaving(20);
3345 return error("message inv size() = %" PRIszu "", vInv.size());
3348 // find last block in inv vector
3349 size_t nLastBlock = std::numeric_limits<size_t>::max();
3350 for (size_t nInv = 0; nInv < vInv.size(); nInv++) {
3351 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3352 nLastBlock = vInv.size() - 1 - nInv;
3357 for (size_t nInv = 0; nInv < vInv.size(); nInv++)
3359 const CInv &inv = vInv[nInv];
3363 pfrom->AddInventoryKnown(inv);
3365 bool fAlreadyHave = AlreadyHave(txdb, inv);
3367 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3371 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3372 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3373 } else if (nInv == nLastBlock) {
3374 // In case we are on a very long side-chain, it is possible that we already have
3375 // the last block in an inv bundle sent in response to getblocks. Try to detect
3376 // this situation and push another getblocks to continue.
3377 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3379 printf("force request: %s\n", inv.ToString().c_str());
3382 // Track requests for our stuff
3383 Inventory(inv.hash);
3388 else if (strCommand == "getdata")
3392 if (vInv.size() > MAX_INV_SZ)
3394 pfrom->Misbehaving(20);
3395 return error("message getdata size() = %" PRIszu "", vInv.size());
3398 if (fDebugNet || (vInv.size() != 1))
3399 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3401 for (const CInv& inv : vInv)
3405 if (fDebugNet || (vInv.size() == 1))
3406 printf("received getdata for: %s\n", inv.ToString().c_str());
3408 if (inv.type == MSG_BLOCK)
3410 // Send block from disk
3411 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3412 if (mi != mapBlockIndex.end())
3415 block.ReadFromDisk((*mi).second);
3416 pfrom->PushMessage("block", block);
3418 // Trigger them to send a getblocks request for the next batch of inventory
3419 if (inv.hash == pfrom->hashContinue)
3421 // ppcoin: send latest proof-of-work block to allow the
3422 // download node to accept as orphan (proof-of-stake
3423 // block might be rejected by stake connection check)
3425 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3426 pfrom->PushMessage("inv", vInv);
3427 pfrom->hashContinue = 0;
3431 else if (inv.IsKnownType())
3433 // Send stream from relay memory
3434 bool pushed = false;
3437 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3438 if (mi != mapRelay.end()) {
3439 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3443 if (!pushed && inv.type == MSG_TX) {
3445 if (mempool.exists(inv.hash)) {
3446 CTransaction tx = mempool.lookup(inv.hash);
3447 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3450 pfrom->PushMessage("tx", ss);
3455 // Track requests for our stuff
3456 Inventory(inv.hash);
3461 else if (strCommand == "getblocks")
3463 CBlockLocator locator;
3465 vRecv >> locator >> hashStop;
3467 // Find the last block the caller has in the main chain
3468 CBlockIndex* pindex = locator.GetBlockIndex();
3470 // Send the rest of the chain
3472 pindex = pindex->pnext;
3474 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3475 for (; pindex; pindex = pindex->pnext)
3477 if (pindex->GetBlockHash() == hashStop)
3479 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3480 // ppcoin: tell downloading node about the latest block if it's
3481 // without risk being rejected due to stake connection check
3482 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3483 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3486 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3489 // When this block is requested, we'll send an inv that'll make them
3490 // getblocks the next batch of inventory.
3491 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3492 pfrom->hashContinue = pindex->GetBlockHash();
3497 else if (strCommand == "checkpoint")
3499 CSyncCheckpoint checkpoint;
3500 vRecv >> checkpoint;
3502 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3505 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3507 for (CNode* pnode : vNodes)
3508 checkpoint.RelayTo(pnode);
3512 else if (strCommand == "getheaders")
3514 CBlockLocator locator;
3516 vRecv >> locator >> hashStop;
3518 CBlockIndex* pindex = NULL;
3519 if (locator.IsNull())
3521 // If locator is null, return the hashStop block
3522 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3523 if (mi == mapBlockIndex.end())
3525 pindex = (*mi).second;
3529 // Find the last block the caller has in the main chain
3530 pindex = locator.GetBlockIndex();
3532 pindex = pindex->pnext;
3535 vector<CBlock> vHeaders;
3537 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3538 for (; pindex; pindex = pindex->pnext)
3540 vHeaders.push_back(pindex->GetBlockHeader());
3541 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3544 pfrom->PushMessage("headers", vHeaders);
3548 else if (strCommand == "tx")
3550 vector<uint256> vWorkQueue;
3551 vector<uint256> vEraseQueue;
3552 CDataStream vMsg(vRecv);
3557 CInv inv(MSG_TX, tx.GetHash());
3558 pfrom->AddInventoryKnown(inv);
3560 bool fMissingInputs = false;
3561 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3563 SyncWithWallets(tx, NULL, true);
3564 RelayTransaction(tx, inv.hash);
3565 mapAlreadyAskedFor.erase(inv);
3566 vWorkQueue.push_back(inv.hash);
3567 vEraseQueue.push_back(inv.hash);
3569 // Recursively process any orphan transactions that depended on this one
3570 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3572 uint256 hashPrev = vWorkQueue[i];
3573 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3574 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3577 const uint256& orphanTxHash = *mi;
3578 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3579 bool fMissingInputs2 = false;
3581 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3583 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3584 SyncWithWallets(tx, NULL, true);
3585 RelayTransaction(orphanTx, orphanTxHash);
3586 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3587 vWorkQueue.push_back(orphanTxHash);
3588 vEraseQueue.push_back(orphanTxHash);
3590 else if (!fMissingInputs2)
3593 vEraseQueue.push_back(orphanTxHash);
3594 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3599 for (uint256 hash : vEraseQueue)
3600 EraseOrphanTx(hash);
3602 else if (fMissingInputs)
3606 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3607 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3609 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3611 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3615 else if (strCommand == "block")
3619 uint256 hashBlock = block.GetHash();
3621 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3624 CInv inv(MSG_BLOCK, hashBlock);
3625 pfrom->AddInventoryKnown(inv);
3627 if (ProcessBlock(pfrom, &block))
3628 mapAlreadyAskedFor.erase(inv);
3629 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3633 // This asymmetric behavior for inbound and outbound connections was introduced
3634 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
3635 // to users' AddrMan and later request them by sending getaddr messages.
3636 // Making users (which are behind NAT and can only make outgoing connections) ignore
3637 // getaddr message mitigates the attack.
3638 else if ((strCommand == "getaddr") && (pfrom->fInbound))
3640 // Don't return addresses older than nCutOff timestamp
3641 int64_t nCutOff = GetTime() - (nNodeLifespan * nOneDay);
3642 pfrom->vAddrToSend.clear();
3643 vector<CAddress> vAddr = addrman.GetAddr();
3644 for (const CAddress &addr : vAddr)
3645 if(addr.nTime > nCutOff)
3646 pfrom->PushAddress(addr);
3650 else if (strCommand == "mempool")
3652 std::vector<uint256> vtxid;
3653 mempool.queryHashes(vtxid);
3655 for (unsigned int i = 0; i < vtxid.size(); i++) {
3656 CInv inv(MSG_TX, vtxid[i]);
3657 vInv.push_back(inv);
3658 if (i == (MAX_INV_SZ - 1))
3661 if (vInv.size() > 0)
3662 pfrom->PushMessage("inv", vInv);
3666 else if (strCommand == "checkorder")
3671 if (!GetBoolArg("-allowreceivebyip"))
3673 pfrom->PushMessage("reply", hashReply, 2, string(""));
3680 /// we have a chance to check the order here
3682 // Keep giving the same key to the same ip until they use it
3683 if (!mapReuseKey.count(pfrom->addr))
3684 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3686 // Send back approval of order and pubkey to use
3687 CScript scriptPubKey;
3688 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3689 pfrom->PushMessage("reply", hashReply, 0, scriptPubKey);
3693 else if (strCommand == "reply")
3698 CRequestTracker tracker;
3700 LOCK(pfrom->cs_mapRequests);
3701 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3702 if (mi != pfrom->mapRequests.end())
3704 tracker = (*mi).second;
3705 pfrom->mapRequests.erase(mi);
3708 if (!tracker.IsNull())
3709 tracker.fn(tracker.param1, vRecv);
3713 else if (strCommand == "ping")
3717 // Echo the message back with the nonce. This allows for two useful features:
3719 // 1) A remote node can quickly check if the connection is operational
3720 // 2) Remote nodes can measure the latency of the network thread. If this node
3721 // is overloaded it won't respond to pings quickly and the remote node can
3722 // avoid sending us more work, like chain download requests.
3724 // The nonce stops the remote getting confused between different pings: without
3725 // it, if the remote node sends a ping once per second and this node takes 5
3726 // seconds to respond to each, the 5th ping the remote sends would appear to
3727 // return very quickly.
3728 pfrom->PushMessage("pong", nonce);
3732 else if (strCommand == "alert")
3737 uint256 alertHash = alert.GetHash();
3738 if (pfrom->setKnown.count(alertHash) == 0)
3740 if (alert.ProcessAlert())
3743 pfrom->setKnown.insert(alertHash);
3746 for (CNode* pnode : vNodes)
3747 alert.RelayTo(pnode);
3751 // Small DoS penalty so peers that send us lots of
3752 // duplicate/expired/invalid-signature/whatever alerts
3753 // eventually get banned.
3754 // This isn't a Misbehaving(100) (immediate ban) because the
3755 // peer might be an older or different implementation with
3756 // a different signature key, etc.
3757 pfrom->Misbehaving(10);
3765 // Ignore unknown commands for extensibility
3769 // Update the last seen time for this node's address
3770 if (pfrom->fNetworkNode)
3771 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3772 AddressCurrentlyConnected(pfrom->addr);
3778 bool ProcessMessages(CNode* pfrom)
3780 CDataStream& vRecv = pfrom->vRecv;
3784 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3788 // (4) message start
3797 // Don't bother if send buffer is too full to respond anyway
3798 if (pfrom->vSend.size() >= SendBufferSize())
3801 // Scan for message start
3802 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3803 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3804 if (vRecv.end() - pstart < nHeaderSize)
3806 if ((int)vRecv.size() > nHeaderSize)
3808 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3809 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3813 if (pstart - vRecv.begin() > 0)
3814 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
3815 vRecv.erase(vRecv.begin(), pstart);
3818 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3823 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3826 string strCommand = hdr.GetCommand();
3829 unsigned int nMessageSize = hdr.nMessageSize;
3830 if (nMessageSize > MAX_SIZE)
3832 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3835 if (nMessageSize > vRecv.size())
3837 // Rewind and wait for rest of message
3838 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3843 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3844 unsigned int nChecksum = 0;
3845 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3846 if (nChecksum != hdr.nChecksum)
3848 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3849 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3853 // Copy message to its own buffer
3854 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3855 vRecv.ignore(nMessageSize);
3863 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3868 catch (std::ios_base::failure& e)
3870 if (strstr(e.what(), "end of data"))
3872 // Allow exceptions from under-length message on vRecv
3873 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());
3875 else if (strstr(e.what(), "size too large"))
3877 // Allow exceptions from over-long size
3878 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3882 PrintExceptionContinue(&e, "ProcessMessages()");
3885 catch (std::exception& e) {
3886 PrintExceptionContinue(&e, "ProcessMessages()");
3888 PrintExceptionContinue(NULL, "ProcessMessages()");
3892 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3902 bool SendMessages(CNode* pto)
3904 TRY_LOCK(cs_main, lockMain);
3906 // Current time in microseconds
3907 int64_t nNow = GetTimeMicros();
3909 // Don't send anything until we get their version message
3910 if (pto->nVersion == 0)
3913 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3915 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
3917 pto->PushMessage("ping", nonce);
3921 if (pto->fStartSync) {
3922 pto->fStartSync = false;
3923 pto->PushGetBlocks(pindexBest, uint256(0));
3926 // Resend wallet transactions that haven't gotten in a block yet
3927 ResendWalletTransactions();
3929 // Address refresh broadcast
3930 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3931 AdvertiseLocal(pto);
3932 pto->nNextLocalAddrSend = PoissonNextSend(nNow, nOneDay);
3938 if (pto->nNextAddrSend < nNow) {
3939 pto->nNextAddrSend = PoissonNextSend(nNow, 30);
3940 vector<CAddress> vAddr;
3941 vAddr.reserve(pto->vAddrToSend.size());
3942 for (const CAddress& addr : pto->vAddrToSend)
3944 if (pto->setAddrKnown.insert(addr).second)
3946 vAddr.push_back(addr);
3947 // receiver rejects addr messages larger than 1000
3948 if (vAddr.size() >= 1000)
3950 pto->PushMessage("addr", vAddr);
3955 pto->vAddrToSend.clear();
3957 pto->PushMessage("addr", vAddr);
3961 // Message: inventory
3964 vector<CInv> vInvWait;
3966 bool fSendTrickle = false;
3967 if (pto->nNextInvSend < nNow) {
3968 fSendTrickle = true;
3969 pto->nNextInvSend = PoissonNextSend(nNow, 5);
3971 LOCK(pto->cs_inventory);
3972 vInv.reserve(pto->vInventoryToSend.size());
3973 vInvWait.reserve(pto->vInventoryToSend.size());
3974 for (const CInv& inv : pto->vInventoryToSend)
3976 if (pto->setInventoryKnown.count(inv))
3979 // trickle out tx inv to protect privacy
3980 if (inv.type == MSG_TX && !fSendTrickle)
3982 // 1/4 of tx invs blast to all immediately
3983 static uint256 hashSalt;
3985 hashSalt = GetRandHash();
3986 uint256 hashRand = inv.hash ^ hashSalt;
3987 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3988 bool fTrickleWait = ((hashRand & 3) != 0);
3992 vInvWait.push_back(inv);
3997 // returns true if wasn't already contained in the set
3998 if (pto->setInventoryKnown.insert(inv).second)
4000 vInv.push_back(inv);
4001 if (vInv.size() >= 1000)
4003 pto->PushMessage("inv", vInv);
4008 pto->vInventoryToSend = vInvWait;
4011 pto->PushMessage("inv", vInv);
4017 vector<CInv> vGetData;
4019 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4021 const CInv& inv = (*pto->mapAskFor.begin()).second;
4022 if (!AlreadyHave(txdb, inv))
4025 printf("sending getdata: %s\n", inv.ToString().c_str());
4026 vGetData.push_back(inv);
4027 if (vGetData.size() >= 1000)
4029 pto->PushMessage("getdata", vGetData);
4032 mapAlreadyAskedFor[inv] = nNow;
4034 pto->mapAskFor.erase(pto->mapAskFor.begin());
4036 if (!vGetData.empty())
4037 pto->PushMessage("getdata", vGetData);
4050 std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4051 for (; it1 != mapBlockIndex.end(); it1++)
4052 delete (*it1).second;
4053 mapBlockIndex.clear();
4056 std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4057 for (; it2 != mapOrphanBlocks.end(); it2++)
4058 delete (*it2).second;
4059 mapOrphanBlocks.clear();
4061 // orphan transactions
4063 } instance_of_cmaincleanup;