1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
9 #include "txdb-leveldb.h"
11 #include "interface.h"
12 #include "checkqueue.h"
14 #include <boost/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
22 using namespace boost;
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
29 CCriticalSection cs_main;
32 unsigned int nTransactionsUpdated = 0;
34 map<uint256, CBlockIndex*> mapBlockIndex;
35 set<pair<COutPoint, unsigned int> > setStakeSeen;
37 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
38 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
39 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
40 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
41 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
43 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
45 unsigned int 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);
869 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
874 // Add previous supporting transactions first
875 for (CMerkleTx& tx : vtxPrev)
877 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
879 uint256 hash = tx.GetHash();
880 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
881 tx.AcceptToMemoryPool(txdb, fCheckInputs);
884 return AcceptToMemoryPool(txdb, fCheckInputs);
889 bool CWalletTx::AcceptWalletTransaction()
892 return AcceptWalletTransaction(txdb);
895 int CTxIndex::GetDepthInMainChain() const
899 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
901 // Find the block in the index
902 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
903 if (mi == mapBlockIndex.end())
905 CBlockIndex* pindex = (*mi).second;
906 if (!pindex || !pindex->IsInMainChain())
908 return 1 + nBestHeight - pindex->nHeight;
911 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
912 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
918 if (mempool.exists(hash))
920 tx = mempool.lookup(hash);
926 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
929 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
930 hashBlock = block.GetHash();
944 //////////////////////////////////////////////////////////////////////////////
946 // CBlock and CBlockIndex
949 static CBlockIndex* pblockindexFBBHLast;
950 CBlockIndex* FindBlockByHeight(int nHeight)
952 CBlockIndex *pblockindex;
953 if (nHeight < nBestHeight / 2)
954 pblockindex = pindexGenesisBlock;
956 pblockindex = pindexBest;
957 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
958 pblockindex = pblockindexFBBHLast;
959 while (pblockindex->nHeight > nHeight)
960 pblockindex = pblockindex->pprev;
961 while (pblockindex->nHeight < nHeight)
962 pblockindex = pblockindex->pnext;
963 pblockindexFBBHLast = pblockindex;
967 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
969 if (!fReadTransactions)
971 *this = pindex->GetBlockHeader();
974 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
976 if (GetHash() != pindex->GetBlockHash())
977 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
981 uint256 static GetOrphanRoot(const CBlock* pblock)
983 // Work back to the first block in the orphan chain
984 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
985 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
986 return pblock->GetHash();
989 // ppcoin: find block wanted by given orphan block
990 uint256 WantedByOrphan(const CBlock* pblockOrphan)
992 // Work back to the first block in the orphan chain
993 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
994 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
995 return pblockOrphan->hashPrevBlock;
998 // select stake target limit according to hard-coded conditions
999 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1001 if(fTestNet) // separate proof of stake target limit for testnet
1002 return bnProofOfStakeLimit;
1003 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1004 return bnProofOfStakeLimit;
1005 if(nHeight + 1 > 15000) // 24 bits since block 15000
1006 return bnProofOfStakeLegacyLimit;
1007 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1008 return bnProofOfStakeHardLimit;
1010 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1013 // miner's coin base reward based on nBits
1014 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees)
1016 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1019 bnTarget.SetCompact(nBits);
1020 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1021 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1023 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1024 // A reasonably continuous curve is used to avoid shock to market
1025 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1027 // Human readable form:
1029 // nSubsidy = 100 / (diff ^ 1/6)
1031 // Please note that we're using bisection to find an approximate solutuion
1032 CBigNum bnLowerBound = CENT;
1033 CBigNum bnUpperBound = bnSubsidyLimit;
1034 while (bnLowerBound + CENT <= bnUpperBound)
1036 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1037 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1038 bnUpperBound = bnMidValue;
1040 bnLowerBound = bnMidValue;
1043 int64_t nSubsidy = bnUpperBound.getuint64();
1045 nSubsidy = (nSubsidy / CENT) * CENT;
1046 if (fDebug && GetBoolArg("-printcreation"))
1047 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1049 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1052 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1053 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1055 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1057 // Stage 2 of emission process is mostly PoS-based.
1059 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1061 bnTarget.SetCompact(nBits);
1062 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1063 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1065 // A reasonably continuous curve is used to avoid shock to market
1067 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1068 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1069 bnMidPart, bnRewardPart;
1071 while (bnLowerBound + CENT <= bnUpperBound)
1073 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1076 // Reward for coin-year is cut in half every 8x multiply of PoS difficulty
1078 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1080 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1083 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1084 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1086 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1087 bnUpperBound = bnMidValue;
1089 bnLowerBound = bnMidValue;
1092 nRewardCoinYear = bnUpperBound.getuint64();
1093 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1096 return nRewardCoinYear;
1098 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1100 // Set reasonable reward limit for large inputs
1102 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1104 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1105 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1107 nSubsidy = min(nSubsidy, nSubsidyLimit);
1109 if (fDebug && GetBoolArg("-printcreation"))
1110 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1115 static const int64_t nTargetTimespan = 7 * nOneDay; // one week
1117 // get proof of work blocks max spacing according to hard-coded conditions
1118 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1120 if(nTime > TARGETS_SWITCH_TIME)
1121 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1124 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1126 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1130 // maximum nBits value could possible be required nTime after
1132 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1135 bnResult.SetCompact(nBase);
1137 while (nTime > 0 && bnResult < bnTargetLimit)
1139 // Maximum 200% adjustment per day...
1143 if (bnResult > bnTargetLimit)
1144 bnResult = bnTargetLimit;
1145 return bnResult.GetCompact();
1149 // minimum amount of work that could possibly be required nTime after
1150 // minimum proof-of-work required was nBase
1152 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1154 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1158 // minimum amount of stake that could possibly be required nTime after
1159 // minimum proof-of-stake required was nBase
1161 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1163 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1167 // ppcoin: find last block index up to pindex
1168 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1170 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1171 pindex = pindex->pprev;
1175 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1177 if (pindexLast == NULL)
1178 return bnProofOfWorkLimit.GetCompact(); // genesis block
1180 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1182 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1183 if (pindexPrev->pprev == NULL)
1184 return bnTargetLimit.GetCompact(); // first block
1185 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1186 if (pindexPrevPrev->pprev == NULL)
1187 return bnTargetLimit.GetCompact(); // second block
1189 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1191 // ppcoin: target change every block
1192 // ppcoin: retarget with exponential moving toward target spacing
1194 bnNew.SetCompact(pindexPrev->nBits);
1195 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1196 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1197 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1198 bnNew /= ((nInterval + 1) * nTargetSpacing);
1200 if (bnNew > bnTargetLimit)
1201 bnNew = bnTargetLimit;
1203 return bnNew.GetCompact();
1206 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1209 bnTarget.SetCompact(nBits);
1212 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1213 return error("CheckProofOfWork() : nBits below minimum work");
1215 // Check proof of work matches claimed amount
1216 if (hash > bnTarget.getuint256())
1217 return error("CheckProofOfWork() : hash doesn't match nBits");
1222 // Return maximum amount of blocks that other nodes claim to have
1223 int GetNumBlocksOfPeers()
1225 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1228 bool IsInitialBlockDownload()
1230 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1232 static int64_t nLastUpdate;
1233 static CBlockIndex* pindexLastBest;
1234 int64_t nCurrentTime = GetTime();
1235 if (pindexBest != pindexLastBest)
1237 pindexLastBest = pindexBest;
1238 nLastUpdate = nCurrentTime;
1240 return (nCurrentTime - nLastUpdate < 10 &&
1241 pindexBest->GetBlockTime() < nCurrentTime - nOneDay);
1244 void static InvalidChainFound(CBlockIndex* pindexNew)
1246 if (pindexNew->nChainTrust > nBestInvalidTrust)
1248 nBestInvalidTrust = pindexNew->nChainTrust;
1249 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1250 uiInterface.NotifyBlocksChanged();
1253 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1254 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1256 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1257 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1258 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1259 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1260 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1261 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1262 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1263 nBestBlockTrust.Get64(),
1264 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1268 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1270 nTime = max(GetBlockTime(), GetAdjustedTime());
1283 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1285 // Relinquish previous transactions' spent pointers
1288 for (const CTxIn& txin : vin)
1290 COutPoint prevout = txin.prevout;
1292 // Get prev txindex from disk
1294 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1295 return error("DisconnectInputs() : ReadTxIndex failed");
1297 if (prevout.n >= txindex.vSpent.size())
1298 return error("DisconnectInputs() : prevout.n out of range");
1300 // Mark outpoint as not spent
1301 txindex.vSpent[prevout.n].SetNull();
1304 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1305 return error("DisconnectInputs() : UpdateTxIndex failed");
1309 // Remove transaction from index
1310 // This can fail if a duplicate of this transaction was in a chain that got
1311 // reorganized away. This is only possible if this transaction was completely
1312 // spent, so erasing it would be a no-op anyway.
1313 txdb.EraseTxIndex(*this);
1319 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1320 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1322 // FetchInputs can return false either because we just haven't seen some inputs
1323 // (in which case the transaction should be stored as an orphan)
1324 // or because the transaction is malformed (in which case the transaction should
1325 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1329 return true; // Coinbase transactions have no inputs to fetch.
1331 for (unsigned int i = 0; i < vin.size(); i++)
1333 COutPoint prevout = vin[i].prevout;
1334 if (inputsRet.count(prevout.hash))
1335 continue; // Got it already
1338 CTxIndex& txindex = inputsRet[prevout.hash].first;
1340 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1342 // Get txindex from current proposed changes
1343 txindex = mapTestPool.find(prevout.hash)->second;
1347 // Read txindex from txdb
1348 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1350 if (!fFound && (fBlock || fMiner))
1351 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());
1354 CTransaction& txPrev = inputsRet[prevout.hash].second;
1355 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1357 // Get prev tx from single transactions in memory
1360 if (!mempool.exists(prevout.hash))
1361 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());
1362 txPrev = mempool.lookup(prevout.hash);
1365 txindex.vSpent.resize(txPrev.vout.size());
1369 // Get prev tx from disk
1370 if (!txPrev.ReadFromDisk(txindex.pos))
1371 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1375 // Make sure all prevout.n indexes are valid:
1376 for (unsigned int i = 0; i < vin.size(); i++)
1378 const COutPoint prevout = vin[i].prevout;
1379 assert(inputsRet.count(prevout.hash) != 0);
1380 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1381 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1382 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1384 // Revisit this if/when transaction replacement is implemented and allows
1387 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()));
1394 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1396 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1397 if (mi == inputs.end())
1398 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1400 const CTransaction& txPrev = (mi->second).second;
1401 if (input.prevout.n >= txPrev.vout.size())
1402 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1404 return txPrev.vout[input.prevout.n];
1407 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1412 int64_t nResult = 0;
1413 for (unsigned int i = 0; i < vin.size(); i++)
1415 nResult += GetOutputFor(vin[i], inputs).nValue;
1421 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1426 unsigned int nSigOps = 0;
1427 for (unsigned int i = 0; i < vin.size(); i++)
1429 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1430 if (prevout.scriptPubKey.IsPayToScriptHash())
1431 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1436 bool CScriptCheck::operator()() const {
1437 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1438 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1439 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1443 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1445 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1448 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1449 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1451 // Take over previous transactions' spent pointers
1452 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1453 // fMiner is true when called from the internal bitcoin miner
1454 // ... both are false when called from CTransaction::AcceptToMemoryPool
1458 int64_t nValueIn = 0;
1460 for (unsigned int i = 0; i < vin.size(); i++)
1462 COutPoint prevout = vin[i].prevout;
1463 assert(inputs.count(prevout.hash) > 0);
1464 CTxIndex& txindex = inputs[prevout.hash].first;
1465 CTransaction& txPrev = inputs[prevout.hash].second;
1467 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1468 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()));
1470 // If prev is coinbase or coinstake, check that it's matured
1471 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1472 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1473 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1474 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1476 // ppcoin: check transaction timestamp
1477 if (txPrev.nTime > nTime)
1478 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1480 // Check for negative or overflow input values
1481 nValueIn += txPrev.vout[prevout.n].nValue;
1482 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1483 return DoS(100, error("ConnectInputs() : txin values out of range"));
1488 pvChecks->reserve(vin.size());
1490 // The first loop above does all the inexpensive checks.
1491 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1492 // Helps prevent CPU exhaustion attacks.
1493 for (unsigned int i = 0; i < vin.size(); i++)
1495 COutPoint prevout = vin[i].prevout;
1496 assert(inputs.count(prevout.hash) > 0);
1497 CTxIndex& txindex = inputs[prevout.hash].first;
1498 CTransaction& txPrev = inputs[prevout.hash].second;
1500 // Check for conflicts (double-spend)
1501 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1502 // for an attacker to attempt to split the network.
1503 if (!txindex.vSpent[prevout.n].IsNull())
1504 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());
1506 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1507 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1508 // still computed and checked, and any change will be caught at the next checkpoint.
1512 CScriptCheck check(txPrev, *this, i, flags, 0);
1515 pvChecks->push_back(CScriptCheck());
1516 check.swap(pvChecks->back());
1520 if (flags & STRICT_FLAGS)
1522 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1523 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1525 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1527 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1531 // Mark outpoints as spent
1532 txindex.vSpent[prevout.n] = posThisTx;
1535 if (fBlock || fMiner)
1537 mapTestPool[prevout.hash] = txindex;
1543 if (nTime > Checkpoints::GetLastCheckpointTime())
1545 unsigned int nTxSize = GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
1547 // coin stake tx earns reward instead of paying fee
1549 if (!GetCoinAge(txdb, nCoinAge))
1550 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1552 int64_t nReward = GetValueOut() - nValueIn;
1553 int64_t nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1555 if (nReward > nCalculatedReward)
1556 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1561 if (nValueIn < GetValueOut())
1562 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1564 // Tally transaction fees
1565 int64_t nTxFee = nValueIn - GetValueOut();
1567 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1570 if (!MoneyRange(nFees))
1571 return DoS(100, error("ConnectInputs() : nFees out of range"));
1579 bool CTransaction::ClientConnectInputs()
1584 // Take over previous transactions' spent pointers
1587 int64_t nValueIn = 0;
1588 for (unsigned int i = 0; i < vin.size(); i++)
1590 // Get prev tx from single transactions in memory
1591 COutPoint prevout = vin[i].prevout;
1592 if (!mempool.exists(prevout.hash))
1594 CTransaction& txPrev = mempool.lookup(prevout.hash);
1596 if (prevout.n >= txPrev.vout.size())
1600 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1601 return error("ClientConnectInputs() : VerifySignature failed");
1603 ///// this is redundant with the mempool.mapNextTx stuff,
1604 ///// not sure which I want to get rid of
1605 ///// this has to go away now that posNext is gone
1606 // // Check for conflicts
1607 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1608 // return error("ConnectInputs() : prev tx already used");
1610 // // Flag outpoints as used
1611 // txPrev.vout[prevout.n].posNext = posThisTx;
1613 nValueIn += txPrev.vout[prevout.n].nValue;
1615 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1616 return error("ClientConnectInputs() : txin values out of range");
1618 if (GetValueOut() > nValueIn)
1628 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1630 // Disconnect in reverse order
1631 for (int i = vtx.size()-1; i >= 0; i--)
1632 if (!vtx[i].DisconnectInputs(txdb))
1635 // Update block index on disk without changing it in memory.
1636 // The memory index structure will be changed after the db commits.
1639 CDiskBlockIndex blockindexPrev(pindex->pprev);
1640 blockindexPrev.hashNext = 0;
1641 if (!txdb.WriteBlockIndex(blockindexPrev))
1642 return error("DisconnectBlock() : WriteBlockIndex failed");
1645 // ppcoin: clean up wallet after disconnecting coinstake
1646 for (CTransaction& tx : vtx)
1647 SyncWithWallets(tx, this, false, false);
1652 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1654 void ThreadScriptCheck(void*) {
1655 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1656 RenameThread("novacoin-scriptch");
1657 scriptcheckqueue.Thread();
1658 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1661 void ThreadScriptCheckQuit() {
1662 scriptcheckqueue.Quit();
1665 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1667 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1668 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1671 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1672 // unless those are already completely spent.
1673 // If such overwrites are allowed, coinbases and transactions depending upon those
1674 // can be duplicated to remove the ability to spend the first instance -- even after
1675 // being sent to another address.
1676 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1677 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1678 // already refuses previously-known transaction ids entirely.
1679 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1680 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1681 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1682 // initial block download.
1683 bool fEnforceBIP30 = true; // Always active in NovaCoin
1684 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1686 //// issue here: it doesn't know the version
1687 unsigned int nTxPos;
1689 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1690 // 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
1693 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1695 map<uint256, CTxIndex> mapQueuedChanges;
1696 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1699 int64_t nValueIn = 0;
1700 int64_t nValueOut = 0;
1701 unsigned int nSigOps = 0;
1702 for (CTransaction& tx : vtx)
1704 uint256 hashTx = tx.GetHash();
1706 if (fEnforceBIP30) {
1707 CTxIndex txindexOld;
1708 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1709 for (CDiskTxPos &pos : txindexOld.vSpent)
1715 nSigOps += tx.GetLegacySigOpCount();
1716 if (nSigOps > MAX_BLOCK_SIGOPS)
1717 return DoS(100, error("ConnectBlock() : too many sigops"));
1719 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1721 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1723 MapPrevTx mapInputs;
1724 if (tx.IsCoinBase())
1725 nValueOut += tx.GetValueOut();
1729 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1732 // Add in sigops done by pay-to-script-hash inputs;
1733 // this is to prevent a "rogue miner" from creating
1734 // an incredibly-expensive-to-validate block.
1735 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1736 if (nSigOps > MAX_BLOCK_SIGOPS)
1737 return DoS(100, error("ConnectBlock() : too many sigops"));
1739 int64_t nTxValueIn = tx.GetValueIn(mapInputs);
1740 int64_t nTxValueOut = tx.GetValueOut();
1741 nValueIn += nTxValueIn;
1742 nValueOut += nTxValueOut;
1743 if (!tx.IsCoinStake())
1744 nFees += nTxValueIn - nTxValueOut;
1746 unsigned int nFlags = SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH;
1748 if (tx.nTime >= CHECKLOCKTIMEVERIFY_SWITCH_TIME) {
1749 nFlags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1752 if (tx.nTime >= CHECKSEQUENCEVERIFY_SWITCH_TIME) {
1753 nFlags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1756 std::vector<CScriptCheck> vChecks;
1757 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, nFlags, nScriptCheckThreads ? &vChecks : NULL))
1759 control.Add(vChecks);
1762 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1765 if (!control.Wait())
1766 return DoS(100, false);
1768 if (IsProofOfWork())
1770 int64_t nBlockReward = GetProofOfWorkReward(nBits, nFees);
1772 // Check coinbase reward
1773 if (vtx[0].GetValueOut() > nBlockReward)
1774 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1775 vtx[0].GetValueOut(),
1779 // track money supply and mint amount info
1780 pindex->nMint = nValueOut - nValueIn + nFees;
1781 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1782 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1783 return error("Connect() : WriteBlockIndex for pindex failed");
1785 // fees are not collected by proof-of-stake miners
1786 // fees are destroyed to compensate the entire network
1787 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1788 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
1793 // Write queued txindex changes
1794 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1796 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1797 return error("ConnectBlock() : UpdateTxIndex failed");
1800 // Update block index on disk without changing it in memory.
1801 // The memory index structure will be changed after the db commits.
1804 CDiskBlockIndex blockindexPrev(pindex->pprev);
1805 blockindexPrev.hashNext = pindex->GetBlockHash();
1806 if (!txdb.WriteBlockIndex(blockindexPrev))
1807 return error("ConnectBlock() : WriteBlockIndex failed");
1810 // Watch for transactions paying to me
1811 for (CTransaction& tx : vtx)
1812 SyncWithWallets(tx, this, true);
1818 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1820 printf("REORGANIZE\n");
1823 CBlockIndex* pfork = pindexBest;
1824 CBlockIndex* plonger = pindexNew;
1825 while (pfork != plonger)
1827 while (plonger->nHeight > pfork->nHeight)
1828 if ((plonger = plonger->pprev) == NULL)
1829 return error("Reorganize() : plonger->pprev is null");
1830 if (pfork == plonger)
1832 if ((pfork = pfork->pprev) == NULL)
1833 return error("Reorganize() : pfork->pprev is null");
1836 // List of what to disconnect
1837 vector<CBlockIndex*> vDisconnect;
1838 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1839 vDisconnect.push_back(pindex);
1841 // List of what to connect
1842 vector<CBlockIndex*> vConnect;
1843 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1844 vConnect.push_back(pindex);
1845 reverse(vConnect.begin(), vConnect.end());
1847 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());
1848 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());
1850 // Disconnect shorter branch
1851 vector<CTransaction> vResurrect;
1852 for (CBlockIndex* pindex : vDisconnect)
1855 if (!block.ReadFromDisk(pindex))
1856 return error("Reorganize() : ReadFromDisk for disconnect failed");
1857 if (!block.DisconnectBlock(txdb, pindex))
1858 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1860 // Queue memory transactions to resurrect
1861 for (const CTransaction& tx : block.vtx)
1862 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1863 vResurrect.push_back(tx);
1866 // Connect longer branch
1867 vector<CTransaction> vDelete;
1868 for (unsigned int i = 0; i < vConnect.size(); i++)
1870 CBlockIndex* pindex = vConnect[i];
1872 if (!block.ReadFromDisk(pindex))
1873 return error("Reorganize() : ReadFromDisk for connect failed");
1874 if (!block.ConnectBlock(txdb, pindex))
1877 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1880 // Queue memory transactions to delete
1881 for (const CTransaction& tx : block.vtx)
1882 vDelete.push_back(tx);
1884 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1885 return error("Reorganize() : WriteHashBestChain failed");
1887 // Make sure it's successfully written to disk before changing memory structure
1888 if (!txdb.TxnCommit())
1889 return error("Reorganize() : TxnCommit failed");
1891 // Disconnect shorter branch
1892 for (CBlockIndex* pindex : vDisconnect)
1894 pindex->pprev->pnext = NULL;
1896 // Connect longer branch
1897 for (CBlockIndex* pindex : vConnect)
1899 pindex->pprev->pnext = pindex;
1901 // Resurrect memory transactions that were in the disconnected branch
1902 for (CTransaction& tx : vResurrect)
1903 tx.AcceptToMemoryPool(txdb, false);
1905 // Delete redundant memory transactions that are in the connected branch
1906 for (CTransaction& tx : vDelete)
1909 printf("REORGANIZE: done\n");
1915 // Called from inside SetBestChain: attaches a block to the new best chain being built
1916 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1918 uint256 hash = GetHash();
1920 // Adding to current best branch
1921 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1924 InvalidChainFound(pindexNew);
1927 if (!txdb.TxnCommit())
1928 return error("SetBestChain() : TxnCommit failed");
1930 // Add to current best branch
1931 pindexNew->pprev->pnext = pindexNew;
1933 // Delete redundant memory transactions
1934 for (CTransaction& tx : vtx)
1940 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1942 uint256 hash = GetHash();
1944 if (!txdb.TxnBegin())
1945 return error("SetBestChain() : TxnBegin failed");
1947 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1949 txdb.WriteHashBestChain(hash);
1950 if (!txdb.TxnCommit())
1951 return error("SetBestChain() : TxnCommit failed");
1952 pindexGenesisBlock = pindexNew;
1954 else if (hashPrevBlock == hashBestChain)
1956 if (!SetBestChainInner(txdb, pindexNew))
1957 return error("SetBestChain() : SetBestChainInner failed");
1961 // the first block in the new chain that will cause it to become the new best chain
1962 CBlockIndex *pindexIntermediate = pindexNew;
1964 // list of blocks that need to be connected afterwards
1965 std::vector<CBlockIndex*> vpindexSecondary;
1967 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1968 // Try to limit how much needs to be done inside
1969 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1971 vpindexSecondary.push_back(pindexIntermediate);
1972 pindexIntermediate = pindexIntermediate->pprev;
1975 if (!vpindexSecondary.empty())
1976 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
1978 // Switch to new best branch
1979 if (!Reorganize(txdb, pindexIntermediate))
1982 InvalidChainFound(pindexNew);
1983 return error("SetBestChain() : Reorganize failed");
1986 // Connect further blocks
1987 for (std::vector<CBlockIndex*>::reverse_iterator rit = vpindexSecondary.rbegin(); rit != vpindexSecondary.rend(); ++rit)
1990 if (!block.ReadFromDisk(*rit))
1992 printf("SetBestChain() : ReadFromDisk failed\n");
1995 if (!txdb.TxnBegin()) {
1996 printf("SetBestChain() : TxnBegin 2 failed\n");
1999 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
2000 if (!block.SetBestChainInner(txdb, *rit))
2005 // Update best block in wallet (so we can detect restored wallets)
2006 bool fIsInitialDownload = IsInitialBlockDownload();
2007 if (!fIsInitialDownload)
2009 const CBlockLocator locator(pindexNew);
2010 ::SetBestChain(locator);
2014 hashBestChain = hash;
2015 pindexBest = pindexNew;
2016 pblockindexFBBHLast = NULL;
2017 nBestHeight = pindexBest->nHeight;
2018 nBestChainTrust = pindexNew->nChainTrust;
2019 nTimeBestReceived = GetTime();
2020 nTransactionsUpdated++;
2022 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2024 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
2025 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2026 CBigNum(nBestChainTrust).ToString().c_str(),
2027 nBestBlockTrust.Get64(),
2028 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2030 // Check the version of the last 100 blocks to see if we need to upgrade:
2031 if (!fIsInitialDownload)
2034 const CBlockIndex* pindex = pindexBest;
2035 for (int i = 0; i < 100 && pindex != NULL; i++)
2037 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2039 pindex = pindex->pprev;
2042 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2043 if (nUpgraded > 100/2)
2044 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2045 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2048 std::string strCmd = GetArg("-blocknotify", "");
2050 if (!fIsInitialDownload && !strCmd.empty())
2052 boost::thread t(runCommand, regex_replace(strCmd, static_cast<std::regex>("%s"), hashBestChain.GetHex()));
2057 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2058 // Only those coins meeting minimum age requirement counts. As those
2059 // transactions not in main chain are not currently indexed so we
2060 // might not find out about their coin age. Older transactions are
2061 // guaranteed to be in main chain by sync-checkpoint. This rule is
2062 // introduced to help nodes establish a consistent view of the coin
2063 // age (trust score) of competing branches.
2064 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2066 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2072 for (const CTxIn& txin : vin)
2074 // First try finding the previous transaction in database
2075 CTransaction txPrev;
2077 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2078 continue; // previous transaction not in main chain
2079 if (nTime < txPrev.nTime)
2080 return false; // Transaction timestamp violation
2082 // Read block header
2084 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2085 return false; // unable to read block of previous transaction
2086 if (block.GetBlockTime() + nStakeMinAge > nTime)
2087 continue; // only count coins meeting min age requirement
2089 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
2090 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2092 if (fDebug && GetBoolArg("-printcoinage"))
2093 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2096 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / nOneDay;
2097 if (fDebug && GetBoolArg("-printcoinage"))
2098 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2099 nCoinAge = bnCoinDay.getuint64();
2103 // ppcoin: total coin age spent in block, in the unit of coin-days.
2104 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2109 for (const CTransaction& tx : vtx)
2111 uint64_t nTxCoinAge;
2112 if (tx.GetCoinAge(txdb, nTxCoinAge))
2113 nCoinAge += nTxCoinAge;
2118 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2120 if (fDebug && GetBoolArg("-printcoinage"))
2121 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2125 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2127 // Check for duplicate
2128 uint256 hash = GetHash();
2129 if (mapBlockIndex.count(hash))
2130 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2132 // Construct new block index object
2133 CBlockIndex* pindexNew = new(nothrow) CBlockIndex(nFile, nBlockPos, *this);
2135 return error("AddToBlockIndex() : new CBlockIndex failed");
2136 pindexNew->phashBlock = &hash;
2137 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2138 if (miPrev != mapBlockIndex.end())
2140 pindexNew->pprev = (*miPrev).second;
2141 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2144 // ppcoin: compute chain trust score
2145 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2147 // ppcoin: compute stake entropy bit for stake modifier
2148 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2149 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2151 // ppcoin: record proof-of-stake hash value
2152 if (pindexNew->IsProofOfStake())
2154 if (!mapProofOfStake.count(hash))
2155 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2156 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2159 // ppcoin: compute stake modifier
2160 uint64_t nStakeModifier = 0;
2161 bool fGeneratedStakeModifier = false;
2162 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2163 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2164 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2165 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2166 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2167 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2169 // Add to mapBlockIndex
2170 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2171 if (pindexNew->IsProofOfStake())
2172 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2173 pindexNew->phashBlock = &((*mi).first);
2175 // Write to disk block index
2177 if (!txdb.TxnBegin())
2179 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2180 if (!txdb.TxnCommit())
2184 if (pindexNew->nChainTrust > nBestChainTrust)
2185 if (!SetBestChain(txdb, pindexNew))
2188 if (pindexNew == pindexBest)
2190 // Notify UI to display prev block's coinbase if it was ours
2191 static uint256 hashPrevBestCoinBase;
2192 UpdatedTransaction(hashPrevBestCoinBase);
2193 hashPrevBestCoinBase = vtx[0].GetHash();
2196 static int8_t counter = 0;
2197 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2198 uiInterface.NotifyBlocksChanged();
2205 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2207 // These are checks that are independent of context
2208 // that can be verified before saving an orphan block.
2210 set<uint256> uniqueTx; // tx hashes
2211 unsigned int nSigOps = 0; // total sigops
2214 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2215 return DoS(100, error("CheckBlock() : size limits failed"));
2217 bool fProofOfStake = IsProofOfStake();
2219 // First transaction must be coinbase, the rest must not be
2220 if (!vtx[0].IsCoinBase())
2221 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2223 if (!vtx[0].CheckTransaction())
2224 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2226 uniqueTx.insert(vtx[0].GetHash());
2227 nSigOps += vtx[0].GetLegacySigOpCount();
2231 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2232 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2234 // nNonce must be zero for proof-of-stake blocks
2236 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2238 // Coinbase output should be empty if proof-of-stake block
2239 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2240 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2242 // Check coinstake timestamp
2243 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2244 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2246 // NovaCoin: check proof-of-stake block signature
2247 if (fCheckSig && !CheckBlockSignature())
2248 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2250 if (!vtx[1].CheckTransaction())
2251 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2253 uniqueTx.insert(vtx[1].GetHash());
2254 nSigOps += vtx[1].GetLegacySigOpCount();
2258 // Check proof of work matches claimed amount
2259 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2260 return DoS(50, error("CheckBlock() : proof of work failed"));
2263 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2264 return error("CheckBlock() : block timestamp too far in the future");
2266 // Check coinbase timestamp
2267 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2268 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2271 // Iterate all transactions starting from second for proof-of-stake block
2272 // or first for proof-of-work block
2273 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2275 const CTransaction& tx = vtx[i];
2277 // Reject coinbase transactions at non-zero index
2278 if (tx.IsCoinBase())
2279 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2281 // Reject coinstake transactions at index != 1
2282 if (tx.IsCoinStake())
2283 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2285 // Check transaction timestamp
2286 if (GetBlockTime() < (int64_t)tx.nTime)
2287 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2289 // Check transaction consistency
2290 if (!tx.CheckTransaction())
2291 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2293 // Add transaction hash into list of unique transaction IDs
2294 uniqueTx.insert(tx.GetHash());
2296 // Calculate sigops count
2297 nSigOps += tx.GetLegacySigOpCount();
2300 // Check for duplicate txids. This is caught by ConnectInputs(),
2301 // but catching it earlier avoids a potential DoS attack:
2302 if (uniqueTx.size() != vtx.size())
2303 return DoS(100, error("CheckBlock() : duplicate transaction"));
2305 // Reject block if validation would consume too much resources.
2306 if (nSigOps > MAX_BLOCK_SIGOPS)
2307 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2309 // Check merkle root
2310 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2311 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2316 bool CBlock::AcceptBlock()
2318 // Check for duplicate
2319 uint256 hash = GetHash();
2320 if (mapBlockIndex.count(hash))
2321 return error("AcceptBlock() : block already in mapBlockIndex");
2323 // Get prev block index
2324 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2325 if (mi == mapBlockIndex.end())
2326 return DoS(10, error("AcceptBlock() : prev block not found"));
2327 CBlockIndex* pindexPrev = (*mi).second;
2328 int nHeight = pindexPrev->nHeight+1;
2330 // Check proof-of-work or proof-of-stake
2331 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2332 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2334 int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
2335 int nMaxOffset = 12 * nOneHour; // 12 hours
2336 if (fTestNet || pindexPrev->nTime < 1450569600)
2337 nMaxOffset = 7 * nOneWeek; // One week (permanently on testNet or until 20 Dec, 2015 on mainNet)
2339 // Check timestamp against prev
2340 if (GetBlockTime() <= nMedianTimePast || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2341 return error("AcceptBlock() : block's timestamp is too early");
2343 // Don't accept blocks with future timestamps
2344 if (pindexPrev->nHeight > 1 && nMedianTimePast + nMaxOffset < GetBlockTime())
2345 return error("AcceptBlock() : block's timestamp is too far in the future");
2347 // Check that all transactions are finalized
2348 for (const CTransaction& tx : vtx)
2349 if (!tx.IsFinal(nHeight, GetBlockTime()))
2350 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2352 // Check that the block chain matches the known block chain up to a checkpoint
2353 if (!Checkpoints::CheckHardened(nHeight, hash))
2354 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2356 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2358 // Check that the block satisfies synchronized checkpoint
2359 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2360 return error("AcceptBlock() : rejected by synchronized checkpoint");
2362 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2363 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2365 // Enforce rule that the coinbase starts with serialized block height
2366 CScript expect = CScript() << nHeight;
2367 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2368 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2369 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2371 // Write block to history file
2372 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2373 return error("AcceptBlock() : out of disk space");
2374 unsigned int nFile = std::numeric_limits<unsigned int>::max();
2375 unsigned int nBlockPos = 0;
2376 if (!WriteToDisk(nFile, nBlockPos))
2377 return error("AcceptBlock() : WriteToDisk failed");
2378 if (!AddToBlockIndex(nFile, nBlockPos))
2379 return error("AcceptBlock() : AddToBlockIndex failed");
2381 // Relay inventory, but don't relay old inventory during initial block download
2382 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2383 if (hashBestChain == hash)
2386 for (CNode* pnode : vNodes)
2387 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2388 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2391 // ppcoin: check pending sync-checkpoint
2392 Checkpoints::AcceptPendingSyncCheckpoint();
2397 uint256 CBlockIndex::GetBlockTrust() const
2400 bnTarget.SetCompact(nBits);
2405 // Return 1 for the first 12 blocks
2406 if (pprev == NULL || pprev->nHeight < 12)
2409 const CBlockIndex* currentIndex = pprev;
2411 if(IsProofOfStake())
2413 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2415 // Return 1/3 of score if parent block is not the PoW block
2416 if (!pprev->IsProofOfWork())
2417 return (bnNewTrust / 3).getuint256();
2421 // Check last 12 blocks type
2422 while (pprev->nHeight - currentIndex->nHeight < 12)
2424 if (currentIndex->IsProofOfWork())
2426 currentIndex = currentIndex->pprev;
2429 // Return 1/3 of score if less than 3 PoW blocks found
2431 return (bnNewTrust / 3).getuint256();
2433 return bnNewTrust.getuint256();
2437 // Calculate work amount for block
2438 CBigNum bnPoWTrust = CBigNum(nPoWBase) / (bnTarget+1);
2440 // Set nPowTrust to 1 if PoW difficulty is too low
2444 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2446 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2447 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2448 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2452 // Check last 12 blocks type
2453 while (pprev->nHeight - currentIndex->nHeight < 12)
2455 if (currentIndex->IsProofOfStake())
2457 currentIndex = currentIndex->pprev;
2460 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2462 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2464 bnTarget.SetCompact(pprev->nBits);
2469 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2471 // Return nPoWTrust + full trust score for previous block nBits
2472 return (bnPoWTrust + bnNewTrust).getuint256();
2476 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2478 unsigned int nFound = 0;
2479 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2481 if (pstart->nVersion >= minVersion)
2483 pstart = pstart->pprev;
2485 return (nFound >= nRequired);
2488 bool static ReserealizeBlockSignature(CBlock* pblock)
2490 if (pblock->IsProofOfWork())
2492 pblock->vchBlockSig.clear();
2496 return CPubKey::ReserealizeSignature(pblock->vchBlockSig);
2499 bool static IsCanonicalBlockSignature(CBlock* pblock)
2501 if (pblock->IsProofOfWork())
2502 return pblock->vchBlockSig.empty();
2504 return IsDERSignature(pblock->vchBlockSig);
2507 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2509 // Check for duplicate
2510 uint256 hash = pblock->GetHash();
2511 if (mapBlockIndex.count(hash))
2512 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2513 if (mapOrphanBlocks.count(hash))
2514 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2516 // Check that block isn't listed as unconditionally banned.
2517 if (!Checkpoints::CheckBanned(hash)) {
2519 pfrom->Misbehaving(100);
2520 return error("ProcessBlock() : block %s is rejected by hard-coded banlist", hash.GetHex().substr(0,20).c_str());
2523 // Check proof-of-stake
2524 // Limited duplicity on stake: prevents block flood attack
2525 // Duplicate stake allowed only when there is orphan child block
2526 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2527 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());
2529 // Strip the garbage from newly received blocks, if we found some
2530 if (!IsCanonicalBlockSignature(pblock)) {
2531 if (!ReserealizeBlockSignature(pblock))
2532 printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2535 // Preliminary checks
2536 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2537 return error("ProcessBlock() : CheckBlock FAILED");
2539 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2540 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2542 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2543 int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2545 bnNewBlock.SetCompact(pblock->nBits);
2548 if (pblock->IsProofOfStake())
2549 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2551 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2553 if (bnNewBlock > bnRequired)
2556 pfrom->Misbehaving(100);
2557 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2562 // ppcoin: ask for pending sync-checkpoint if any
2563 if (!IsInitialBlockDownload())
2564 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2566 // If don't already have its previous block, shunt it off to holding area until we get it
2567 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2569 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2570 // ppcoin: check proof-of-stake
2571 if (pblock->IsProofOfStake())
2573 // Limited duplicity on stake: prevents block flood attack
2574 // Duplicate stake allowed only when there is orphan child block
2575 if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2576 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());
2578 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2580 CBlock* pblock2 = new CBlock(*pblock);
2581 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2582 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2584 // Ask this guy to fill in what we're missing
2587 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2588 // ppcoin: getblocks may not obtain the ancestor block rejected
2589 // earlier by duplicate-stake check so we ask for it again directly
2590 if (!IsInitialBlockDownload())
2591 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2596 // ppcoin: verify hash target and signature of coinstake tx
2597 if (pblock->IsProofOfStake())
2599 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2600 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2602 // Having prev block in index should be enough for validation
2603 if (mapBlockIndex.count(pblock->hashPrevBlock))
2604 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());
2606 // Orphan blocks should be validated later once all parents successfully added to local chain
2607 printf("ProcessBlock(): delaying proof-of-stake validation for orphan block %s\n", hash.ToString().c_str());
2608 return false; // do not error here as we expect this to happen here
2611 // Needed for AcceptBlock()
2612 if (!mapProofOfStake.count(hash))
2613 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2617 if (!pblock->AcceptBlock())
2618 return error("ProcessBlock() : AcceptBlock FAILED");
2620 // Process any orphan blocks that depended on this one
2621 vector<uint256> vWorkQueue;
2622 vWorkQueue.push_back(hash);
2623 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2625 uint256 hashPrev = vWorkQueue[i];
2626 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2627 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2630 CBlock* pblockOrphan = (*mi).second;
2631 uint256 hashOrphanBlock = pblockOrphan->GetHash();
2633 if (pblockOrphan->IsProofOfStake()) {
2634 // Check proof-of-stake and do other contextual
2635 // preparations before running AcceptBlock()
2636 uint256 hashOrphanProofOfStake = 0;
2637 uint256 targetOrphanProofOfStake = 0;
2639 if (CheckProofOfStake(pblockOrphan->vtx[1], pblockOrphan->nBits, hashOrphanProofOfStake, targetOrphanProofOfStake))
2641 // Needed for AcceptBlock()
2642 if (!mapProofOfStake.count(hashOrphanBlock))
2643 mapProofOfStake.insert(make_pair(hashOrphanBlock, hashOrphanProofOfStake));
2645 // Finally, we're ready to run AcceptBlock()
2646 if (pblockOrphan->AcceptBlock())
2647 vWorkQueue.push_back(hashOrphanBlock);
2648 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2651 // proof-of-work verification
2652 // is notoriously simpler
2653 if (pblockOrphan->AcceptBlock())
2654 vWorkQueue.push_back(hashOrphanBlock);
2657 mapOrphanBlocks.erase(hashOrphanBlock);
2658 delete pblockOrphan;
2661 mapOrphanBlocksByPrev.erase(hashPrev);
2664 printf("ProcessBlock: ACCEPTED\n");
2666 // ppcoin: if responsible for sync-checkpoint send it
2667 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2668 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2673 // ppcoin: check block signature
2674 bool CBlock::CheckBlockSignature() const
2676 if (vchBlockSig.empty())
2679 txnouttype whichType;
2680 vector<valtype> vSolutions;
2681 if (!Solver(vtx[1].vout[1].scriptPubKey, whichType, vSolutions))
2684 if (whichType == TX_PUBKEY)
2686 valtype& vchPubKey = vSolutions[0];
2687 CPubKey key(vchPubKey);
2690 return key.Verify(GetHash(), vchBlockSig);
2696 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2698 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
2700 // Check for nMinDiskSpace bytes (currently 50MB)
2701 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2704 string strMessage = _("Warning: Disk space is low!");
2705 strMiscWarning = strMessage;
2706 printf("*** %s\n", strMessage.c_str());
2707 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2714 static boost::filesystem::path BlockFilePath(unsigned int nFile)
2716 string strBlockFn = strprintf("blk%04u.dat", nFile);
2717 return GetDataDir() / strBlockFn;
2720 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2722 if ((nFile < 1) || (nFile == std::numeric_limits<uint32_t>::max()))
2724 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2727 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2729 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2738 static unsigned int nCurrentBlockFile = 1;
2740 FILE* AppendBlockFile(unsigned int& nFileRet)
2745 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2748 if (fseek(file, 0, SEEK_END) != 0)
2750 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2751 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2753 nFileRet = nCurrentBlockFile;
2757 nCurrentBlockFile++;
2761 void UnloadBlockIndex()
2763 mapBlockIndex.clear();
2764 setStakeSeen.clear();
2765 pindexGenesisBlock = NULL;
2767 nBestChainTrust = 0;
2768 nBestInvalidTrust = 0;
2773 bool LoadBlockIndex(bool fAllowNew)
2777 pchMessageStart[0] = 0xcd;
2778 pchMessageStart[1] = 0xf2;
2779 pchMessageStart[2] = 0xc0;
2780 pchMessageStart[3] = 0xef;
2782 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2783 nStakeMinAge = 2 * nOneHour; // test net min age is 2 hours
2784 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2785 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2786 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2793 if (!txdb.LoadBlockIndex())
2797 // Init with genesis block
2799 if (mapBlockIndex.empty())
2808 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2809 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2810 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2812 // vMerkleTree: 4cb33b3b6a
2816 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2817 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2818 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2820 // vMerkleTree: 4cb33b3b6a
2822 const string strTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2824 txNew.nTime = 1360105017;
2825 txNew.vin.resize(1);
2826 txNew.vout.resize(1);
2827 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>(strTimestamp.begin(), strTimestamp.end());
2828 txNew.vout[0].SetEmpty();
2830 block.vtx.push_back(txNew);
2831 block.hashPrevBlock = 0;
2832 block.hashMerkleRoot = block.BuildMerkleTree();
2834 block.nTime = 1360105017;
2835 block.nBits = bnProofOfWorkLimit.GetCompact();
2836 block.nNonce = !fTestNet ? 1575379 : 46534;
2839 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2841 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2842 assert(block.CheckBlock());
2844 // Start new block file
2846 unsigned int nBlockPos;
2847 if (!block.WriteToDisk(nFile, nBlockPos))
2848 return error("LoadBlockIndex() : writing genesis block to disk failed");
2849 if (!block.AddToBlockIndex(nFile, nBlockPos))
2850 return error("LoadBlockIndex() : genesis block not accepted");
2852 // initialize synchronized checkpoint
2853 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2854 return error("LoadBlockIndex() : failed to init sync checkpoint");
2856 // upgrade time set to zero if txdb initialized
2858 if (!txdb.WriteModifierUpgradeTime(0))
2859 return error("LoadBlockIndex() : failed to init upgrade info");
2860 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2866 string strPubKey = "";
2867 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2869 // write checkpoint master key to db
2871 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2872 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2873 if (!txdb.TxnCommit())
2874 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2875 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2876 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2879 // upgrade time set to zero if blocktreedb initialized
2880 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2882 if (nModifierUpgradeTime)
2883 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2885 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2889 nModifierUpgradeTime = GetTime();
2890 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2891 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2892 return error("LoadBlockIndex() : failed to write upgrade info");
2901 void PrintBlockTree()
2903 // pre-compute tree structure
2904 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2905 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2907 CBlockIndex* pindex = (*mi).second;
2908 mapNext[pindex->pprev].push_back(pindex);
2910 //while (rand() % 3 == 0)
2911 // mapNext[pindex->pprev].push_back(pindex);
2914 vector<pair<int, CBlockIndex*> > vStack;
2915 vStack.push_back(make_pair(0, pindexGenesisBlock));
2918 while (!vStack.empty())
2920 int nCol = vStack.back().first;
2921 CBlockIndex* pindex = vStack.back().second;
2924 // print split or gap
2925 if (nCol > nPrevCol)
2927 for (int i = 0; i < nCol-1; i++)
2931 else if (nCol < nPrevCol)
2933 for (int i = 0; i < nCol; i++)
2940 for (int i = 0; i < nCol; i++)
2945 block.ReadFromDisk(pindex);
2946 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
2950 block.GetHash().ToString().c_str(),
2952 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2953 FormatMoney(pindex->nMint).c_str(),
2956 PrintWallets(block);
2958 // put the main time-chain first
2959 vector<CBlockIndex*>& vNext = mapNext[pindex];
2960 for (unsigned int i = 0; i < vNext.size(); i++)
2962 if (vNext[i]->pnext)
2964 swap(vNext[0], vNext[i]);
2970 for (unsigned int i = 0; i < vNext.size(); i++)
2971 vStack.push_back(make_pair(nCol+i, vNext[i]));
2975 bool LoadExternalBlockFile(FILE* fileIn)
2977 int64_t nStart = GetTimeMillis();
2983 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2984 unsigned int nPos = 0;
2985 while (nPos != std::numeric_limits<uint32_t>::max() && blkdat.good() && !fRequestShutdown)
2987 unsigned char pchData[65536];
2989 fseek(blkdat, nPos, SEEK_SET);
2990 size_t nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2993 nPos = std::numeric_limits<uint32_t>::max();
2996 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2999 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
3001 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
3004 nPos += ((unsigned char*)nFind - pchData) + 1;
3007 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
3008 } while(!fRequestShutdown);
3009 if (nPos == std::numeric_limits<uint32_t>::max())
3011 fseek(blkdat, nPos, SEEK_SET);
3014 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
3018 if (ProcessBlock(NULL,&block))
3026 catch (const std::exception&) {
3027 printf("%s() : Deserialize or I/O error caught during load\n",
3028 BOOST_CURRENT_FUNCTION);
3031 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3035 //////////////////////////////////////////////////////////////////////////////
3040 extern map<uint256, CAlert> mapAlerts;
3041 extern CCriticalSection cs_mapAlerts;
3043 string GetWarnings(string strFor)
3046 string strStatusBar;
3049 if (GetBoolArg("-testsafemode"))
3052 // Misc warnings like out of disk space and clock is wrong
3053 if (!strMiscWarning.empty())
3056 strStatusBar = strMiscWarning;
3059 // if detected unmet upgrade requirement enter safe mode
3060 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3061 if (IsFixedModifierInterval(nModifierUpgradeTime + nOneDay)) // 1 day margin
3064 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3067 // if detected invalid checkpoint enter safe mode
3068 if (Checkpoints::hashInvalidCheckpoint != 0)
3071 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3077 for (auto& item : mapAlerts)
3079 const CAlert& alert = item.second;
3080 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3082 nPriority = alert.nPriority;
3083 strStatusBar = alert.strStatusBar;
3084 if (nPriority > 1000)
3085 strRPC = strStatusBar;
3090 if (strFor == "statusbar")
3091 return strStatusBar;
3092 else if (strFor == "rpc")
3094 assert(!"GetWarnings() : invalid parameter");
3105 //////////////////////////////////////////////////////////////////////////////
3111 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3117 bool txInMap = false;
3120 txInMap = (mempool.exists(inv.hash));
3123 mapOrphanTransactions.count(inv.hash) ||
3124 txdb.ContainsTx(inv.hash);
3128 return mapBlockIndex.count(inv.hash) ||
3129 mapOrphanBlocks.count(inv.hash);
3131 // Don't know what it is, just say we already got one
3138 // The message start string is designed to be unlikely to occur in normal data.
3139 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3140 // a large 4-byte int at any alignment.
3141 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3143 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3145 static map<CService, CPubKey> mapReuseKey;
3146 RandAddSeedPerfmon();
3148 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3149 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3151 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3155 if (strCommand == "version")
3157 // Each connection can only send one version message
3158 if (pfrom->nVersion != 0)
3160 pfrom->Misbehaving(1);
3167 uint64_t nNonce = 1;
3168 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3169 if (pfrom->nVersion < MIN_PROTO_VERSION)
3171 // Since February 20, 2012, the protocol is initiated at version 209,
3172 // and earlier versions are no longer supported
3173 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3174 pfrom->fDisconnect = true;
3178 if (pfrom->nVersion == 10300)
3179 pfrom->nVersion = 300;
3181 vRecv >> addrFrom >> nNonce;
3183 vRecv >> pfrom->strSubVer;
3185 vRecv >> pfrom->nStartingHeight;
3187 if (pfrom->fInbound && addrMe.IsRoutable())
3189 pfrom->addrLocal = addrMe;
3193 // Disconnect if we connected to ourself
3194 if (nNonce == nLocalHostNonce && nNonce > 1)
3196 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3197 pfrom->fDisconnect = true;
3201 if (pfrom->nVersion < 60010)
3203 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3204 pfrom->fDisconnect = true;
3208 // record my external IP reported by peer
3209 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3210 addrSeenByPeer = addrMe;
3212 // Be shy and don't send version until we hear
3213 if (pfrom->fInbound)
3214 pfrom->PushVersion();
3216 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3218 AddTimeData(pfrom->addr, nTime);
3221 pfrom->PushMessage("verack");
3222 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3224 if (!pfrom->fInbound)
3226 // Advertise our address
3227 if (!fNoListen && !IsInitialBlockDownload())
3229 CAddress addr = GetLocalAddress(&pfrom->addr);
3230 if (addr.IsRoutable())
3231 pfrom->PushAddress(addr);
3234 // Get recent addresses
3235 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3237 pfrom->PushMessage("getaddr");
3238 pfrom->fGetAddr = true;
3240 addrman.Good(pfrom->addr);
3242 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3244 addrman.Add(addrFrom, addrFrom);
3245 addrman.Good(addrFrom);
3249 // Ask the first connected node for block updates
3250 static int nAskedForBlocks = 0;
3251 if (!pfrom->fClient && !pfrom->fOneShot &&
3252 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3253 (pfrom->nVersion < NOBLKS_VERSION_START ||
3254 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3255 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3258 pfrom->PushGetBlocks(pindexBest, uint256(0));
3264 for (auto& item : mapAlerts)
3265 item.second.RelayTo(pfrom);
3268 // Relay sync-checkpoint
3270 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3271 if (!Checkpoints::checkpointMessage.IsNull())
3272 Checkpoints::checkpointMessage.RelayTo(pfrom);
3275 pfrom->fSuccessfullyConnected = true;
3277 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());
3279 cPeerBlockCounts.input(pfrom->nStartingHeight);
3281 // ppcoin: ask for pending sync-checkpoint if any
3282 if (!IsInitialBlockDownload())
3283 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3287 else if (pfrom->nVersion == 0)
3289 // Must have a version message before anything else
3290 pfrom->Misbehaving(1);
3295 else if (strCommand == "verack")
3297 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3301 else if (strCommand == "addr")
3303 vector<CAddress> vAddr;
3306 // Don't want addr from older versions unless seeding
3307 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3309 if (vAddr.size() > 1000)
3311 pfrom->Misbehaving(20);
3312 return error("message addr size() = %" PRIszu "", vAddr.size());
3315 // Store the new addresses
3316 vector<CAddress> vAddrOk;
3317 int64_t nNow = GetAdjustedTime();
3318 int64_t nSince = nNow - 10 * 60;
3319 for (CAddress& addr : vAddr)
3323 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3324 addr.nTime = nNow - 5 * nOneDay;
3325 pfrom->AddAddressKnown(addr);
3326 bool fReachable = IsReachable(addr);
3327 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3329 // Relay to a limited number of other nodes
3332 // Use deterministic randomness to send to the same nodes for 24 hours
3333 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3334 static uint256 hashSalt;
3336 hashSalt = GetRandHash();
3337 uint64_t hashAddr = addr.GetHash();
3338 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/nOneDay);
3339 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3340 multimap<uint256, CNode*> mapMix;
3341 for (CNode* pnode : vNodes)
3343 if (pnode->nVersion < CADDR_TIME_VERSION)
3345 unsigned int nPointer;
3346 memcpy(&nPointer, &pnode, sizeof(nPointer));
3347 uint256 hashKey = hashRand ^ nPointer;
3348 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3349 mapMix.insert(make_pair(hashKey, pnode));
3351 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3352 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3353 ((*mi).second)->PushAddress(addr);
3356 // Do not store addresses outside our network
3358 vAddrOk.push_back(addr);
3360 addrman.Add(vAddrOk, pfrom->addr, 2 * nOneHour);
3361 if (vAddr.size() < 1000)
3362 pfrom->fGetAddr = false;
3363 if (pfrom->fOneShot)
3364 pfrom->fDisconnect = true;
3367 else if (strCommand == "inv")
3371 if (vInv.size() > MAX_INV_SZ)
3373 pfrom->Misbehaving(20);
3374 return error("message inv size() = %" PRIszu "", vInv.size());
3377 // find last block in inv vector
3378 size_t nLastBlock = std::numeric_limits<size_t>::max();
3379 for (size_t nInv = 0; nInv < vInv.size(); nInv++) {
3380 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3381 nLastBlock = vInv.size() - 1 - nInv;
3386 for (size_t nInv = 0; nInv < vInv.size(); nInv++)
3388 const CInv &inv = vInv[nInv];
3392 pfrom->AddInventoryKnown(inv);
3394 bool fAlreadyHave = AlreadyHave(txdb, inv);
3396 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3400 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3401 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3402 } else if (nInv == nLastBlock) {
3403 // In case we are on a very long side-chain, it is possible that we already have
3404 // the last block in an inv bundle sent in response to getblocks. Try to detect
3405 // this situation and push another getblocks to continue.
3406 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3408 printf("force request: %s\n", inv.ToString().c_str());
3411 // Track requests for our stuff
3412 Inventory(inv.hash);
3417 else if (strCommand == "getdata")
3421 if (vInv.size() > MAX_INV_SZ)
3423 pfrom->Misbehaving(20);
3424 return error("message getdata size() = %" PRIszu "", vInv.size());
3427 if (fDebugNet || (vInv.size() != 1))
3428 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3430 for (const CInv& inv : vInv)
3434 if (fDebugNet || (vInv.size() == 1))
3435 printf("received getdata for: %s\n", inv.ToString().c_str());
3437 if (inv.type == MSG_BLOCK)
3439 // Send block from disk
3440 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3441 if (mi != mapBlockIndex.end())
3444 block.ReadFromDisk((*mi).second);
3445 pfrom->PushMessage("block", block);
3447 // Trigger them to send a getblocks request for the next batch of inventory
3448 if (inv.hash == pfrom->hashContinue)
3450 // ppcoin: send latest proof-of-work block to allow the
3451 // download node to accept as orphan (proof-of-stake
3452 // block might be rejected by stake connection check)
3454 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3455 pfrom->PushMessage("inv", vInv);
3456 pfrom->hashContinue = 0;
3460 else if (inv.IsKnownType())
3462 // Send stream from relay memory
3463 bool pushed = false;
3466 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3467 if (mi != mapRelay.end()) {
3468 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3472 if (!pushed && inv.type == MSG_TX) {
3474 if (mempool.exists(inv.hash)) {
3475 CTransaction tx = mempool.lookup(inv.hash);
3476 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3479 pfrom->PushMessage("tx", ss);
3484 // Track requests for our stuff
3485 Inventory(inv.hash);
3490 else if (strCommand == "getblocks")
3492 CBlockLocator locator;
3494 vRecv >> locator >> hashStop;
3496 // Find the last block the caller has in the main chain
3497 CBlockIndex* pindex = locator.GetBlockIndex();
3499 // Send the rest of the chain
3501 pindex = pindex->pnext;
3503 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3504 for (; pindex; pindex = pindex->pnext)
3506 if (pindex->GetBlockHash() == hashStop)
3508 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3509 // ppcoin: tell downloading node about the latest block if it's
3510 // without risk being rejected due to stake connection check
3511 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3512 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3515 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3518 // When this block is requested, we'll send an inv that'll make them
3519 // getblocks the next batch of inventory.
3520 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3521 pfrom->hashContinue = pindex->GetBlockHash();
3526 else if (strCommand == "checkpoint")
3528 CSyncCheckpoint checkpoint;
3529 vRecv >> checkpoint;
3531 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3534 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3536 for (CNode* pnode : vNodes)
3537 checkpoint.RelayTo(pnode);
3541 else if (strCommand == "getheaders")
3543 CBlockLocator locator;
3545 vRecv >> locator >> hashStop;
3547 CBlockIndex* pindex = NULL;
3548 if (locator.IsNull())
3550 // If locator is null, return the hashStop block
3551 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3552 if (mi == mapBlockIndex.end())
3554 pindex = (*mi).second;
3558 // Find the last block the caller has in the main chain
3559 pindex = locator.GetBlockIndex();
3561 pindex = pindex->pnext;
3564 vector<CBlock> vHeaders;
3566 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3567 for (; pindex; pindex = pindex->pnext)
3569 vHeaders.push_back(pindex->GetBlockHeader());
3570 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3573 pfrom->PushMessage("headers", vHeaders);
3577 else if (strCommand == "tx")
3579 vector<uint256> vWorkQueue;
3580 vector<uint256> vEraseQueue;
3581 CDataStream vMsg(vRecv);
3586 CInv inv(MSG_TX, tx.GetHash());
3587 pfrom->AddInventoryKnown(inv);
3589 bool fMissingInputs = false;
3590 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3592 SyncWithWallets(tx, NULL, true);
3593 RelayTransaction(tx, inv.hash);
3594 mapAlreadyAskedFor.erase(inv);
3595 vWorkQueue.push_back(inv.hash);
3596 vEraseQueue.push_back(inv.hash);
3598 // Recursively process any orphan transactions that depended on this one
3599 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3601 uint256 hashPrev = vWorkQueue[i];
3602 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3603 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3606 const uint256& orphanTxHash = *mi;
3607 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3608 bool fMissingInputs2 = false;
3610 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3612 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3613 SyncWithWallets(tx, NULL, true);
3614 RelayTransaction(orphanTx, orphanTxHash);
3615 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3616 vWorkQueue.push_back(orphanTxHash);
3617 vEraseQueue.push_back(orphanTxHash);
3619 else if (!fMissingInputs2)
3622 vEraseQueue.push_back(orphanTxHash);
3623 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3628 for (uint256 hash : vEraseQueue)
3629 EraseOrphanTx(hash);
3631 else if (fMissingInputs)
3635 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3636 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3638 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3640 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3644 else if (strCommand == "block")
3648 uint256 hashBlock = block.GetHash();
3650 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3653 CInv inv(MSG_BLOCK, hashBlock);
3654 pfrom->AddInventoryKnown(inv);
3656 if (ProcessBlock(pfrom, &block))
3657 mapAlreadyAskedFor.erase(inv);
3658 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3662 // This asymmetric behavior for inbound and outbound connections was introduced
3663 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
3664 // to users' AddrMan and later request them by sending getaddr messages.
3665 // Making users (which are behind NAT and can only make outgoing connections) ignore
3666 // getaddr message mitigates the attack.
3667 else if ((strCommand == "getaddr") && (pfrom->fInbound))
3669 // Don't return addresses older than nCutOff timestamp
3670 int64_t nCutOff = GetTime() - (nNodeLifespan * nOneDay);
3671 pfrom->vAddrToSend.clear();
3672 vector<CAddress> vAddr = addrman.GetAddr();
3673 for (const CAddress &addr : vAddr)
3674 if(addr.nTime > nCutOff)
3675 pfrom->PushAddress(addr);
3679 else if (strCommand == "mempool")
3681 std::vector<uint256> vtxid;
3682 mempool.queryHashes(vtxid);
3684 for (unsigned int i = 0; i < vtxid.size(); i++) {
3685 CInv inv(MSG_TX, vtxid[i]);
3686 vInv.push_back(inv);
3687 if (i == (MAX_INV_SZ - 1))
3690 if (vInv.size() > 0)
3691 pfrom->PushMessage("inv", vInv);
3695 else if (strCommand == "checkorder")
3700 if (!GetBoolArg("-allowreceivebyip"))
3702 pfrom->PushMessage("reply", hashReply, 2, string(""));
3709 /// we have a chance to check the order here
3711 // Keep giving the same key to the same ip until they use it
3712 if (!mapReuseKey.count(pfrom->addr))
3713 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3715 // Send back approval of order and pubkey to use
3716 CScript scriptPubKey;
3717 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3718 pfrom->PushMessage("reply", hashReply, 0, scriptPubKey);
3722 else if (strCommand == "reply")
3727 CRequestTracker tracker;
3729 LOCK(pfrom->cs_mapRequests);
3730 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3731 if (mi != pfrom->mapRequests.end())
3733 tracker = (*mi).second;
3734 pfrom->mapRequests.erase(mi);
3737 if (!tracker.IsNull())
3738 tracker.fn(tracker.param1, vRecv);
3742 else if (strCommand == "ping")
3746 // Echo the message back with the nonce. This allows for two useful features:
3748 // 1) A remote node can quickly check if the connection is operational
3749 // 2) Remote nodes can measure the latency of the network thread. If this node
3750 // is overloaded it won't respond to pings quickly and the remote node can
3751 // avoid sending us more work, like chain download requests.
3753 // The nonce stops the remote getting confused between different pings: without
3754 // it, if the remote node sends a ping once per second and this node takes 5
3755 // seconds to respond to each, the 5th ping the remote sends would appear to
3756 // return very quickly.
3757 pfrom->PushMessage("pong", nonce);
3761 else if (strCommand == "alert")
3766 uint256 alertHash = alert.GetHash();
3767 if (pfrom->setKnown.count(alertHash) == 0)
3769 if (alert.ProcessAlert())
3772 pfrom->setKnown.insert(alertHash);
3775 for (CNode* pnode : vNodes)
3776 alert.RelayTo(pnode);
3780 // Small DoS penalty so peers that send us lots of
3781 // duplicate/expired/invalid-signature/whatever alerts
3782 // eventually get banned.
3783 // This isn't a Misbehaving(100) (immediate ban) because the
3784 // peer might be an older or different implementation with
3785 // a different signature key, etc.
3786 pfrom->Misbehaving(10);
3794 // Ignore unknown commands for extensibility
3798 // Update the last seen time for this node's address
3799 if (pfrom->fNetworkNode)
3800 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3801 AddressCurrentlyConnected(pfrom->addr);
3807 bool ProcessMessages(CNode* pfrom)
3809 CDataStream& vRecv = pfrom->vRecv;
3813 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3817 // (4) message start
3826 // Don't bother if send buffer is too full to respond anyway
3827 if (pfrom->vSend.size() >= SendBufferSize())
3830 // Scan for message start
3831 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3832 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3833 if (vRecv.end() - pstart < nHeaderSize)
3835 if ((int)vRecv.size() > nHeaderSize)
3837 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3838 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3842 if (pstart - vRecv.begin() > 0)
3843 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
3844 vRecv.erase(vRecv.begin(), pstart);
3847 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3852 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3855 string strCommand = hdr.GetCommand();
3858 unsigned int nMessageSize = hdr.nMessageSize;
3859 if (nMessageSize > MAX_SIZE)
3861 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3864 if (nMessageSize > vRecv.size())
3866 // Rewind and wait for rest of message
3867 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3872 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3873 unsigned int nChecksum = 0;
3874 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3875 if (nChecksum != hdr.nChecksum)
3877 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3878 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3882 // Copy message to its own buffer
3883 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3884 vRecv.ignore(nMessageSize);
3892 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3897 catch (std::ios_base::failure& e)
3899 if (strstr(e.what(), "end of data"))
3901 // Allow exceptions from under-length message on vRecv
3902 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());
3904 else if (strstr(e.what(), "size too large"))
3906 // Allow exceptions from over-long size
3907 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3911 PrintExceptionContinue(&e, "ProcessMessages()");
3914 catch (std::exception& e) {
3915 PrintExceptionContinue(&e, "ProcessMessages()");
3917 PrintExceptionContinue(NULL, "ProcessMessages()");
3921 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3931 bool SendMessages(CNode* pto)
3933 TRY_LOCK(cs_main, lockMain);
3935 // Current time in microseconds
3936 int64_t nNow = GetTimeMicros();
3938 // Don't send anything until we get their version message
3939 if (pto->nVersion == 0)
3942 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3944 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
3946 pto->PushMessage("ping", nonce);
3950 if (pto->fStartSync) {
3951 pto->fStartSync = false;
3952 pto->PushGetBlocks(pindexBest, uint256(0));
3955 // Resend wallet transactions that haven't gotten in a block yet
3956 ResendWalletTransactions();
3958 // Address refresh broadcast
3959 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3960 AdvertiseLocal(pto);
3961 pto->nNextLocalAddrSend = PoissonNextSend(nNow, nOneDay);
3967 if (pto->nNextAddrSend < nNow) {
3968 pto->nNextAddrSend = PoissonNextSend(nNow, 30);
3969 vector<CAddress> vAddr;
3970 vAddr.reserve(pto->vAddrToSend.size());
3971 for (const CAddress& addr : pto->vAddrToSend)
3973 if (pto->setAddrKnown.insert(addr).second)
3975 vAddr.push_back(addr);
3976 // receiver rejects addr messages larger than 1000
3977 if (vAddr.size() >= 1000)
3979 pto->PushMessage("addr", vAddr);
3984 pto->vAddrToSend.clear();
3986 pto->PushMessage("addr", vAddr);
3990 // Message: inventory
3993 vector<CInv> vInvWait;
3995 bool fSendTrickle = false;
3996 if (pto->nNextInvSend < nNow) {
3997 fSendTrickle = true;
3998 pto->nNextInvSend = PoissonNextSend(nNow, 5);
4000 LOCK(pto->cs_inventory);
4001 vInv.reserve(pto->vInventoryToSend.size());
4002 vInvWait.reserve(pto->vInventoryToSend.size());
4003 for (const CInv& inv : pto->vInventoryToSend)
4005 if (pto->setInventoryKnown.count(inv))
4008 // trickle out tx inv to protect privacy
4009 if (inv.type == MSG_TX && !fSendTrickle)
4011 // 1/4 of tx invs blast to all immediately
4012 static uint256 hashSalt;
4014 hashSalt = GetRandHash();
4015 uint256 hashRand = inv.hash ^ hashSalt;
4016 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4017 bool fTrickleWait = ((hashRand & 3) != 0);
4021 vInvWait.push_back(inv);
4026 // returns true if wasn't already contained in the set
4027 if (pto->setInventoryKnown.insert(inv).second)
4029 vInv.push_back(inv);
4030 if (vInv.size() >= 1000)
4032 pto->PushMessage("inv", vInv);
4037 pto->vInventoryToSend = vInvWait;
4040 pto->PushMessage("inv", vInv);
4046 vector<CInv> vGetData;
4048 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4050 const CInv& inv = (*pto->mapAskFor.begin()).second;
4051 if (!AlreadyHave(txdb, inv))
4054 printf("sending getdata: %s\n", inv.ToString().c_str());
4055 vGetData.push_back(inv);
4056 if (vGetData.size() >= 1000)
4058 pto->PushMessage("getdata", vGetData);
4061 mapAlreadyAskedFor[inv] = nNow;
4063 pto->mapAskFor.erase(pto->mapAskFor.begin());
4065 if (!vGetData.empty())
4066 pto->PushMessage("getdata", vGetData);
4079 std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4080 for (; it1 != mapBlockIndex.end(); it1++)
4081 delete (*it1).second;
4082 mapBlockIndex.clear();
4085 std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4086 for (; it2 != mapOrphanBlocks.end(); it2++)
4087 delete (*it2).second;
4088 mapOrphanBlocks.clear();
4090 // orphan transactions
4092 } instance_of_cmaincleanup;