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"
18 #include <boost/filesystem.hpp>
19 #include <boost/filesystem/fstream.hpp>
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
29 CCriticalSection cs_main;
32 unsigned int nTransactionsUpdated = 0;
34 map<uint256, CBlockIndex*> mapBlockIndex;
35 set<pair<COutPoint, unsigned int> > setStakeSeen;
37 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
38 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
39 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
40 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
41 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
43 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
45 unsigned int nStakeMinAge = 30 * nOneDay; // 30 days as zero time weight
46 unsigned int nStakeMaxAge = 90 * nOneDay; // 90 days as full weight
47 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
48 unsigned int nModifierInterval = 6 * nOneHour; // time to elapse before new modifier is computed
50 int nCoinbaseMaturity = 500;
52 CBlockIndex* pindexGenesisBlock = NULL;
55 uint256 nBestChainTrust = 0;
56 uint256 nBestInvalidTrust = 0;
58 uint256 hashBestChain = 0;
59 CBlockIndex* pindexBest = NULL;
60 int64_t nTimeBestReceived = 0;
61 int nScriptCheckThreads = 0;
63 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
65 map<uint256, CBlock*> mapOrphanBlocks;
66 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
67 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
68 map<uint256, uint256> mapProofOfStake;
70 map<uint256, CTransaction> mapOrphanTransactions;
71 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
73 // Constant stuff for coinbase transactions we create:
74 CScript COINBASE_FLAGS;
76 const string strMessageMagic = "NovaCoin Signed Message:\n";
79 int64_t nTransactionFee = MIN_TX_FEE;
80 int64_t nMinimumInputValue = MIN_TXOUT_AMOUNT;
82 // Ping and address broadcast intervals
83 int64_t nPingInterval = 30 * 60;
85 extern enum Checkpoints::CPMode CheckpointsMode;
87 //////////////////////////////////////////////////////////////////////////////
89 // dispatching functions
92 // These functions dispatch to one or all registered wallets
95 void RegisterWallet(CWallet* pwalletIn)
98 LOCK(cs_setpwalletRegistered);
99 setpwalletRegistered.insert(pwalletIn);
103 void UnregisterWallet(CWallet* pwalletIn)
106 LOCK(cs_setpwalletRegistered);
107 setpwalletRegistered.erase(pwalletIn);
111 // check whether the passed transaction is from us
112 bool static IsFromMe(CTransaction& tx)
114 for (CWallet* pwallet : setpwalletRegistered)
115 if (pwallet->IsFromMe(tx))
120 // erases transaction with the given hash from all wallets
121 void static EraseFromWallets(uint256 hash)
123 for (CWallet* pwallet : setpwalletRegistered)
124 pwallet->EraseFromWallet(hash);
127 // make sure all wallets know about the given transaction, in the given block
128 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
132 // wallets need to refund inputs when disconnecting coinstake
133 if (tx.IsCoinStake())
135 for (CWallet* pwallet : setpwalletRegistered)
136 if (pwallet->IsFromMe(tx))
137 pwallet->DisableTransaction(tx);
142 for (CWallet* pwallet : setpwalletRegistered)
143 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
146 // notify wallets about a new best chain
147 void static SetBestChain(const CBlockLocator& loc)
149 for (CWallet* pwallet : setpwalletRegistered)
150 pwallet->SetBestChain(loc);
153 // notify wallets about an updated transaction
154 void static UpdatedTransaction(const uint256& hashTx)
156 for (CWallet* pwallet : setpwalletRegistered)
157 pwallet->UpdatedTransaction(hashTx);
161 void static PrintWallets(const CBlock& block)
163 for (CWallet* pwallet : setpwalletRegistered)
164 pwallet->PrintWallet(block);
167 // notify wallets about an incoming inventory (for request counts)
168 void static Inventory(const uint256& hash)
170 for (CWallet* pwallet : setpwalletRegistered)
171 pwallet->Inventory(hash);
174 // ask wallets to resend their transactions
175 void ResendWalletTransactions(bool fForceResend)
177 for (CWallet* pwallet : setpwalletRegistered)
178 pwallet->ResendWalletTransactions(fForceResend);
187 //////////////////////////////////////////////////////////////////////////////
189 // mapOrphanTransactions
192 bool AddOrphanTx(const CTransaction& tx)
194 uint256 hash = tx.GetHash();
195 if (mapOrphanTransactions.count(hash))
198 // Ignore big transactions, to avoid a
199 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
200 // large transaction with a missing parent then we assume
201 // it will rebroadcast it later, after the parent transaction(s)
202 // have been mined or received.
203 // 10,000 orphans, each of which is at most 5,000 bytes big is
204 // at most 500 megabytes of orphans:
206 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
210 printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
214 mapOrphanTransactions[hash] = tx;
215 for (const CTxIn& txin : tx.vin)
216 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
218 printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
219 mapOrphanTransactions.size());
223 void static EraseOrphanTx(uint256 hash)
225 if (!mapOrphanTransactions.count(hash))
227 const CTransaction& tx = mapOrphanTransactions[hash];
228 for (const CTxIn& txin : tx.vin)
230 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
231 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
232 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
234 mapOrphanTransactions.erase(hash);
237 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
239 unsigned int nEvicted = 0;
240 while (mapOrphanTransactions.size() > nMaxOrphans)
242 // Evict a random orphan:
243 uint256 randomhash = GetRandHash();
244 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
245 if (it == mapOrphanTransactions.end())
246 it = mapOrphanTransactions.begin();
247 EraseOrphanTx(it->first);
259 //////////////////////////////////////////////////////////////////////////////
261 // CTransaction and CTxIndex
264 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
267 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
269 if (!ReadFromDisk(txindexRet.pos))
271 if (prevout.n >= vout.size())
279 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
282 return ReadFromDisk(txdb, prevout, txindex);
285 bool CTransaction::ReadFromDisk(COutPoint prevout)
289 return ReadFromDisk(txdb, prevout, txindex);
292 bool CTransaction::IsStandard(string& strReason) const
294 if (nVersion > CTransaction::CURRENT_VERSION)
296 strReason = "version";
300 unsigned int nDataOut = 0;
301 txnouttype whichType;
302 for (const CTxIn& txin : vin)
304 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
305 // keys. (remember the 520 byte limit on redeemScript size) That works
306 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
307 // bytes of scriptSig, which we round off to 1650 bytes for some minor
308 // future-proofing. That's also enough to spend a 20-of-20
309 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
310 // considered standard)
311 if (txin.scriptSig.size() > 1650)
313 strReason = "scriptsig-size";
316 if (!txin.scriptSig.IsPushOnly())
318 strReason = "scriptsig-not-pushonly";
321 if (!txin.scriptSig.HasCanonicalPushes()) {
322 strReason = "txin-scriptsig-not-canonicalpushes";
326 for (const CTxOut& txout : vout) {
327 if (!::IsStandard(txout.scriptPubKey, whichType)) {
328 strReason = "scriptpubkey";
331 if (whichType == TX_NULL_DATA)
334 if (txout.nValue == 0) {
335 strReason = "txout-value=0";
338 if (!txout.scriptPubKey.HasCanonicalPushes()) {
339 strReason = "txout-scriptsig-not-canonicalpushes";
345 // only one OP_RETURN txout is permitted
347 strReason = "multi-op-return";
355 // Check transaction inputs, and make sure any
356 // pay-to-script-hash transactions are evaluating IsStandard scripts
358 // Why bother? To avoid denial-of-service attacks; an attacker
359 // can submit a standard HASH... OP_EQUAL transaction,
360 // which will get accepted into blocks. The redemption
361 // script can be anything; an attacker could use a very
362 // expensive-to-check-upon-redemption script like:
363 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
365 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
368 return true; // Coinbases don't use vin normally
370 for (unsigned int i = 0; i < vin.size(); i++)
372 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
374 vector<vector<unsigned char> > vSolutions;
375 txnouttype whichType;
376 // get the scriptPubKey corresponding to this input:
377 const CScript& prevScript = prev.scriptPubKey;
378 if (!Solver(prevScript, whichType, vSolutions))
380 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
381 if (nArgsExpected < 0)
384 // Transactions with extra stuff in their scriptSigs are
385 // non-standard. Note that this EvalScript() call will
386 // be quick, because if there are any operations
387 // beside "push data" in the scriptSig the
388 // IsStandard() call returns false
389 vector<vector<unsigned char> > stack;
390 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
393 if (whichType == TX_SCRIPTHASH)
397 CScript subscript(stack.back().begin(), stack.back().end());
398 vector<vector<unsigned char> > vSolutions2;
399 txnouttype whichType2;
400 if (!Solver(subscript, whichType2, vSolutions2))
402 if (whichType2 == TX_SCRIPTHASH)
406 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
409 nArgsExpected += tmpExpected;
412 if (stack.size() != (unsigned int)nArgsExpected)
420 CTransaction::GetLegacySigOpCount() const
422 unsigned int nSigOps = 0;
425 // Coinbase scriptsigs are never executed, so there is
426 // no sense in calculation of sigops.
427 for (const CTxIn& txin : vin)
429 nSigOps += txin.scriptSig.GetSigOpCount(false);
432 for (const CTxOut& txout : vout)
434 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
439 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
452 // Load the block this tx is in
454 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
456 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
461 // Update the tx's hashBlock
462 hashBlock = pblock->GetHash();
464 // Locate the transaction
465 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
466 if (pblock->vtx[nIndex] == *(CTransaction*)this)
468 if (nIndex == (int)pblock->vtx.size())
470 vMerkleBranch.clear();
472 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
476 // Fill in merkle branch
477 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
480 // Is the tx in a block that's in the main chain
481 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
482 if (mi == mapBlockIndex.end())
484 const CBlockIndex* pindex = (*mi).second;
485 if (!pindex || !pindex->IsInMainChain())
488 return pindexBest->nHeight - pindex->nHeight + 1;
491 bool CTransaction::CheckTransaction() const
493 // Basic checks that don't depend on any context
495 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
497 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
499 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
500 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
502 // Check for negative or overflow output values
503 int64_t nValueOut = 0;
504 for (unsigned int i = 0; i < vout.size(); i++)
506 const CTxOut& txout = vout[i];
507 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
508 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
510 if (txout.nValue < 0)
511 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
512 if (txout.nValue > MAX_MONEY)
513 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
514 nValueOut += txout.nValue;
515 if (!MoneyRange(nValueOut))
516 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
519 // Check for duplicate inputs
520 set<COutPoint> vInOutPoints;
521 for (const CTxIn& txin : vin)
523 if (vInOutPoints.count(txin.prevout))
525 vInOutPoints.insert(txin.prevout);
530 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
531 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
535 for (const CTxIn& txin : vin)
536 if (txin.prevout.IsNull())
537 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
543 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
545 int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
549 // Enforce 0.01 as minimum fee for coinstake
551 nMinRelayTxFee = CENT;
554 // Base fee is either nMinTxFee or nMinRelayTxFee
555 int64_t nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
557 unsigned int nNewBlockSize = nBlockSize + nBytes;
558 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
564 // Transactions under 1K are free
570 // Free transaction area
571 if (nNewBlockSize < 27000)
576 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
577 // each non empty output which is less than 0.01
579 // It's safe to ignore empty outputs here, because these inputs are allowed
580 // only for coinbase and coinstake transactions.
581 for (const CTxOut& txout : vout)
582 if (txout.nValue < CENT && !txout.IsEmpty())
585 // Raise the price as the block approaches full
586 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
588 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
590 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
593 if (!MoneyRange(nMinFee))
600 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
601 bool* pfMissingInputs)
604 *pfMissingInputs = false;
606 // Time (prevent mempool memory exhaustion attack)
607 if (tx.nTime > FutureDrift(GetAdjustedTime()))
608 return tx.DoS(10, error("CTxMemPool::accept() : transaction timestamp is too far in the future"));
610 if (!tx.CheckTransaction())
611 return error("CTxMemPool::accept() : CheckTransaction failed");
613 // Coinbase is only valid in a block, not as a loose transaction
615 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
617 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
618 if (tx.IsCoinStake())
619 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
621 // To help v0.1.5 clients who would see it as a negative number
622 if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
623 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
625 // Rather not work on nonstandard transactions (unless -testnet)
627 if (!fTestNet && !tx.IsStandard(strNonStd))
628 return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
630 // Do we already have it?
631 uint256 hash = tx.GetHash();
634 if (mapTx.count(hash))
638 if (txdb.ContainsTx(hash))
641 // Check for conflicts with in-memory transactions
642 CTransaction* ptxOld = NULL;
643 for (unsigned int i = 0; i < tx.vin.size(); i++)
645 COutPoint outpoint = tx.vin[i].prevout;
646 if (mapNextTx.count(outpoint))
648 // Disable replacement feature for now
651 // Allow replacing with a newer version of the same transaction
654 ptxOld = mapNextTx[outpoint].ptx;
655 if (ptxOld->IsFinal())
657 if (!tx.IsNewerThan(*ptxOld))
659 for (unsigned int i = 0; i < tx.vin.size(); i++)
661 COutPoint outpoint = tx.vin[i].prevout;
662 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
672 map<uint256, CTxIndex> mapUnused;
673 bool fInvalid = false;
674 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
677 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
679 *pfMissingInputs = true;
683 // Check for non-standard pay-to-script-hash in inputs
684 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
685 return error("CTxMemPool::accept() : nonstandard transaction input");
687 // Note: if you modify this code to accept non-standard transactions, then
688 // you should add code here to check that the transaction does a
689 // reasonable number of ECDSA signature verifications.
691 int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
692 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
694 // Don't accept it if it can't get into a block
695 int64_t txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
696 if (nFees < txMinFee)
697 return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
698 hash.ToString().c_str(),
701 // Continuously rate-limit free transactions
702 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
703 // be annoying or make others' transactions take longer to confirm.
704 if (nFees < MIN_RELAY_TX_FEE)
706 static CCriticalSection cs;
707 static double dFreeCount;
708 static int64_t nLastTime;
709 int64_t nNow = GetTime();
713 // Use an exponentially decaying ~10-minute window:
714 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
716 // -limitfreerelay unit is thousand-bytes-per-minute
717 // At default rate it would take over a month to fill 1GB
718 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
719 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
721 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
726 // Check against previous transactions
727 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
728 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, STRICT_FLAGS))
730 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
734 // Store transaction in memory
739 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
742 addUnchecked(hash, tx);
745 ///// are we sure this is ok when loading transactions or restoring block txes
746 // If updated, erase old tx from wallet
748 EraseFromWallets(ptxOld->GetHash());
750 printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
751 hash.ToString().substr(0,10).c_str(),
756 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
758 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
761 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
763 // Add to memory pool without checking anything. Don't call this directly,
764 // call CTxMemPool::accept to properly check the transaction first.
767 for (unsigned int i = 0; i < tx.vin.size(); i++)
768 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
769 nTransactionsUpdated++;
775 bool CTxMemPool::remove(CTransaction &tx)
777 // Remove transaction from memory pool
780 uint256 hash = tx.GetHash();
781 if (mapTx.count(hash))
783 for (const CTxIn& txin : tx.vin)
784 mapNextTx.erase(txin.prevout);
786 nTransactionsUpdated++;
792 void CTxMemPool::clear()
797 ++nTransactionsUpdated;
800 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
805 vtxid.reserve(mapTx.size());
806 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
807 vtxid.push_back((*mi).first);
813 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
815 if (hashBlock == 0 || nIndex == -1)
818 // Find the block it claims to be in
819 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
820 if (mi == mapBlockIndex.end())
822 CBlockIndex* pindex = (*mi).second;
823 if (!pindex || !pindex->IsInMainChain())
826 // Make sure the merkle branch connects to this block
827 if (!fMerkleVerified)
829 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
831 fMerkleVerified = true;
835 return pindexBest->nHeight - pindex->nHeight + 1;
839 int CMerkleTx::GetBlocksToMaturity() const
841 if (!(IsCoinBase() || IsCoinStake()))
843 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
847 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
851 if (!IsInMainChain() && !ClientConnectInputs())
853 return CTransaction::AcceptToMemoryPool(txdb, false);
857 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
861 bool CMerkleTx::AcceptToMemoryPool()
864 return AcceptToMemoryPool(txdb);
867 int CTxIndex::GetDepthInMainChain() const
871 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
873 // Find the block in the index
874 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
875 if (mi == mapBlockIndex.end())
877 CBlockIndex* pindex = (*mi).second;
878 if (!pindex || !pindex->IsInMainChain())
880 return 1 + nBestHeight - pindex->nHeight;
883 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
884 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
890 if (mempool.exists(hash))
892 tx = mempool.lookup(hash);
898 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
901 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
902 hashBlock = block.GetHash();
916 //////////////////////////////////////////////////////////////////////////////
918 // CBlock and CBlockIndex
921 static CBlockIndex* pblockindexFBBHLast;
922 CBlockIndex* FindBlockByHeight(int nHeight)
924 CBlockIndex *pblockindex;
925 if (nHeight < nBestHeight / 2)
926 pblockindex = pindexGenesisBlock;
928 pblockindex = pindexBest;
929 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
930 pblockindex = pblockindexFBBHLast;
931 while (pblockindex->nHeight > nHeight)
932 pblockindex = pblockindex->pprev;
933 while (pblockindex->nHeight < nHeight)
934 pblockindex = pblockindex->pnext;
935 pblockindexFBBHLast = pblockindex;
939 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
941 if (!fReadTransactions)
943 *this = pindex->GetBlockHeader();
946 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
948 if (GetHash() != pindex->GetBlockHash())
949 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
953 uint256 static GetOrphanRoot(const CBlock* pblock)
955 // Work back to the first block in the orphan chain
956 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
957 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
958 return pblock->GetHash();
961 // ppcoin: find block wanted by given orphan block
962 uint256 WantedByOrphan(const CBlock* pblockOrphan)
964 // Work back to the first block in the orphan chain
965 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
966 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
967 return pblockOrphan->hashPrevBlock;
970 // select stake target limit according to hard-coded conditions
971 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
973 if(fTestNet) // separate proof of stake target limit for testnet
974 return bnProofOfStakeLimit;
975 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
976 return bnProofOfStakeLimit;
977 if(nHeight + 1 > 15000) // 24 bits since block 15000
978 return bnProofOfStakeLegacyLimit;
979 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
980 return bnProofOfStakeHardLimit;
982 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
985 // miner's coin base reward based on nBits
986 int64_t GetProofOfWorkReward(unsigned int nBits)
988 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
991 bnTarget.SetCompact(nBits);
992 CBigNum bnTargetLimit = bnProofOfWorkLimit;
993 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
995 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
996 // A reasonably continuous curve is used to avoid shock to market
997 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
999 // Human readable form:
1001 // nSubsidy = 100 / (diff ^ 1/6)
1003 // Please note that we're using bisection to find an approximate solutuion
1004 CBigNum bnLowerBound = CENT;
1005 CBigNum bnUpperBound = bnSubsidyLimit;
1006 while (bnLowerBound + CENT <= bnUpperBound)
1008 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1009 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1010 bnUpperBound = bnMidValue;
1012 bnLowerBound = bnMidValue;
1015 int64_t nSubsidy = bnUpperBound.getuint64();
1017 nSubsidy = (nSubsidy / CENT) * CENT;
1018 if (fDebug && GetBoolArg("-printcreation"))
1019 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1021 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
1024 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1025 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1027 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1029 // Stage 2 of emission process is mostly PoS-based.
1031 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1033 bnTarget.SetCompact(nBits);
1034 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1035 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1037 // A reasonably continuous curve is used to avoid shock to market
1039 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1040 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1041 bnMidPart, bnRewardPart;
1043 while (bnLowerBound + CENT <= bnUpperBound)
1045 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1048 // Reward for coin-year is cut in half every 8x multiply of PoS difficulty
1050 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1052 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1055 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1056 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1058 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1059 bnUpperBound = bnMidValue;
1061 bnLowerBound = bnMidValue;
1064 nRewardCoinYear = bnUpperBound.getuint64();
1065 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1068 return nRewardCoinYear;
1070 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1072 // Set reasonable reward limit for large inputs
1074 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1076 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1077 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1079 nSubsidy = min(nSubsidy, nSubsidyLimit);
1081 if (fDebug && GetBoolArg("-printcreation"))
1082 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1087 static const int64_t nTargetTimespan = 7 * nOneDay; // one week
1089 // get proof of work blocks max spacing according to hard-coded conditions
1090 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1092 if(nTime > TARGETS_SWITCH_TIME)
1093 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1096 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1098 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1102 // maximum nBits value could possible be required nTime after
1104 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1107 bnResult.SetCompact(nBase);
1109 while (nTime > 0 && bnResult < bnTargetLimit)
1111 // Maximum 200% adjustment per day...
1115 if (bnResult > bnTargetLimit)
1116 bnResult = bnTargetLimit;
1117 return bnResult.GetCompact();
1121 // minimum amount of work that could possibly be required nTime after
1122 // minimum proof-of-work required was nBase
1124 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1126 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1130 // minimum amount of stake that could possibly be required nTime after
1131 // minimum proof-of-stake required was nBase
1133 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1135 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1139 // ppcoin: find last block index up to pindex
1140 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1142 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1143 pindex = pindex->pprev;
1147 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1149 if (pindexLast == NULL)
1150 return bnProofOfWorkLimit.GetCompact(); // genesis block
1152 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1154 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1155 if (pindexPrev->pprev == NULL)
1156 return bnTargetLimit.GetCompact(); // first block
1157 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1158 if (pindexPrevPrev->pprev == NULL)
1159 return bnTargetLimit.GetCompact(); // second block
1161 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1163 // ppcoin: target change every block
1164 // ppcoin: retarget with exponential moving toward target spacing
1166 bnNew.SetCompact(pindexPrev->nBits);
1167 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1168 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1169 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1170 bnNew /= ((nInterval + 1) * nTargetSpacing);
1172 if (bnNew > bnTargetLimit)
1173 bnNew = bnTargetLimit;
1175 return bnNew.GetCompact();
1178 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1181 bnTarget.SetCompact(nBits);
1184 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1185 return error("CheckProofOfWork() : nBits below minimum work");
1187 // Check proof of work matches claimed amount
1188 if (hash > bnTarget.getuint256())
1189 return error("CheckProofOfWork() : hash doesn't match nBits");
1194 // Return maximum amount of blocks that other nodes claim to have
1195 int GetNumBlocksOfPeers()
1197 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1200 bool IsInitialBlockDownload()
1202 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1204 static int64_t nLastUpdate;
1205 static CBlockIndex* pindexLastBest;
1206 int64_t nCurrentTime = GetTime();
1207 if (pindexBest != pindexLastBest)
1209 pindexLastBest = pindexBest;
1210 nLastUpdate = nCurrentTime;
1212 return (nCurrentTime - nLastUpdate < 10 &&
1213 pindexBest->GetBlockTime() < nCurrentTime - nOneDay);
1216 void static InvalidChainFound(CBlockIndex* pindexNew)
1218 if (pindexNew->nChainTrust > nBestInvalidTrust)
1220 nBestInvalidTrust = pindexNew->nChainTrust;
1221 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1222 uiInterface.NotifyBlocksChanged();
1225 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1226 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1228 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1229 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1230 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1231 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1232 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1233 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1234 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1235 nBestBlockTrust.Get64(),
1236 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1240 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1242 nTime = max(GetBlockTime(), GetAdjustedTime());
1255 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1257 // Relinquish previous transactions' spent pointers
1260 for (const CTxIn& txin : vin)
1262 COutPoint prevout = txin.prevout;
1264 // Get prev txindex from disk
1266 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1267 return error("DisconnectInputs() : ReadTxIndex failed");
1269 if (prevout.n >= txindex.vSpent.size())
1270 return error("DisconnectInputs() : prevout.n out of range");
1272 // Mark outpoint as not spent
1273 txindex.vSpent[prevout.n].SetNull();
1276 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1277 return error("DisconnectInputs() : UpdateTxIndex failed");
1281 // Remove transaction from index
1282 // This can fail if a duplicate of this transaction was in a chain that got
1283 // reorganized away. This is only possible if this transaction was completely
1284 // spent, so erasing it would be a no-op anyway.
1285 txdb.EraseTxIndex(*this);
1291 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1292 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1294 // FetchInputs can return false either because we just haven't seen some inputs
1295 // (in which case the transaction should be stored as an orphan)
1296 // or because the transaction is malformed (in which case the transaction should
1297 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1301 return true; // Coinbase transactions have no inputs to fetch.
1303 for (unsigned int i = 0; i < vin.size(); i++)
1305 COutPoint prevout = vin[i].prevout;
1306 if (inputsRet.count(prevout.hash))
1307 continue; // Got it already
1310 CTxIndex& txindex = inputsRet[prevout.hash].first;
1312 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1314 // Get txindex from current proposed changes
1315 txindex = mapTestPool.find(prevout.hash)->second;
1319 // Read txindex from txdb
1320 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1322 if (!fFound && (fBlock || fMiner))
1323 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());
1326 CTransaction& txPrev = inputsRet[prevout.hash].second;
1327 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1329 // Get prev tx from single transactions in memory
1332 if (!mempool.exists(prevout.hash))
1333 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());
1334 txPrev = mempool.lookup(prevout.hash);
1337 txindex.vSpent.resize(txPrev.vout.size());
1341 // Get prev tx from disk
1342 if (!txPrev.ReadFromDisk(txindex.pos))
1343 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1347 // Make sure all prevout.n indexes are valid:
1348 for (unsigned int i = 0; i < vin.size(); i++)
1350 const COutPoint prevout = vin[i].prevout;
1351 assert(inputsRet.count(prevout.hash) != 0);
1352 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1353 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1354 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1356 // Revisit this if/when transaction replacement is implemented and allows
1359 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()));
1366 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1368 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1369 if (mi == inputs.end())
1370 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1372 const CTransaction& txPrev = (mi->second).second;
1373 if (input.prevout.n >= txPrev.vout.size())
1374 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1376 return txPrev.vout[input.prevout.n];
1379 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1384 int64_t nResult = 0;
1385 for (unsigned int i = 0; i < vin.size(); i++)
1387 nResult += GetOutputFor(vin[i], inputs).nValue;
1393 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1398 unsigned int nSigOps = 0;
1399 for (unsigned int i = 0; i < vin.size(); i++)
1401 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1402 if (prevout.scriptPubKey.IsPayToScriptHash())
1403 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1408 bool CScriptCheck::operator()() const {
1409 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1410 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1411 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1415 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1417 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1420 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1421 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1423 // Take over previous transactions' spent pointers
1424 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1425 // fMiner is true when called from the internal bitcoin miner
1426 // ... both are false when called from CTransaction::AcceptToMemoryPool
1430 int64_t nValueIn = 0;
1432 for (unsigned int i = 0; i < vin.size(); i++)
1434 COutPoint prevout = vin[i].prevout;
1435 assert(inputs.count(prevout.hash) > 0);
1436 CTxIndex& txindex = inputs[prevout.hash].first;
1437 CTransaction& txPrev = inputs[prevout.hash].second;
1439 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1440 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()));
1442 // If prev is coinbase or coinstake, check that it's matured
1443 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1444 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1445 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1446 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1448 // ppcoin: check transaction timestamp
1449 if (txPrev.nTime > nTime)
1450 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1452 // Check for negative or overflow input values
1453 nValueIn += txPrev.vout[prevout.n].nValue;
1454 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1455 return DoS(100, error("ConnectInputs() : txin values out of range"));
1460 pvChecks->reserve(vin.size());
1462 // The first loop above does all the inexpensive checks.
1463 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1464 // Helps prevent CPU exhaustion attacks.
1465 for (unsigned int i = 0; i < vin.size(); i++)
1467 COutPoint prevout = vin[i].prevout;
1468 assert(inputs.count(prevout.hash) > 0);
1469 CTxIndex& txindex = inputs[prevout.hash].first;
1470 CTransaction& txPrev = inputs[prevout.hash].second;
1472 // Check for conflicts (double-spend)
1473 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1474 // for an attacker to attempt to split the network.
1475 if (!txindex.vSpent[prevout.n].IsNull())
1476 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());
1478 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1479 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1480 // still computed and checked, and any change will be caught at the next checkpoint.
1484 CScriptCheck check(txPrev, *this, i, flags, 0);
1487 pvChecks->push_back(CScriptCheck());
1488 check.swap(pvChecks->back());
1492 if (flags & STRICT_FLAGS)
1494 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1495 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1497 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1499 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1503 // Mark outpoints as spent
1504 txindex.vSpent[prevout.n] = posThisTx;
1507 if (fBlock || fMiner)
1509 mapTestPool[prevout.hash] = txindex;
1515 if (nTime > Checkpoints::GetLastCheckpointTime())
1517 unsigned int nTxSize = GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
1519 // coin stake tx earns reward instead of paying fee
1521 if (!GetCoinAge(txdb, nCoinAge))
1522 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1524 int64_t nReward = GetValueOut() - nValueIn;
1525 int64_t nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1527 if (nReward > nCalculatedReward)
1528 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1533 if (nValueIn < GetValueOut())
1534 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1536 // Tally transaction fees
1537 int64_t nTxFee = nValueIn - GetValueOut();
1539 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1542 if (!MoneyRange(nFees))
1543 return DoS(100, error("ConnectInputs() : nFees out of range"));
1551 bool CTransaction::ClientConnectInputs()
1556 // Take over previous transactions' spent pointers
1559 int64_t nValueIn = 0;
1560 for (unsigned int i = 0; i < vin.size(); i++)
1562 // Get prev tx from single transactions in memory
1563 COutPoint prevout = vin[i].prevout;
1564 if (!mempool.exists(prevout.hash))
1566 CTransaction& txPrev = mempool.lookup(prevout.hash);
1568 if (prevout.n >= txPrev.vout.size())
1572 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1573 return error("ClientConnectInputs() : VerifySignature failed");
1575 ///// this is redundant with the mempool.mapNextTx stuff,
1576 ///// not sure which I want to get rid of
1577 ///// this has to go away now that posNext is gone
1578 // // Check for conflicts
1579 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1580 // return error("ConnectInputs() : prev tx already used");
1582 // // Flag outpoints as used
1583 // txPrev.vout[prevout.n].posNext = posThisTx;
1585 nValueIn += txPrev.vout[prevout.n].nValue;
1587 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1588 return error("ClientConnectInputs() : txin values out of range");
1590 if (GetValueOut() > nValueIn)
1600 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1602 // Disconnect in reverse order
1603 for (int i = vtx.size()-1; i >= 0; i--)
1604 if (!vtx[i].DisconnectInputs(txdb))
1607 // Update block index on disk without changing it in memory.
1608 // The memory index structure will be changed after the db commits.
1611 CDiskBlockIndex blockindexPrev(pindex->pprev);
1612 blockindexPrev.hashNext = 0;
1613 if (!txdb.WriteBlockIndex(blockindexPrev))
1614 return error("DisconnectBlock() : WriteBlockIndex failed");
1617 // ppcoin: clean up wallet after disconnecting coinstake
1618 for (CTransaction& tx : vtx)
1619 SyncWithWallets(tx, this, false, false);
1624 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1626 void ThreadScriptCheck(void*) {
1627 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1628 RenameThread("novacoin-scriptch");
1629 scriptcheckqueue.Thread();
1630 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1633 void ThreadScriptCheckQuit() {
1634 scriptcheckqueue.Quit();
1637 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1639 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1640 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1643 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1644 // unless those are already completely spent.
1645 // If such overwrites are allowed, coinbases and transactions depending upon those
1646 // can be duplicated to remove the ability to spend the first instance -- even after
1647 // being sent to another address.
1648 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1649 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1650 // already refuses previously-known transaction ids entirely.
1651 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1652 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1653 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1654 // initial block download.
1655 bool fEnforceBIP30 = true; // Always active in NovaCoin
1656 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1658 //// issue here: it doesn't know the version
1659 unsigned int nTxPos;
1661 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1662 // 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
1665 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1667 map<uint256, CTxIndex> mapQueuedChanges;
1668 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1671 int64_t nValueIn = 0;
1672 int64_t nValueOut = 0;
1673 unsigned int nSigOps = 0;
1674 for (CTransaction& tx : vtx)
1676 uint256 hashTx = tx.GetHash();
1678 if (fEnforceBIP30) {
1679 CTxIndex txindexOld;
1680 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1681 for (CDiskTxPos &pos : txindexOld.vSpent)
1687 nSigOps += tx.GetLegacySigOpCount();
1688 if (nSigOps > MAX_BLOCK_SIGOPS)
1689 return DoS(100, error("ConnectBlock() : too many sigops"));
1691 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1693 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1695 MapPrevTx mapInputs;
1696 if (tx.IsCoinBase())
1697 nValueOut += tx.GetValueOut();
1701 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1704 // Add in sigops done by pay-to-script-hash inputs;
1705 // this is to prevent a "rogue miner" from creating
1706 // an incredibly-expensive-to-validate block.
1707 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1708 if (nSigOps > MAX_BLOCK_SIGOPS)
1709 return DoS(100, error("ConnectBlock() : too many sigops"));
1711 int64_t nTxValueIn = tx.GetValueIn(mapInputs);
1712 int64_t nTxValueOut = tx.GetValueOut();
1713 nValueIn += nTxValueIn;
1714 nValueOut += nTxValueOut;
1715 if (!tx.IsCoinStake())
1716 nFees += nTxValueIn - nTxValueOut;
1718 unsigned int nFlags = SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH;
1720 if (tx.nTime >= CHECKLOCKTIMEVERIFY_SWITCH_TIME) {
1721 nFlags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1724 if (tx.nTime >= CHECKSEQUENCEVERIFY_SWITCH_TIME) {
1725 nFlags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1728 std::vector<CScriptCheck> vChecks;
1729 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, nFlags, nScriptCheckThreads ? &vChecks : NULL))
1731 control.Add(vChecks);
1734 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1737 if (!control.Wait())
1738 return DoS(100, false);
1740 if (IsProofOfWork())
1742 int64_t nBlockReward = GetProofOfWorkReward(nBits) + nFees;
1744 // Check coinbase reward
1745 if (vtx[0].GetValueOut() > nBlockReward)
1746 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1747 vtx[0].GetValueOut(),
1751 // track money supply and mint amount info
1752 pindex->nMint = nValueOut - nValueIn + nFees;
1753 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1754 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1755 return error("Connect() : WriteBlockIndex for pindex failed");
1757 // fees are not collected by proof-of-stake miners
1758 // fees are destroyed to compensate the entire network
1759 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1760 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
1765 // Write queued txindex changes
1766 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1768 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1769 return error("ConnectBlock() : UpdateTxIndex failed");
1772 // Update block index on disk without changing it in memory.
1773 // The memory index structure will be changed after the db commits.
1776 CDiskBlockIndex blockindexPrev(pindex->pprev);
1777 blockindexPrev.hashNext = pindex->GetBlockHash();
1778 if (!txdb.WriteBlockIndex(blockindexPrev))
1779 return error("ConnectBlock() : WriteBlockIndex failed");
1782 // Watch for transactions paying to me
1783 for (CTransaction& tx : vtx)
1784 SyncWithWallets(tx, this, true);
1790 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1792 printf("REORGANIZE\n");
1795 CBlockIndex* pfork = pindexBest;
1796 CBlockIndex* plonger = pindexNew;
1797 while (pfork != plonger)
1799 while (plonger->nHeight > pfork->nHeight)
1800 if ((plonger = plonger->pprev) == NULL)
1801 return error("Reorganize() : plonger->pprev is null");
1802 if (pfork == plonger)
1804 if ((pfork = pfork->pprev) == NULL)
1805 return error("Reorganize() : pfork->pprev is null");
1808 // List of what to disconnect
1809 vector<CBlockIndex*> vDisconnect;
1810 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1811 vDisconnect.push_back(pindex);
1813 // List of what to connect
1814 vector<CBlockIndex*> vConnect;
1815 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1816 vConnect.push_back(pindex);
1817 reverse(vConnect.begin(), vConnect.end());
1819 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());
1820 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());
1822 // Disconnect shorter branch
1823 vector<CTransaction> vResurrect;
1824 for (CBlockIndex* pindex : vDisconnect)
1827 if (!block.ReadFromDisk(pindex))
1828 return error("Reorganize() : ReadFromDisk for disconnect failed");
1829 if (!block.DisconnectBlock(txdb, pindex))
1830 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1832 // Queue memory transactions to resurrect
1833 for (const CTransaction& tx : block.vtx)
1834 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1835 vResurrect.push_back(tx);
1838 // Connect longer branch
1839 vector<CTransaction> vDelete;
1840 for (unsigned int i = 0; i < vConnect.size(); i++)
1842 CBlockIndex* pindex = vConnect[i];
1844 if (!block.ReadFromDisk(pindex))
1845 return error("Reorganize() : ReadFromDisk for connect failed");
1846 if (!block.ConnectBlock(txdb, pindex))
1849 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1852 // Queue memory transactions to delete
1853 for (const CTransaction& tx : block.vtx)
1854 vDelete.push_back(tx);
1856 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1857 return error("Reorganize() : WriteHashBestChain failed");
1859 // Make sure it's successfully written to disk before changing memory structure
1860 if (!txdb.TxnCommit())
1861 return error("Reorganize() : TxnCommit failed");
1863 // Disconnect shorter branch
1864 for (CBlockIndex* pindex : vDisconnect)
1866 pindex->pprev->pnext = NULL;
1868 // Connect longer branch
1869 for (CBlockIndex* pindex : vConnect)
1871 pindex->pprev->pnext = pindex;
1873 // Resurrect memory transactions that were in the disconnected branch
1874 for (CTransaction& tx : vResurrect)
1875 tx.AcceptToMemoryPool(txdb, false);
1877 // Delete redundant memory transactions that are in the connected branch
1878 for (CTransaction& tx : vDelete)
1881 printf("REORGANIZE: done\n");
1887 // Called from inside SetBestChain: attaches a block to the new best chain being built
1888 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1890 uint256 hash = GetHash();
1892 // Adding to current best branch
1893 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1896 InvalidChainFound(pindexNew);
1899 if (!txdb.TxnCommit())
1900 return error("SetBestChain() : TxnCommit failed");
1902 // Add to current best branch
1903 pindexNew->pprev->pnext = pindexNew;
1905 // Delete redundant memory transactions
1906 for (CTransaction& tx : vtx)
1912 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1914 uint256 hash = GetHash();
1916 if (!txdb.TxnBegin())
1917 return error("SetBestChain() : TxnBegin failed");
1919 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1921 txdb.WriteHashBestChain(hash);
1922 if (!txdb.TxnCommit())
1923 return error("SetBestChain() : TxnCommit failed");
1924 pindexGenesisBlock = pindexNew;
1926 else if (hashPrevBlock == hashBestChain)
1928 if (!SetBestChainInner(txdb, pindexNew))
1929 return error("SetBestChain() : SetBestChainInner failed");
1933 // the first block in the new chain that will cause it to become the new best chain
1934 CBlockIndex *pindexIntermediate = pindexNew;
1936 // list of blocks that need to be connected afterwards
1937 std::vector<CBlockIndex*> vpindexSecondary;
1939 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1940 // Try to limit how much needs to be done inside
1941 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1943 vpindexSecondary.push_back(pindexIntermediate);
1944 pindexIntermediate = pindexIntermediate->pprev;
1947 if (!vpindexSecondary.empty())
1948 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
1950 // Switch to new best branch
1951 if (!Reorganize(txdb, pindexIntermediate))
1954 InvalidChainFound(pindexNew);
1955 return error("SetBestChain() : Reorganize failed");
1958 // Connect further blocks
1959 for (std::vector<CBlockIndex*>::reverse_iterator rit = vpindexSecondary.rbegin(); rit != vpindexSecondary.rend(); ++rit)
1962 if (!block.ReadFromDisk(*rit))
1964 printf("SetBestChain() : ReadFromDisk failed\n");
1967 if (!txdb.TxnBegin()) {
1968 printf("SetBestChain() : TxnBegin 2 failed\n");
1971 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1972 if (!block.SetBestChainInner(txdb, *rit))
1977 // Update best block in wallet (so we can detect restored wallets)
1978 bool fIsInitialDownload = IsInitialBlockDownload();
1979 if (!fIsInitialDownload)
1981 const CBlockLocator locator(pindexNew);
1982 ::SetBestChain(locator);
1986 hashBestChain = hash;
1987 pindexBest = pindexNew;
1988 pblockindexFBBHLast = NULL;
1989 nBestHeight = pindexBest->nHeight;
1990 nBestChainTrust = pindexNew->nChainTrust;
1991 nTimeBestReceived = GetTime();
1992 nTransactionsUpdated++;
1994 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1996 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1997 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1998 CBigNum(nBestChainTrust).ToString().c_str(),
1999 nBestBlockTrust.Get64(),
2000 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2002 // Check the version of the last 100 blocks to see if we need to upgrade:
2003 if (!fIsInitialDownload)
2006 const CBlockIndex* pindex = pindexBest;
2007 for (int i = 0; i < 100 && pindex != NULL; i++)
2009 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2011 pindex = pindex->pprev;
2014 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2015 if (nUpgraded > 100/2)
2016 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2017 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2020 std::string strCmd = GetArg("-blocknotify", "");
2022 if (!fIsInitialDownload && !strCmd.empty())
2024 boost::thread t(runCommand, regex_replace(strCmd, static_cast<std::regex>("%s"), hashBestChain.GetHex()));
2029 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2030 // Only those coins meeting minimum age requirement counts. As those
2031 // transactions not in main chain are not currently indexed so we
2032 // might not find out about their coin age. Older transactions are
2033 // guaranteed to be in main chain by sync-checkpoint. This rule is
2034 // introduced to help nodes establish a consistent view of the coin
2035 // age (trust score) of competing branches.
2036 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2038 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2044 for (const CTxIn& txin : vin)
2046 // First try finding the previous transaction in database
2047 CTransaction txPrev;
2049 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2050 continue; // previous transaction not in main chain
2051 if (nTime < txPrev.nTime)
2052 return false; // Transaction timestamp violation
2054 // Read block header
2056 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2057 return false; // unable to read block of previous transaction
2058 if (block.GetBlockTime() + nStakeMinAge > nTime)
2059 continue; // only count coins meeting min age requirement
2061 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
2062 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2064 if (fDebug && GetBoolArg("-printcoinage"))
2065 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2068 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / nOneDay;
2069 if (fDebug && GetBoolArg("-printcoinage"))
2070 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2071 nCoinAge = bnCoinDay.getuint64();
2075 // ppcoin: total coin age spent in block, in the unit of coin-days.
2076 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2081 for (const CTransaction& tx : vtx)
2083 uint64_t nTxCoinAge;
2084 if (tx.GetCoinAge(txdb, nTxCoinAge))
2085 nCoinAge += nTxCoinAge;
2090 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2092 if (fDebug && GetBoolArg("-printcoinage"))
2093 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2097 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2099 // Check for duplicate
2100 uint256 hash = GetHash();
2101 if (mapBlockIndex.count(hash))
2102 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2104 // Construct new block index object
2105 CBlockIndex* pindexNew = new(nothrow) CBlockIndex(nFile, nBlockPos, *this);
2107 return error("AddToBlockIndex() : new CBlockIndex failed");
2108 pindexNew->phashBlock = &hash;
2109 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2110 if (miPrev != mapBlockIndex.end())
2112 pindexNew->pprev = (*miPrev).second;
2113 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2116 // ppcoin: compute chain trust score
2117 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2119 // ppcoin: compute stake entropy bit for stake modifier
2120 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2121 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2123 // ppcoin: record proof-of-stake hash value
2124 if (pindexNew->IsProofOfStake())
2126 if (!mapProofOfStake.count(hash))
2127 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2128 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2131 // ppcoin: compute stake modifier
2132 uint64_t nStakeModifier = 0;
2133 bool fGeneratedStakeModifier = false;
2134 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2135 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2136 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2137 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2138 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2139 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2141 // Add to mapBlockIndex
2142 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2143 if (pindexNew->IsProofOfStake())
2144 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2145 pindexNew->phashBlock = &((*mi).first);
2147 // Write to disk block index
2149 if (!txdb.TxnBegin())
2151 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2152 if (!txdb.TxnCommit())
2156 if (pindexNew->nChainTrust > nBestChainTrust)
2157 if (!SetBestChain(txdb, pindexNew))
2160 if (pindexNew == pindexBest)
2162 // Notify UI to display prev block's coinbase if it was ours
2163 static uint256 hashPrevBestCoinBase;
2164 UpdatedTransaction(hashPrevBestCoinBase);
2165 hashPrevBestCoinBase = vtx[0].GetHash();
2168 static int8_t counter = 0;
2169 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2170 uiInterface.NotifyBlocksChanged();
2177 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2179 // These are checks that are independent of context
2180 // that can be verified before saving an orphan block.
2182 set<uint256> uniqueTx; // tx hashes
2183 unsigned int nSigOps = 0; // total sigops
2186 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2187 return DoS(100, error("CheckBlock() : size limits failed"));
2189 bool fProofOfStake = IsProofOfStake();
2191 // First transaction must be coinbase, the rest must not be
2192 if (!vtx[0].IsCoinBase())
2193 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2195 if (!vtx[0].CheckTransaction())
2196 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2198 uniqueTx.insert(vtx[0].GetHash());
2199 nSigOps += vtx[0].GetLegacySigOpCount();
2203 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2204 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2206 // nNonce must be zero for proof-of-stake blocks
2208 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2210 // Coinbase output should be empty if proof-of-stake block
2211 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2212 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2214 // Check coinstake timestamp
2215 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2216 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2218 // NovaCoin: check proof-of-stake block signature
2219 if (fCheckSig && !CheckBlockSignature())
2220 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2222 if (!vtx[1].CheckTransaction())
2223 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2225 uniqueTx.insert(vtx[1].GetHash());
2226 nSigOps += vtx[1].GetLegacySigOpCount();
2230 // Check proof of work matches claimed amount
2231 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2232 return DoS(50, error("CheckBlock() : proof of work failed"));
2235 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2236 return error("CheckBlock() : block timestamp too far in the future");
2238 // Check coinbase timestamp
2239 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2240 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2243 // Iterate all transactions starting from second for proof-of-stake block
2244 // or first for proof-of-work block
2245 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2247 const CTransaction& tx = vtx[i];
2249 // Reject coinbase transactions at non-zero index
2250 if (tx.IsCoinBase())
2251 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2253 // Reject coinstake transactions at index != 1
2254 if (tx.IsCoinStake())
2255 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2257 // Check transaction timestamp
2258 if (GetBlockTime() < (int64_t)tx.nTime)
2259 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2261 // Check transaction consistency
2262 if (!tx.CheckTransaction())
2263 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2265 // Add transaction hash into list of unique transaction IDs
2266 uniqueTx.insert(tx.GetHash());
2268 // Calculate sigops count
2269 nSigOps += tx.GetLegacySigOpCount();
2272 // Check for duplicate txids. This is caught by ConnectInputs(),
2273 // but catching it earlier avoids a potential DoS attack:
2274 if (uniqueTx.size() != vtx.size())
2275 return DoS(100, error("CheckBlock() : duplicate transaction"));
2277 // Reject block if validation would consume too much resources.
2278 if (nSigOps > MAX_BLOCK_SIGOPS)
2279 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2281 // Check merkle root
2282 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2283 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2288 bool CBlock::AcceptBlock()
2290 // Check for duplicate
2291 uint256 hash = GetHash();
2292 if (mapBlockIndex.count(hash))
2293 return error("AcceptBlock() : block already in mapBlockIndex");
2295 // Get prev block index
2296 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2297 if (mi == mapBlockIndex.end())
2298 return DoS(10, error("AcceptBlock() : prev block not found"));
2299 CBlockIndex* pindexPrev = (*mi).second;
2300 int nHeight = pindexPrev->nHeight+1;
2302 // Check proof-of-work or proof-of-stake
2303 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2304 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2306 int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
2307 int nMaxOffset = 12 * nOneHour; // 12 hours
2308 if (fTestNet || pindexPrev->nTime < 1450569600)
2309 nMaxOffset = 7 * nOneWeek; // One week (permanently on testNet or until 20 Dec, 2015 on mainNet)
2311 // Check timestamp against prev
2312 if (GetBlockTime() <= nMedianTimePast || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2313 return error("AcceptBlock() : block's timestamp is too early");
2315 // Don't accept blocks with future timestamps
2316 if (pindexPrev->nHeight > 1 && nMedianTimePast + nMaxOffset < GetBlockTime())
2317 return error("AcceptBlock() : block's timestamp is too far in the future");
2319 // Check that all transactions are finalized
2320 for (const CTransaction& tx : vtx)
2321 if (!tx.IsFinal(nHeight, GetBlockTime()))
2322 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2324 // Check that the block chain matches the known block chain up to a checkpoint
2325 if (!Checkpoints::CheckHardened(nHeight, hash))
2326 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2328 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2330 // Check that the block satisfies synchronized checkpoint
2331 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2332 return error("AcceptBlock() : rejected by synchronized checkpoint");
2334 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2335 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2337 // Enforce rule that the coinbase starts with serialized block height
2338 CScript expect = CScript() << nHeight;
2339 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2340 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2341 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2343 // Write block to history file
2344 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2345 return error("AcceptBlock() : out of disk space");
2346 unsigned int nFile = std::numeric_limits<unsigned int>::max();
2347 unsigned int nBlockPos = 0;
2348 if (!WriteToDisk(nFile, nBlockPos))
2349 return error("AcceptBlock() : WriteToDisk failed");
2350 if (!AddToBlockIndex(nFile, nBlockPos))
2351 return error("AcceptBlock() : AddToBlockIndex failed");
2353 // Relay inventory, but don't relay old inventory during initial block download
2354 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2355 if (hashBestChain == hash)
2358 for (CNode* pnode : vNodes)
2359 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2360 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2363 // ppcoin: check pending sync-checkpoint
2364 Checkpoints::AcceptPendingSyncCheckpoint();
2369 uint256 CBlockIndex::GetBlockTrust() const
2372 bnTarget.SetCompact(nBits);
2377 // Return 1 for the first 12 blocks
2378 if (pprev == NULL || pprev->nHeight < 12)
2381 const CBlockIndex* currentIndex = pprev;
2383 if(IsProofOfStake())
2385 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2387 // Return 1/3 of score if parent block is not the PoW block
2388 if (!pprev->IsProofOfWork())
2389 return (bnNewTrust / 3).getuint256();
2393 // Check last 12 blocks type
2394 while (pprev->nHeight - currentIndex->nHeight < 12)
2396 if (currentIndex->IsProofOfWork())
2398 currentIndex = currentIndex->pprev;
2401 // Return 1/3 of score if less than 3 PoW blocks found
2403 return (bnNewTrust / 3).getuint256();
2405 return bnNewTrust.getuint256();
2409 // Calculate work amount for block
2410 CBigNum bnPoWTrust = CBigNum(nPoWBase) / (bnTarget+1);
2412 // Set nPowTrust to 1 if PoW difficulty is too low
2416 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2418 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2419 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2420 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2424 // Check last 12 blocks type
2425 while (pprev->nHeight - currentIndex->nHeight < 12)
2427 if (currentIndex->IsProofOfStake())
2429 currentIndex = currentIndex->pprev;
2432 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2434 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2436 bnTarget.SetCompact(pprev->nBits);
2441 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2443 // Return nPoWTrust + full trust score for previous block nBits
2444 return (bnPoWTrust + bnNewTrust).getuint256();
2448 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2450 unsigned int nFound = 0;
2451 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2453 if (pstart->nVersion >= minVersion)
2455 pstart = pstart->pprev;
2457 return (nFound >= nRequired);
2460 bool static ReserealizeBlockSignature(CBlock* pblock)
2462 if (pblock->IsProofOfWork())
2464 pblock->vchBlockSig.clear();
2468 return CPubKey::ReserealizeSignature(pblock->vchBlockSig);
2471 bool static IsCanonicalBlockSignature(CBlock* pblock)
2473 if (pblock->IsProofOfWork())
2474 return pblock->vchBlockSig.empty();
2476 return IsDERSignature(pblock->vchBlockSig);
2479 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2481 // Check for duplicate
2482 uint256 hash = pblock->GetHash();
2483 if (mapBlockIndex.count(hash))
2484 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2485 if (mapOrphanBlocks.count(hash))
2486 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2488 // Check that block isn't listed as unconditionally banned.
2489 if (!Checkpoints::CheckBanned(hash)) {
2491 pfrom->Misbehaving(100);
2492 return error("ProcessBlock() : block %s is rejected by hard-coded banlist", hash.GetHex().substr(0,20).c_str());
2495 // Check proof-of-stake
2496 // Limited duplicity on stake: prevents block flood attack
2497 // Duplicate stake allowed only when there is orphan child block
2498 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2499 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());
2501 // Strip the garbage from newly received blocks, if we found some
2502 if (!IsCanonicalBlockSignature(pblock)) {
2503 if (!ReserealizeBlockSignature(pblock))
2504 printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2507 // Preliminary checks
2508 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2509 return error("ProcessBlock() : CheckBlock FAILED");
2511 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2512 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2514 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2515 int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2517 bnNewBlock.SetCompact(pblock->nBits);
2520 if (pblock->IsProofOfStake())
2521 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2523 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2525 if (bnNewBlock > bnRequired)
2528 pfrom->Misbehaving(100);
2529 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2534 // ppcoin: ask for pending sync-checkpoint if any
2535 if (!IsInitialBlockDownload())
2536 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2538 // If don't already have its previous block, shunt it off to holding area until we get it
2539 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2541 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2542 // ppcoin: check proof-of-stake
2543 if (pblock->IsProofOfStake())
2545 // Limited duplicity on stake: prevents block flood attack
2546 // Duplicate stake allowed only when there is orphan child block
2547 if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2548 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());
2550 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2552 CBlock* pblock2 = new CBlock(*pblock);
2553 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2554 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2556 // Ask this guy to fill in what we're missing
2559 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2560 // ppcoin: getblocks may not obtain the ancestor block rejected
2561 // earlier by duplicate-stake check so we ask for it again directly
2562 if (!IsInitialBlockDownload())
2563 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2568 // ppcoin: verify hash target and signature of coinstake tx
2569 if (pblock->IsProofOfStake())
2571 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2572 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2574 // Having prev block in index should be enough for validation
2575 if (mapBlockIndex.count(pblock->hashPrevBlock))
2576 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());
2578 // Orphan blocks should be validated later once all parents successfully added to local chain
2579 printf("ProcessBlock(): delaying proof-of-stake validation for orphan block %s\n", hash.ToString().c_str());
2580 return false; // do not error here as we expect this to happen here
2583 // Needed for AcceptBlock()
2584 if (!mapProofOfStake.count(hash))
2585 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2589 if (!pblock->AcceptBlock())
2590 return error("ProcessBlock() : AcceptBlock FAILED");
2592 // Process any orphan blocks that depended on this one
2593 vector<uint256> vWorkQueue;
2594 vWorkQueue.push_back(hash);
2595 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2597 uint256 hashPrev = vWorkQueue[i];
2598 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2599 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2602 CBlock* pblockOrphan = (*mi).second;
2603 uint256 hashOrphanBlock = pblockOrphan->GetHash();
2605 if (pblockOrphan->IsProofOfStake()) {
2606 // Check proof-of-stake and do other contextual
2607 // preparations before running AcceptBlock()
2608 uint256 hashOrphanProofOfStake = 0;
2609 uint256 targetOrphanProofOfStake = 0;
2611 if (CheckProofOfStake(pblockOrphan->vtx[1], pblockOrphan->nBits, hashOrphanProofOfStake, targetOrphanProofOfStake))
2613 // Needed for AcceptBlock()
2614 if (!mapProofOfStake.count(hashOrphanBlock))
2615 mapProofOfStake.insert(make_pair(hashOrphanBlock, hashOrphanProofOfStake));
2617 // Finally, we're ready to run AcceptBlock()
2618 if (pblockOrphan->AcceptBlock())
2619 vWorkQueue.push_back(hashOrphanBlock);
2620 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2623 // proof-of-work verification
2624 // is notoriously simpler
2625 if (pblockOrphan->AcceptBlock())
2626 vWorkQueue.push_back(hashOrphanBlock);
2629 mapOrphanBlocks.erase(hashOrphanBlock);
2630 delete pblockOrphan;
2633 mapOrphanBlocksByPrev.erase(hashPrev);
2636 printf("ProcessBlock: ACCEPTED\n");
2638 // ppcoin: if responsible for sync-checkpoint send it
2639 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2640 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2645 // ppcoin: check block signature
2646 bool CBlock::CheckBlockSignature() const
2648 if (vchBlockSig.empty())
2651 txnouttype whichType;
2652 vector<valtype> vSolutions;
2653 if (!Solver(vtx[1].vout[1].scriptPubKey, whichType, vSolutions))
2656 if (whichType == TX_PUBKEY)
2658 valtype& vchPubKey = vSolutions[0];
2659 CPubKey key(vchPubKey);
2662 return key.Verify(GetHash(), vchBlockSig);
2668 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2670 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
2672 // Check for nMinDiskSpace bytes (currently 50MB)
2673 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2676 string strMessage = _("Warning: Disk space is low!");
2677 strMiscWarning = strMessage;
2678 printf("*** %s\n", strMessage.c_str());
2679 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2686 static boost::filesystem::path BlockFilePath(unsigned int nFile)
2688 string strBlockFn = strprintf("blk%04u.dat", nFile);
2689 return GetDataDir() / strBlockFn;
2692 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2694 if ((nFile < 1) || (nFile == std::numeric_limits<uint32_t>::max()))
2696 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2699 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2701 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2710 static unsigned int nCurrentBlockFile = 1;
2712 FILE* AppendBlockFile(unsigned int& nFileRet)
2717 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2720 if (fseek(file, 0, SEEK_END) != 0)
2722 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2723 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2725 nFileRet = nCurrentBlockFile;
2729 nCurrentBlockFile++;
2733 void UnloadBlockIndex()
2735 mapBlockIndex.clear();
2736 setStakeSeen.clear();
2737 pindexGenesisBlock = NULL;
2739 nBestChainTrust = 0;
2740 nBestInvalidTrust = 0;
2745 bool LoadBlockIndex(bool fAllowNew)
2749 pchMessageStart[0] = 0xcd;
2750 pchMessageStart[1] = 0xf2;
2751 pchMessageStart[2] = 0xc0;
2752 pchMessageStart[3] = 0xef;
2754 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2755 nStakeMinAge = 2 * nOneHour; // test net min age is 2 hours
2756 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2757 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2758 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2765 if (!txdb.LoadBlockIndex())
2769 // Init with genesis block
2771 if (mapBlockIndex.empty())
2780 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2781 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2782 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2784 // vMerkleTree: 4cb33b3b6a
2788 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2789 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2790 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2792 // vMerkleTree: 4cb33b3b6a
2794 const string strTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2796 txNew.nTime = 1360105017;
2797 txNew.vin.resize(1);
2798 txNew.vout.resize(1);
2799 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>(strTimestamp.begin(), strTimestamp.end());
2800 txNew.vout[0].SetEmpty();
2802 block.vtx.push_back(txNew);
2803 block.hashPrevBlock = 0;
2804 block.hashMerkleRoot = block.BuildMerkleTree();
2806 block.nTime = 1360105017;
2807 block.nBits = bnProofOfWorkLimit.GetCompact();
2808 block.nNonce = !fTestNet ? 1575379 : 46534;
2811 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2813 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2814 assert(block.CheckBlock());
2816 // Start new block file
2818 unsigned int nBlockPos;
2819 if (!block.WriteToDisk(nFile, nBlockPos))
2820 return error("LoadBlockIndex() : writing genesis block to disk failed");
2821 if (!block.AddToBlockIndex(nFile, nBlockPos))
2822 return error("LoadBlockIndex() : genesis block not accepted");
2824 // initialize synchronized checkpoint
2825 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2826 return error("LoadBlockIndex() : failed to init sync checkpoint");
2828 // upgrade time set to zero if txdb initialized
2830 if (!txdb.WriteModifierUpgradeTime(0))
2831 return error("LoadBlockIndex() : failed to init upgrade info");
2832 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2838 string strPubKey = "";
2839 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2841 // write checkpoint master key to db
2843 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2844 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2845 if (!txdb.TxnCommit())
2846 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2847 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2848 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2851 // upgrade time set to zero if blocktreedb initialized
2852 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2854 if (nModifierUpgradeTime)
2855 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2857 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2861 nModifierUpgradeTime = GetTime();
2862 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2863 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2864 return error("LoadBlockIndex() : failed to write upgrade info");
2873 void PrintBlockTree()
2875 // pre-compute tree structure
2876 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2877 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2879 CBlockIndex* pindex = (*mi).second;
2880 mapNext[pindex->pprev].push_back(pindex);
2882 //while (rand() % 3 == 0)
2883 // mapNext[pindex->pprev].push_back(pindex);
2886 vector<pair<int, CBlockIndex*> > vStack;
2887 vStack.push_back(make_pair(0, pindexGenesisBlock));
2890 while (!vStack.empty())
2892 int nCol = vStack.back().first;
2893 CBlockIndex* pindex = vStack.back().second;
2896 // print split or gap
2897 if (nCol > nPrevCol)
2899 for (int i = 0; i < nCol-1; i++)
2903 else if (nCol < nPrevCol)
2905 for (int i = 0; i < nCol; i++)
2912 for (int i = 0; i < nCol; i++)
2917 block.ReadFromDisk(pindex);
2918 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
2922 block.GetHash().ToString().c_str(),
2924 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2925 FormatMoney(pindex->nMint).c_str(),
2928 PrintWallets(block);
2930 // put the main time-chain first
2931 vector<CBlockIndex*>& vNext = mapNext[pindex];
2932 for (unsigned int i = 0; i < vNext.size(); i++)
2934 if (vNext[i]->pnext)
2936 swap(vNext[0], vNext[i]);
2942 for (unsigned int i = 0; i < vNext.size(); i++)
2943 vStack.push_back(make_pair(nCol+i, vNext[i]));
2947 bool LoadExternalBlockFile(FILE* fileIn)
2949 int64_t nStart = GetTimeMillis();
2955 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2956 unsigned int nPos = 0;
2957 while (nPos != std::numeric_limits<uint32_t>::max() && blkdat.good() && !fRequestShutdown)
2959 unsigned char pchData[65536];
2961 fseek(blkdat, nPos, SEEK_SET);
2962 size_t nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2965 nPos = std::numeric_limits<uint32_t>::max();
2968 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2971 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2973 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2976 nPos += ((unsigned char*)nFind - pchData) + 1;
2979 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2980 } while(!fRequestShutdown);
2981 if (nPos == std::numeric_limits<uint32_t>::max())
2983 fseek(blkdat, nPos, SEEK_SET);
2986 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2990 if (ProcessBlock(NULL,&block))
2998 catch (const std::exception&) {
2999 printf("%s() : Deserialize or I/O error caught during load\n",
3000 BOOST_CURRENT_FUNCTION);
3003 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3007 //////////////////////////////////////////////////////////////////////////////
3012 extern map<uint256, CAlert> mapAlerts;
3013 extern CCriticalSection cs_mapAlerts;
3015 string GetWarnings(string strFor)
3018 string strStatusBar;
3021 if (GetBoolArg("-testsafemode"))
3024 // Misc warnings like out of disk space and clock is wrong
3025 if (!strMiscWarning.empty())
3028 strStatusBar = strMiscWarning;
3031 // if detected unmet upgrade requirement enter safe mode
3032 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3033 if (IsFixedModifierInterval(nModifierUpgradeTime + nOneDay)) // 1 day margin
3036 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3039 // if detected invalid checkpoint enter safe mode
3040 if (Checkpoints::hashInvalidCheckpoint != 0)
3043 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3049 for (auto& item : mapAlerts)
3051 const CAlert& alert = item.second;
3052 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3054 nPriority = alert.nPriority;
3055 strStatusBar = alert.strStatusBar;
3056 if (nPriority > 1000)
3057 strRPC = strStatusBar;
3062 if (strFor == "statusbar")
3063 return strStatusBar;
3064 else if (strFor == "rpc")
3066 assert(!"GetWarnings() : invalid parameter");
3077 //////////////////////////////////////////////////////////////////////////////
3083 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3089 bool txInMap = false;
3092 txInMap = (mempool.exists(inv.hash));
3095 mapOrphanTransactions.count(inv.hash) ||
3096 txdb.ContainsTx(inv.hash);
3100 return mapBlockIndex.count(inv.hash) ||
3101 mapOrphanBlocks.count(inv.hash);
3103 // Don't know what it is, just say we already got one
3110 // The message start string is designed to be unlikely to occur in normal data.
3111 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3112 // a large 4-byte int at any alignment.
3113 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3115 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3117 static map<CService, CPubKey> mapReuseKey;
3118 RandAddSeedPerfmon();
3120 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3121 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3123 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3127 if (strCommand == "version")
3129 // Each connection can only send one version message
3130 if (pfrom->nVersion != 0)
3132 pfrom->Misbehaving(1);
3139 uint64_t nNonce = 1;
3140 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3141 if (pfrom->nVersion < MIN_PROTO_VERSION)
3143 // Since February 20, 2012, the protocol is initiated at version 209,
3144 // and earlier versions are no longer supported
3145 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3146 pfrom->fDisconnect = true;
3150 if (pfrom->nVersion == 10300)
3151 pfrom->nVersion = 300;
3153 vRecv >> addrFrom >> nNonce;
3155 vRecv >> pfrom->strSubVer;
3157 vRecv >> pfrom->nStartingHeight;
3159 if (pfrom->fInbound && addrMe.IsRoutable())
3161 pfrom->addrLocal = addrMe;
3165 // Disconnect if we connected to ourself
3166 if (nNonce == nLocalHostNonce && nNonce > 1)
3168 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3169 pfrom->fDisconnect = true;
3173 if (pfrom->nVersion < 60010)
3175 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3176 pfrom->fDisconnect = true;
3180 // record my external IP reported by peer
3181 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3182 addrSeenByPeer = addrMe;
3184 // Be shy and don't send version until we hear
3185 if (pfrom->fInbound)
3186 pfrom->PushVersion();
3188 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3190 AddTimeData(pfrom->addr, nTime);
3193 pfrom->PushMessage("verack");
3194 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3196 if (!pfrom->fInbound)
3198 // Advertise our address
3199 if (!fNoListen && !IsInitialBlockDownload())
3201 CAddress addr = GetLocalAddress(&pfrom->addr);
3202 if (addr.IsRoutable())
3203 pfrom->PushAddress(addr);
3206 // Get recent addresses
3207 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3209 pfrom->PushMessage("getaddr");
3210 pfrom->fGetAddr = true;
3212 addrman.Good(pfrom->addr);
3214 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3216 addrman.Add(addrFrom, addrFrom);
3217 addrman.Good(addrFrom);
3221 // Ask the first connected node for block updates
3222 static int nAskedForBlocks = 0;
3223 if (!pfrom->fClient && !pfrom->fOneShot &&
3224 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3225 (pfrom->nVersion < NOBLKS_VERSION_START ||
3226 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3227 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3230 pfrom->PushGetBlocks(pindexBest, uint256(0));
3236 for (auto& item : mapAlerts)
3237 item.second.RelayTo(pfrom);
3240 // Relay sync-checkpoint
3242 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3243 if (!Checkpoints::checkpointMessage.IsNull())
3244 Checkpoints::checkpointMessage.RelayTo(pfrom);
3247 pfrom->fSuccessfullyConnected = true;
3249 printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
3251 cPeerBlockCounts.input(pfrom->nStartingHeight);
3253 // ppcoin: ask for pending sync-checkpoint if any
3254 if (!IsInitialBlockDownload())
3255 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3259 else if (pfrom->nVersion == 0)
3261 // Must have a version message before anything else
3262 pfrom->Misbehaving(1);
3267 else if (strCommand == "verack")
3269 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3273 else if (strCommand == "addr")
3275 vector<CAddress> vAddr;
3278 // Don't want addr from older versions unless seeding
3279 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3281 if (vAddr.size() > 1000)
3283 pfrom->Misbehaving(20);
3284 return error("message addr size() = %" PRIszu "", vAddr.size());
3287 // Store the new addresses
3288 vector<CAddress> vAddrOk;
3289 int64_t nNow = GetAdjustedTime();
3290 int64_t nSince = nNow - 10 * 60;
3291 for (CAddress& addr : vAddr)
3295 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3296 addr.nTime = nNow - 5 * nOneDay;
3297 pfrom->AddAddressKnown(addr);
3298 bool fReachable = IsReachable(addr);
3299 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3301 // Relay to a limited number of other nodes
3304 // Use deterministic randomness to send to the same nodes for 24 hours
3305 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3306 static uint256 hashSalt;
3308 hashSalt = GetRandHash();
3309 uint64_t hashAddr = addr.GetHash();
3310 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/nOneDay);
3311 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3312 multimap<uint256, CNode*> mapMix;
3313 for (CNode* pnode : vNodes)
3315 if (pnode->nVersion < CADDR_TIME_VERSION)
3317 unsigned int nPointer;
3318 memcpy(&nPointer, &pnode, sizeof(nPointer));
3319 uint256 hashKey = hashRand ^ nPointer;
3320 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3321 mapMix.insert(make_pair(hashKey, pnode));
3323 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3324 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3325 ((*mi).second)->PushAddress(addr);
3328 // Do not store addresses outside our network
3330 vAddrOk.push_back(addr);
3332 addrman.Add(vAddrOk, pfrom->addr, 2 * nOneHour);
3333 if (vAddr.size() < 1000)
3334 pfrom->fGetAddr = false;
3335 if (pfrom->fOneShot)
3336 pfrom->fDisconnect = true;
3339 else if (strCommand == "inv")
3343 if (vInv.size() > MAX_INV_SZ)
3345 pfrom->Misbehaving(20);
3346 return error("message inv size() = %" PRIszu "", vInv.size());
3349 // find last block in inv vector
3350 size_t nLastBlock = std::numeric_limits<size_t>::max();
3351 for (size_t nInv = 0; nInv < vInv.size(); nInv++) {
3352 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3353 nLastBlock = vInv.size() - 1 - nInv;
3358 for (size_t nInv = 0; nInv < vInv.size(); nInv++)
3360 const CInv &inv = vInv[nInv];
3364 pfrom->AddInventoryKnown(inv);
3366 bool fAlreadyHave = AlreadyHave(txdb, inv);
3368 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3372 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3373 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3374 } else if (nInv == nLastBlock) {
3375 // In case we are on a very long side-chain, it is possible that we already have
3376 // the last block in an inv bundle sent in response to getblocks. Try to detect
3377 // this situation and push another getblocks to continue.
3378 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3380 printf("force request: %s\n", inv.ToString().c_str());
3383 // Track requests for our stuff
3384 Inventory(inv.hash);
3389 else if (strCommand == "getdata")
3393 if (vInv.size() > MAX_INV_SZ)
3395 pfrom->Misbehaving(20);
3396 return error("message getdata size() = %" PRIszu "", vInv.size());
3399 if (fDebugNet || (vInv.size() != 1))
3400 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3402 for (const CInv& inv : vInv)
3406 if (fDebugNet || (vInv.size() == 1))
3407 printf("received getdata for: %s\n", inv.ToString().c_str());
3409 if (inv.type == MSG_BLOCK)
3411 // Send block from disk
3412 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3413 if (mi != mapBlockIndex.end())
3416 block.ReadFromDisk((*mi).second);
3417 pfrom->PushMessage("block", block);
3419 // Trigger them to send a getblocks request for the next batch of inventory
3420 if (inv.hash == pfrom->hashContinue)
3422 // ppcoin: send latest proof-of-work block to allow the
3423 // download node to accept as orphan (proof-of-stake
3424 // block might be rejected by stake connection check)
3426 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3427 pfrom->PushMessage("inv", vInv);
3428 pfrom->hashContinue = 0;
3432 else if (inv.IsKnownType())
3434 // Send stream from relay memory
3435 bool pushed = false;
3438 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3439 if (mi != mapRelay.end()) {
3440 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3444 if (!pushed && inv.type == MSG_TX) {
3446 if (mempool.exists(inv.hash)) {
3447 CTransaction tx = mempool.lookup(inv.hash);
3448 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3451 pfrom->PushMessage("tx", ss);
3456 // Track requests for our stuff
3457 Inventory(inv.hash);
3462 else if (strCommand == "getblocks")
3464 CBlockLocator locator;
3466 vRecv >> locator >> hashStop;
3468 // Find the last block the caller has in the main chain
3469 CBlockIndex* pindex = locator.GetBlockIndex();
3471 // Send the rest of the chain
3473 pindex = pindex->pnext;
3475 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3476 for (; pindex; pindex = pindex->pnext)
3478 if (pindex->GetBlockHash() == hashStop)
3480 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3481 // ppcoin: tell downloading node about the latest block if it's
3482 // without risk being rejected due to stake connection check
3483 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3484 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3487 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3490 // When this block is requested, we'll send an inv that'll make them
3491 // getblocks the next batch of inventory.
3492 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3493 pfrom->hashContinue = pindex->GetBlockHash();
3498 else if (strCommand == "checkpoint")
3500 CSyncCheckpoint checkpoint;
3501 vRecv >> checkpoint;
3503 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3506 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3508 for (CNode* pnode : vNodes)
3509 checkpoint.RelayTo(pnode);
3513 else if (strCommand == "getheaders")
3515 CBlockLocator locator;
3517 vRecv >> locator >> hashStop;
3519 CBlockIndex* pindex = NULL;
3520 if (locator.IsNull())
3522 // If locator is null, return the hashStop block
3523 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3524 if (mi == mapBlockIndex.end())
3526 pindex = (*mi).second;
3530 // Find the last block the caller has in the main chain
3531 pindex = locator.GetBlockIndex();
3533 pindex = pindex->pnext;
3536 vector<CBlock> vHeaders;
3538 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3539 for (; pindex; pindex = pindex->pnext)
3541 vHeaders.push_back(pindex->GetBlockHeader());
3542 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3545 pfrom->PushMessage("headers", vHeaders);
3549 else if (strCommand == "tx")
3551 vector<uint256> vWorkQueue;
3552 vector<uint256> vEraseQueue;
3553 CDataStream vMsg(vRecv);
3558 CInv inv(MSG_TX, tx.GetHash());
3559 pfrom->AddInventoryKnown(inv);
3561 bool fMissingInputs = false;
3562 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3564 SyncWithWallets(tx, NULL, true);
3565 RelayTransaction(tx, inv.hash);
3566 mapAlreadyAskedFor.erase(inv);
3567 vWorkQueue.push_back(inv.hash);
3568 vEraseQueue.push_back(inv.hash);
3570 // Recursively process any orphan transactions that depended on this one
3571 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3573 uint256 hashPrev = vWorkQueue[i];
3574 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3575 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3578 const uint256& orphanTxHash = *mi;
3579 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3580 bool fMissingInputs2 = false;
3582 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3584 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3585 SyncWithWallets(tx, NULL, true);
3586 RelayTransaction(orphanTx, orphanTxHash);
3587 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3588 vWorkQueue.push_back(orphanTxHash);
3589 vEraseQueue.push_back(orphanTxHash);
3591 else if (!fMissingInputs2)
3594 vEraseQueue.push_back(orphanTxHash);
3595 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3600 for (uint256 hash : vEraseQueue)
3601 EraseOrphanTx(hash);
3603 else if (fMissingInputs)
3607 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3608 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3610 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3612 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3616 else if (strCommand == "block")
3620 uint256 hashBlock = block.GetHash();
3622 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3625 CInv inv(MSG_BLOCK, hashBlock);
3626 pfrom->AddInventoryKnown(inv);
3628 if (ProcessBlock(pfrom, &block))
3629 mapAlreadyAskedFor.erase(inv);
3630 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3634 // This asymmetric behavior for inbound and outbound connections was introduced
3635 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
3636 // to users' AddrMan and later request them by sending getaddr messages.
3637 // Making users (which are behind NAT and can only make outgoing connections) ignore
3638 // getaddr message mitigates the attack.
3639 else if ((strCommand == "getaddr") && (pfrom->fInbound))
3641 // Don't return addresses older than nCutOff timestamp
3642 int64_t nCutOff = GetTime() - (nNodeLifespan * nOneDay);
3643 pfrom->vAddrToSend.clear();
3644 vector<CAddress> vAddr = addrman.GetAddr();
3645 for (const CAddress &addr : vAddr)
3646 if(addr.nTime > nCutOff)
3647 pfrom->PushAddress(addr);
3651 else if (strCommand == "mempool")
3653 std::vector<uint256> vtxid;
3654 mempool.queryHashes(vtxid);
3656 for (unsigned int i = 0; i < vtxid.size(); i++) {
3657 CInv inv(MSG_TX, vtxid[i]);
3658 vInv.push_back(inv);
3659 if (i == (MAX_INV_SZ - 1))
3662 if (vInv.size() > 0)
3663 pfrom->PushMessage("inv", vInv);
3667 else if (strCommand == "checkorder")
3672 if (!GetBoolArg("-allowreceivebyip"))
3674 pfrom->PushMessage("reply", hashReply, 2, string(""));
3681 /// we have a chance to check the order here
3683 // Keep giving the same key to the same ip until they use it
3684 if (!mapReuseKey.count(pfrom->addr))
3685 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3687 // Send back approval of order and pubkey to use
3688 CScript scriptPubKey;
3689 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3690 pfrom->PushMessage("reply", hashReply, 0, scriptPubKey);
3694 else if (strCommand == "reply")
3699 CRequestTracker tracker;
3701 LOCK(pfrom->cs_mapRequests);
3702 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3703 if (mi != pfrom->mapRequests.end())
3705 tracker = (*mi).second;
3706 pfrom->mapRequests.erase(mi);
3709 if (!tracker.IsNull())
3710 tracker.fn(tracker.param1, vRecv);
3714 else if (strCommand == "ping")
3718 // Echo the message back with the nonce. This allows for two useful features:
3720 // 1) A remote node can quickly check if the connection is operational
3721 // 2) Remote nodes can measure the latency of the network thread. If this node
3722 // is overloaded it won't respond to pings quickly and the remote node can
3723 // avoid sending us more work, like chain download requests.
3725 // The nonce stops the remote getting confused between different pings: without
3726 // it, if the remote node sends a ping once per second and this node takes 5
3727 // seconds to respond to each, the 5th ping the remote sends would appear to
3728 // return very quickly.
3729 pfrom->PushMessage("pong", nonce);
3733 else if (strCommand == "alert")
3738 uint256 alertHash = alert.GetHash();
3739 if (pfrom->setKnown.count(alertHash) == 0)
3741 if (alert.ProcessAlert())
3744 pfrom->setKnown.insert(alertHash);
3747 for (CNode* pnode : vNodes)
3748 alert.RelayTo(pnode);
3752 // Small DoS penalty so peers that send us lots of
3753 // duplicate/expired/invalid-signature/whatever alerts
3754 // eventually get banned.
3755 // This isn't a Misbehaving(100) (immediate ban) because the
3756 // peer might be an older or different implementation with
3757 // a different signature key, etc.
3758 pfrom->Misbehaving(10);
3766 // Ignore unknown commands for extensibility
3770 // Update the last seen time for this node's address
3771 if (pfrom->fNetworkNode)
3772 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3773 AddressCurrentlyConnected(pfrom->addr);
3779 bool ProcessMessages(CNode* pfrom)
3781 CDataStream& vRecv = pfrom->vRecv;
3785 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3789 // (4) message start
3798 // Don't bother if send buffer is too full to respond anyway
3799 if (pfrom->vSend.size() >= SendBufferSize())
3802 // Scan for message start
3803 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3804 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3805 if (vRecv.end() - pstart < nHeaderSize)
3807 if ((int)vRecv.size() > nHeaderSize)
3809 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3810 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3814 if (pstart - vRecv.begin() > 0)
3815 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
3816 vRecv.erase(vRecv.begin(), pstart);
3819 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3824 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3827 string strCommand = hdr.GetCommand();
3830 unsigned int nMessageSize = hdr.nMessageSize;
3831 if (nMessageSize > MAX_SIZE)
3833 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3836 if (nMessageSize > vRecv.size())
3838 // Rewind and wait for rest of message
3839 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3844 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3845 unsigned int nChecksum = 0;
3846 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3847 if (nChecksum != hdr.nChecksum)
3849 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3850 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3854 // Copy message to its own buffer
3855 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3856 vRecv.ignore(nMessageSize);
3864 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3869 catch (std::ios_base::failure& e)
3871 if (strstr(e.what(), "end of data"))
3873 // Allow exceptions from under-length message on vRecv
3874 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());
3876 else if (strstr(e.what(), "size too large"))
3878 // Allow exceptions from over-long size
3879 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3883 PrintExceptionContinue(&e, "ProcessMessages()");
3886 catch (std::exception& e) {
3887 PrintExceptionContinue(&e, "ProcessMessages()");
3889 PrintExceptionContinue(NULL, "ProcessMessages()");
3893 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3903 bool SendMessages(CNode* pto)
3905 TRY_LOCK(cs_main, lockMain);
3907 // Current time in microseconds
3908 int64_t nNow = GetTimeMicros();
3910 // Don't send anything until we get their version message
3911 if (pto->nVersion == 0)
3914 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3916 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
3918 pto->PushMessage("ping", nonce);
3922 if (pto->fStartSync) {
3923 pto->fStartSync = false;
3924 pto->PushGetBlocks(pindexBest, uint256(0));
3927 // Resend wallet transactions that haven't gotten in a block yet
3928 ResendWalletTransactions();
3930 // Address refresh broadcast
3931 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3932 AdvertiseLocal(pto);
3933 pto->nNextLocalAddrSend = PoissonNextSend(nNow, nOneDay);
3939 if (pto->nNextAddrSend < nNow) {
3940 pto->nNextAddrSend = PoissonNextSend(nNow, 30);
3941 vector<CAddress> vAddr;
3942 vAddr.reserve(pto->vAddrToSend.size());
3943 for (const CAddress& addr : pto->vAddrToSend)
3945 if (pto->setAddrKnown.insert(addr).second)
3947 vAddr.push_back(addr);
3948 // receiver rejects addr messages larger than 1000
3949 if (vAddr.size() >= 1000)
3951 pto->PushMessage("addr", vAddr);
3956 pto->vAddrToSend.clear();
3958 pto->PushMessage("addr", vAddr);
3962 // Message: inventory
3965 vector<CInv> vInvWait;
3967 bool fSendTrickle = false;
3968 if (pto->nNextInvSend < nNow) {
3969 fSendTrickle = true;
3970 pto->nNextInvSend = PoissonNextSend(nNow, 5);
3972 LOCK(pto->cs_inventory);
3973 vInv.reserve(pto->vInventoryToSend.size());
3974 vInvWait.reserve(pto->vInventoryToSend.size());
3975 for (const CInv& inv : pto->vInventoryToSend)
3977 if (pto->setInventoryKnown.count(inv))
3980 // trickle out tx inv to protect privacy
3981 if (inv.type == MSG_TX && !fSendTrickle)
3983 // 1/4 of tx invs blast to all immediately
3984 static uint256 hashSalt;
3986 hashSalt = GetRandHash();
3987 uint256 hashRand = inv.hash ^ hashSalt;
3988 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3989 bool fTrickleWait = ((hashRand & 3) != 0);
3993 vInvWait.push_back(inv);
3998 // returns true if wasn't already contained in the set
3999 if (pto->setInventoryKnown.insert(inv).second)
4001 vInv.push_back(inv);
4002 if (vInv.size() >= 1000)
4004 pto->PushMessage("inv", vInv);
4009 pto->vInventoryToSend = vInvWait;
4012 pto->PushMessage("inv", vInv);
4018 vector<CInv> vGetData;
4020 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4022 const CInv& inv = (*pto->mapAskFor.begin()).second;
4023 if (!AlreadyHave(txdb, inv))
4026 printf("sending getdata: %s\n", inv.ToString().c_str());
4027 vGetData.push_back(inv);
4028 if (vGetData.size() >= 1000)
4030 pto->PushMessage("getdata", vGetData);
4033 mapAlreadyAskedFor[inv] = nNow;
4035 pto->mapAskFor.erase(pto->mapAskFor.begin());
4037 if (!vGetData.empty())
4038 pto->PushMessage("getdata", vGetData);
4051 std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4052 for (; it1 != mapBlockIndex.end(); it1++)
4053 delete (*it1).second;
4054 mapBlockIndex.clear();
4057 std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4058 for (; it2 != mapOrphanBlocks.end(); it2++)
4059 delete (*it2).second;
4060 mapOrphanBlocks.clear();
4062 // orphan transactions
4064 } instance_of_cmaincleanup;