1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 #include "checkpoints.h"
10 #include "txdb-leveldb.h"
12 #include "interface.h"
13 #include "checkqueue.h"
19 #include <boost/filesystem.hpp>
20 #include <boost/filesystem/fstream.hpp>
27 CCriticalSection cs_setpwalletRegistered;
28 set<CWallet*> setpwalletRegistered;
30 CCriticalSection cs_main;
33 unsigned int nTransactionsUpdated = 0;
35 map<uint256, CBlockIndex*> mapBlockIndex;
36 set<pair<COutPoint, unsigned int> > setStakeSeen;
38 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
39 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
40 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
41 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
42 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
44 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
46 unsigned int nStakeMinAge = 30 * nOneDay; // 30 days as zero time weight
47 unsigned int nStakeMaxAge = 90 * nOneDay; // 90 days as full weight
48 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
49 unsigned int nModifierInterval = 6 * nOneHour; // time to elapse before new modifier is computed
51 int nCoinbaseMaturity = 500;
53 CBlockIndex* pindexGenesisBlock = NULL;
56 uint256 nBestChainTrust = 0;
57 uint256 nBestInvalidTrust = 0;
59 uint256 hashBestChain = 0;
60 CBlockIndex* pindexBest = NULL;
61 int64_t nTimeBestReceived = 0;
62 int nScriptCheckThreads = 0;
64 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
66 map<uint256, CBlock*> mapOrphanBlocks;
67 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
68 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
69 map<uint256, uint256> mapProofOfStake;
71 map<uint256, CTransaction> mapOrphanTransactions;
72 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
74 // Constant stuff for coinbase transactions we create:
75 CScript COINBASE_FLAGS;
77 const string strMessageMagic = "NovaCoin Signed Message:\n";
80 int64_t nTransactionFee = MIN_TX_FEE;
81 int64_t nMinimumInputValue = MIN_TXOUT_AMOUNT;
83 // Ping and address broadcast intervals
84 int64_t nPingInterval = 30 * 60;
86 extern enum Checkpoints::CPMode CheckpointsMode;
88 //////////////////////////////////////////////////////////////////////////////
90 // dispatching functions
93 // These functions dispatch to one or all registered wallets
96 void RegisterWallet(CWallet* pwalletIn)
99 LOCK(cs_setpwalletRegistered);
100 setpwalletRegistered.insert(pwalletIn);
104 void UnregisterWallet(CWallet* pwalletIn)
107 LOCK(cs_setpwalletRegistered);
108 setpwalletRegistered.erase(pwalletIn);
112 // check whether the passed transaction is from us
113 bool static IsFromMe(CTransaction& tx)
115 for (CWallet* pwallet : setpwalletRegistered)
116 if (pwallet->IsFromMe(tx))
121 // erases transaction with the given hash from all wallets
122 void static EraseFromWallets(uint256 hash)
124 for (CWallet* pwallet : setpwalletRegistered)
125 pwallet->EraseFromWallet(hash);
128 // make sure all wallets know about the given transaction, in the given block
129 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
133 // wallets need to refund inputs when disconnecting coinstake
134 if (tx.IsCoinStake())
136 for (CWallet* pwallet : setpwalletRegistered)
137 if (pwallet->IsFromMe(tx))
138 pwallet->DisableTransaction(tx);
143 for (CWallet* pwallet : setpwalletRegistered)
144 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
147 // notify wallets about a new best chain
148 void static SetBestChain(const CBlockLocator& loc)
150 for (CWallet* pwallet : setpwalletRegistered)
151 pwallet->SetBestChain(loc);
154 // notify wallets about an updated transaction
155 void static UpdatedTransaction(const uint256& hashTx)
157 for (CWallet* pwallet : setpwalletRegistered)
158 pwallet->UpdatedTransaction(hashTx);
162 void static PrintWallets(const CBlock& block)
164 for (CWallet* pwallet : setpwalletRegistered)
165 pwallet->PrintWallet(block);
168 // notify wallets about an incoming inventory (for request counts)
169 void static Inventory(const uint256& hash)
171 for (CWallet* pwallet : setpwalletRegistered)
172 pwallet->Inventory(hash);
175 // ask wallets to resend their transactions
176 void ResendWalletTransactions(bool fForceResend)
178 for (CWallet* pwallet : setpwalletRegistered)
179 pwallet->ResendWalletTransactions(fForceResend);
188 //////////////////////////////////////////////////////////////////////////////
190 // mapOrphanTransactions
193 bool AddOrphanTx(const CTransaction& tx)
195 uint256 hash = tx.GetHash();
196 if (mapOrphanTransactions.count(hash))
199 // Ignore big transactions, to avoid a
200 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
201 // large transaction with a missing parent then we assume
202 // it will rebroadcast it later, after the parent transaction(s)
203 // have been mined or received.
204 // 10,000 orphans, each of which is at most 5,000 bytes big is
205 // at most 500 megabytes of orphans:
207 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
211 printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
215 mapOrphanTransactions[hash] = tx;
216 for (const CTxIn& txin : tx.vin)
217 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
219 printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
220 mapOrphanTransactions.size());
224 void static EraseOrphanTx(uint256 hash)
226 if (!mapOrphanTransactions.count(hash))
228 const CTransaction& tx = mapOrphanTransactions[hash];
229 for (const CTxIn& txin : tx.vin)
231 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
232 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
233 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
235 mapOrphanTransactions.erase(hash);
238 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
240 unsigned int nEvicted = 0;
241 while (mapOrphanTransactions.size() > nMaxOrphans)
243 // Evict a random orphan:
244 uint256 randomhash = GetRandHash();
245 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
246 if (it == mapOrphanTransactions.end())
247 it = mapOrphanTransactions.begin();
248 EraseOrphanTx(it->first);
260 //////////////////////////////////////////////////////////////////////////////
262 // CTransaction and CTxIndex
265 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
268 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
270 if (!ReadFromDisk(txindexRet.pos))
272 if (prevout.n >= vout.size())
280 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
283 return ReadFromDisk(txdb, prevout, txindex);
286 bool CTransaction::ReadFromDisk(COutPoint prevout)
290 return ReadFromDisk(txdb, prevout, txindex);
293 bool CTransaction::IsStandard(string& strReason) const
295 if (nVersion > CTransaction::CURRENT_VERSION)
297 strReason = "version";
301 unsigned int nDataOut = 0;
302 txnouttype whichType;
303 for (const CTxIn& txin : vin)
305 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
306 // keys. (remember the 520 byte limit on redeemScript size) That works
307 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
308 // bytes of scriptSig, which we round off to 1650 bytes for some minor
309 // future-proofing. That's also enough to spend a 20-of-20
310 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
311 // considered standard)
312 if (txin.scriptSig.size() > 1650)
314 strReason = "scriptsig-size";
317 if (!txin.scriptSig.IsPushOnly())
319 strReason = "scriptsig-not-pushonly";
322 if (!txin.scriptSig.HasCanonicalPushes()) {
323 strReason = "txin-scriptsig-not-canonicalpushes";
327 for (const CTxOut& txout : vout) {
328 if (!::IsStandard(txout.scriptPubKey, whichType)) {
329 strReason = "scriptpubkey";
332 if (whichType == TX_NULL_DATA)
335 if (txout.nValue == 0) {
336 strReason = "txout-value=0";
339 if (!txout.scriptPubKey.HasCanonicalPushes()) {
340 strReason = "txout-scriptsig-not-canonicalpushes";
346 // only one OP_RETURN txout is permitted
348 strReason = "multi-op-return";
356 // Check transaction inputs, and make sure any
357 // pay-to-script-hash transactions are evaluating IsStandard scripts
359 // Why bother? To avoid denial-of-service attacks; an attacker
360 // can submit a standard HASH... OP_EQUAL transaction,
361 // which will get accepted into blocks. The redemption
362 // script can be anything; an attacker could use a very
363 // expensive-to-check-upon-redemption script like:
364 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
366 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
369 return true; // Coinbases don't use vin normally
371 for (unsigned int i = 0; i < vin.size(); i++)
373 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
375 vector<vector<unsigned char> > vSolutions;
376 txnouttype whichType;
377 // get the scriptPubKey corresponding to this input:
378 const CScript& prevScript = prev.scriptPubKey;
379 if (!Solver(prevScript, whichType, vSolutions))
381 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
382 if (nArgsExpected < 0)
385 // Transactions with extra stuff in their scriptSigs are
386 // non-standard. Note that this EvalScript() call will
387 // be quick, because if there are any operations
388 // beside "push data" in the scriptSig the
389 // IsStandard() call returns false
390 vector<vector<unsigned char> > stack;
391 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
394 if (whichType == TX_SCRIPTHASH)
398 CScript subscript(stack.back().begin(), stack.back().end());
399 vector<vector<unsigned char> > vSolutions2;
400 txnouttype whichType2;
401 if (!Solver(subscript, whichType2, vSolutions2))
403 if (whichType2 == TX_SCRIPTHASH)
407 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
410 nArgsExpected += tmpExpected;
413 if (stack.size() != (unsigned int)nArgsExpected)
421 CTransaction::GetLegacySigOpCount() const
423 unsigned int nSigOps = 0;
426 // Coinbase scriptsigs are never executed, so there is
427 // no sense in calculation of sigops.
428 for (const CTxIn& txin : vin)
430 nSigOps += txin.scriptSig.GetSigOpCount(false);
433 for (const CTxOut& txout : vout)
435 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
440 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
453 // Load the block this tx is in
455 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
457 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
462 // Update the tx's hashBlock
463 hashBlock = pblock->GetHash();
465 // Locate the transaction
466 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
467 if (pblock->vtx[nIndex] == *(CTransaction*)this)
469 if (nIndex == (int)pblock->vtx.size())
471 vMerkleBranch.clear();
473 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
477 // Fill in merkle branch
478 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
481 // Is the tx in a block that's in the main chain
482 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
483 if (mi == mapBlockIndex.end())
485 const CBlockIndex* pindex = (*mi).second;
486 if (!pindex || !pindex->IsInMainChain())
489 return pindexBest->nHeight - pindex->nHeight + 1;
492 bool CTransaction::CheckTransaction() const
494 // Basic checks that don't depend on any context
496 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
498 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
500 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
501 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
503 // Check for negative or overflow output values
504 int64_t nValueOut = 0;
505 for (unsigned int i = 0; i < vout.size(); i++)
507 const CTxOut& txout = vout[i];
508 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
509 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
511 if (txout.nValue < 0)
512 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
513 if (txout.nValue > MAX_MONEY)
514 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
515 nValueOut += txout.nValue;
516 if (!MoneyRange(nValueOut))
517 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
520 // Check for duplicate inputs
521 set<COutPoint> vInOutPoints;
522 for (const CTxIn& txin : vin)
524 if (vInOutPoints.count(txin.prevout))
526 vInOutPoints.insert(txin.prevout);
531 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
532 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
536 for (const CTxIn& txin : vin)
537 if (txin.prevout.IsNull())
538 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
544 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
546 int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
550 // Enforce 0.01 as minimum fee for coinstake
552 nMinRelayTxFee = CENT;
555 // Base fee is either nMinTxFee or nMinRelayTxFee
556 int64_t nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
558 unsigned int nNewBlockSize = nBlockSize + nBytes;
559 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
565 // Transactions under 1K are free
571 // Free transaction area
572 if (nNewBlockSize < 27000)
577 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
578 // each non empty output which is less than 0.01
580 // It's safe to ignore empty outputs here, because these inputs are allowed
581 // only for coinbase and coinstake transactions.
582 for (const CTxOut& txout : vout)
583 if (txout.nValue < CENT && !txout.IsEmpty())
586 // Raise the price as the block approaches full
587 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
589 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
591 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
594 if (!MoneyRange(nMinFee))
601 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
602 bool* pfMissingInputs)
605 *pfMissingInputs = false;
607 // Time (prevent mempool memory exhaustion attack)
608 if (tx.nTime > FutureDrift(GetAdjustedTime()))
609 return tx.DoS(10, error("CTxMemPool::accept() : transaction timestamp is too far in the future"));
611 if (!tx.CheckTransaction())
612 return error("CTxMemPool::accept() : CheckTransaction failed");
614 // Coinbase is only valid in a block, not as a loose transaction
616 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
618 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
619 if (tx.IsCoinStake())
620 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
622 // To help v0.1.5 clients who would see it as a negative number
623 if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
624 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
626 // Rather not work on nonstandard transactions (unless -testnet)
628 if (!fTestNet && !tx.IsStandard(strNonStd))
629 return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
631 // Do we already have it?
632 uint256 hash = tx.GetHash();
635 if (mapTx.count(hash))
639 if (txdb.ContainsTx(hash))
642 // Check for conflicts with in-memory transactions
643 CTransaction* ptxOld = NULL;
644 for (unsigned int i = 0; i < tx.vin.size(); i++)
646 COutPoint outpoint = tx.vin[i].prevout;
647 if (mapNextTx.count(outpoint))
649 // Disable replacement feature for now
652 // Allow replacing with a newer version of the same transaction
655 ptxOld = mapNextTx[outpoint].ptx;
656 if (ptxOld->IsFinal())
658 if (!tx.IsNewerThan(*ptxOld))
660 for (unsigned int i = 0; i < tx.vin.size(); i++)
662 COutPoint outpoint = tx.vin[i].prevout;
663 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
673 map<uint256, CTxIndex> mapUnused;
674 bool fInvalid = false;
675 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
678 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
680 *pfMissingInputs = true;
684 // Check for non-standard pay-to-script-hash in inputs
685 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
686 return error("CTxMemPool::accept() : nonstandard transaction input");
688 // Note: if you modify this code to accept non-standard transactions, then
689 // you should add code here to check that the transaction does a
690 // reasonable number of ECDSA signature verifications.
692 int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
693 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
695 // Don't accept it if it can't get into a block
696 int64_t txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
697 if (nFees < txMinFee)
698 return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
699 hash.ToString().c_str(),
702 // Continuously rate-limit free transactions
703 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
704 // be annoying or make others' transactions take longer to confirm.
705 if (nFees < MIN_RELAY_TX_FEE)
707 static CCriticalSection cs;
708 static double dFreeCount;
709 static int64_t nLastTime;
710 int64_t nNow = GetTime();
714 // Use an exponentially decaying ~10-minute window:
715 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
717 // -limitfreerelay unit is thousand-bytes-per-minute
718 // At default rate it would take over a month to fill 1GB
719 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
720 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
722 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
727 // Check against previous transactions
728 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
729 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, STRICT_FLAGS))
731 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
735 // Store transaction in memory
740 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
743 addUnchecked(hash, tx);
746 ///// are we sure this is ok when loading transactions or restoring block txes
747 // If updated, erase old tx from wallet
749 EraseFromWallets(ptxOld->GetHash());
751 printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
752 hash.ToString().substr(0,10).c_str(),
757 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
759 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
762 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
764 // Add to memory pool without checking anything. Don't call this directly,
765 // call CTxMemPool::accept to properly check the transaction first.
768 for (unsigned int i = 0; i < tx.vin.size(); i++)
769 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
770 nTransactionsUpdated++;
776 bool CTxMemPool::remove(CTransaction &tx)
778 // Remove transaction from memory pool
781 uint256 hash = tx.GetHash();
782 if (mapTx.count(hash))
784 for (const CTxIn& txin : tx.vin)
785 mapNextTx.erase(txin.prevout);
787 nTransactionsUpdated++;
793 void CTxMemPool::clear()
798 ++nTransactionsUpdated;
801 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
806 vtxid.reserve(mapTx.size());
807 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
808 vtxid.push_back((*mi).first);
814 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
816 if (hashBlock == 0 || nIndex == -1)
819 // Find the block it claims to be in
820 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
821 if (mi == mapBlockIndex.end())
823 CBlockIndex* pindex = (*mi).second;
824 if (!pindex || !pindex->IsInMainChain())
827 // Make sure the merkle branch connects to this block
828 if (!fMerkleVerified)
830 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
832 fMerkleVerified = true;
836 return pindexBest->nHeight - pindex->nHeight + 1;
840 int CMerkleTx::GetBlocksToMaturity() const
842 if (!(IsCoinBase() || IsCoinStake()))
844 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
848 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
852 if (!IsInMainChain() && !ClientConnectInputs())
854 return CTransaction::AcceptToMemoryPool(txdb, false);
858 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
862 bool CMerkleTx::AcceptToMemoryPool()
865 return AcceptToMemoryPool(txdb);
868 int CTxIndex::GetDepthInMainChain() const
872 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
874 // Find the block in the index
875 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
876 if (mi == mapBlockIndex.end())
878 CBlockIndex* pindex = (*mi).second;
879 if (!pindex || !pindex->IsInMainChain())
881 return 1 + nBestHeight - pindex->nHeight;
884 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
885 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
891 if (mempool.exists(hash))
893 tx = mempool.lookup(hash);
899 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
902 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
903 hashBlock = block.GetHash();
917 //////////////////////////////////////////////////////////////////////////////
919 // CBlock and CBlockIndex
922 static CBlockIndex* pblockindexFBBHLast;
923 CBlockIndex* FindBlockByHeight(int nHeight)
925 CBlockIndex *pblockindex;
926 if (nHeight < nBestHeight / 2)
927 pblockindex = pindexGenesisBlock;
929 pblockindex = pindexBest;
930 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
931 pblockindex = pblockindexFBBHLast;
932 while (pblockindex->nHeight > nHeight)
933 pblockindex = pblockindex->pprev;
934 while (pblockindex->nHeight < nHeight)
935 pblockindex = pblockindex->pnext;
936 pblockindexFBBHLast = pblockindex;
940 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
942 if (!fReadTransactions)
944 *this = pindex->GetBlockHeader();
947 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
949 if (GetHash() != pindex->GetBlockHash())
950 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
954 uint256 static GetOrphanRoot(const CBlock* pblock)
956 // Work back to the first block in the orphan chain
957 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
958 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
959 return pblock->GetHash();
962 // ppcoin: find block wanted by given orphan block
963 uint256 WantedByOrphan(const CBlock* pblockOrphan)
965 // Work back to the first block in the orphan chain
966 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
967 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
968 return pblockOrphan->hashPrevBlock;
971 // select stake target limit according to hard-coded conditions
972 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
974 if(fTestNet) // separate proof of stake target limit for testnet
975 return bnProofOfStakeLimit;
976 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
977 return bnProofOfStakeLimit;
978 if(nHeight + 1 > 15000) // 24 bits since block 15000
979 return bnProofOfStakeLegacyLimit;
980 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
981 return bnProofOfStakeHardLimit;
983 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
986 // miner's coin base reward based on nBits
987 int64_t GetProofOfWorkReward(unsigned int nBits)
989 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
992 bnTarget.SetCompact(nBits);
993 CBigNum bnTargetLimit = bnProofOfWorkLimit;
994 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
996 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
997 // A reasonably continuous curve is used to avoid shock to market
998 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1000 // Human readable form:
1002 // nSubsidy = 100 / (diff ^ 1/6)
1004 // Please note that we're using bisection to find an approximate solutuion
1005 CBigNum bnLowerBound = CENT;
1006 CBigNum bnUpperBound = bnSubsidyLimit;
1007 while (bnLowerBound + CENT <= bnUpperBound)
1009 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1010 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1011 bnUpperBound = bnMidValue;
1013 bnLowerBound = bnMidValue;
1016 int64_t nSubsidy = bnUpperBound.getuint64();
1018 nSubsidy = (nSubsidy / CENT) * CENT;
1019 if (fDebug && GetBoolArg("-printcreation"))
1020 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1022 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
1025 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1026 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1028 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1030 // Stage 2 of emission process is mostly PoS-based.
1032 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1034 bnTarget.SetCompact(nBits);
1035 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1036 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1038 // A reasonably continuous curve is used to avoid shock to market
1040 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1041 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1042 bnMidPart, bnRewardPart;
1044 while (bnLowerBound + CENT <= bnUpperBound)
1046 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1049 // Reward for coin-year is cut in half every 8x multiply of PoS difficulty
1051 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1053 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1056 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1057 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1059 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1060 bnUpperBound = bnMidValue;
1062 bnLowerBound = bnMidValue;
1065 nRewardCoinYear = bnUpperBound.getuint64();
1066 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1069 return nRewardCoinYear;
1071 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1073 // Set reasonable reward limit for large inputs
1075 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1077 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1078 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1080 nSubsidy = min(nSubsidy, nSubsidyLimit);
1082 if (fDebug && GetBoolArg("-printcreation"))
1083 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1088 static const int64_t nTargetTimespan = 7 * nOneDay; // one week
1090 // get proof of work blocks max spacing according to hard-coded conditions
1091 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1093 if(nTime > TARGETS_SWITCH_TIME)
1094 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1097 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1099 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1103 // maximum nBits value could possible be required nTime after
1105 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1108 bnResult.SetCompact(nBase);
1110 while (nTime > 0 && bnResult < bnTargetLimit)
1112 // Maximum 200% adjustment per day...
1116 if (bnResult > bnTargetLimit)
1117 bnResult = bnTargetLimit;
1118 return bnResult.GetCompact();
1122 // minimum amount of work that could possibly be required nTime after
1123 // minimum proof-of-work required was nBase
1125 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1127 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1131 // minimum amount of stake that could possibly be required nTime after
1132 // minimum proof-of-stake required was nBase
1134 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1136 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1140 // ppcoin: find last block index up to pindex
1141 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1143 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1144 pindex = pindex->pprev;
1148 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1150 if (pindexLast == NULL)
1151 return bnProofOfWorkLimit.GetCompact(); // genesis block
1153 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1155 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1156 if (pindexPrev->pprev == NULL)
1157 return bnTargetLimit.GetCompact(); // first block
1158 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1159 if (pindexPrevPrev->pprev == NULL)
1160 return bnTargetLimit.GetCompact(); // second block
1162 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1164 // ppcoin: target change every block
1165 // ppcoin: retarget with exponential moving toward target spacing
1167 bnNew.SetCompact(pindexPrev->nBits);
1168 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1169 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1170 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1171 bnNew /= ((nInterval + 1) * nTargetSpacing);
1173 if (bnNew > bnTargetLimit)
1174 bnNew = bnTargetLimit;
1176 return bnNew.GetCompact();
1179 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1182 bnTarget.SetCompact(nBits);
1185 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1186 return error("CheckProofOfWork() : nBits below minimum work");
1188 // Check proof of work matches claimed amount
1189 if (hash > bnTarget.getuint256())
1190 return error("CheckProofOfWork() : hash doesn't match nBits");
1195 // Return maximum amount of blocks that other nodes claim to have
1196 int GetNumBlocksOfPeers()
1198 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1201 bool IsInitialBlockDownload()
1203 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1205 static int64_t nLastUpdate;
1206 static CBlockIndex* pindexLastBest;
1207 int64_t nCurrentTime = GetTime();
1208 if (pindexBest != pindexLastBest)
1210 pindexLastBest = pindexBest;
1211 nLastUpdate = nCurrentTime;
1213 return (nCurrentTime - nLastUpdate < 10 &&
1214 pindexBest->GetBlockTime() < nCurrentTime - nOneDay);
1217 void static InvalidChainFound(CBlockIndex* pindexNew)
1219 if (pindexNew->nChainTrust > nBestInvalidTrust)
1221 nBestInvalidTrust = pindexNew->nChainTrust;
1222 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1223 uiInterface.NotifyBlocksChanged();
1226 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1227 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1229 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1230 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1231 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1232 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1233 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1234 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1235 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1236 nBestBlockTrust.Get64(),
1237 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1240 uint256 CBlock::GetHash() const
1242 return scrypt_blockhash((const uint8_t*)&nVersion);
1245 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1247 nTime = max(GetBlockTime(), GetAdjustedTime());
1260 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1262 // Relinquish previous transactions' spent pointers
1265 for (const CTxIn& txin : vin)
1267 COutPoint prevout = txin.prevout;
1269 // Get prev txindex from disk
1271 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1272 return error("DisconnectInputs() : ReadTxIndex failed");
1274 if (prevout.n >= txindex.vSpent.size())
1275 return error("DisconnectInputs() : prevout.n out of range");
1277 // Mark outpoint as not spent
1278 txindex.vSpent[prevout.n].SetNull();
1281 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1282 return error("DisconnectInputs() : UpdateTxIndex failed");
1286 // Remove transaction from index
1287 // This can fail if a duplicate of this transaction was in a chain that got
1288 // reorganized away. This is only possible if this transaction was completely
1289 // spent, so erasing it would be a no-op anyway.
1290 txdb.EraseTxIndex(*this);
1296 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1297 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1299 // FetchInputs can return false either because we just haven't seen some inputs
1300 // (in which case the transaction should be stored as an orphan)
1301 // or because the transaction is malformed (in which case the transaction should
1302 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1306 return true; // Coinbase transactions have no inputs to fetch.
1308 for (unsigned int i = 0; i < vin.size(); i++)
1310 COutPoint prevout = vin[i].prevout;
1311 if (inputsRet.count(prevout.hash))
1312 continue; // Got it already
1315 CTxIndex& txindex = inputsRet[prevout.hash].first;
1317 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1319 // Get txindex from current proposed changes
1320 txindex = mapTestPool.find(prevout.hash)->second;
1324 // Read txindex from txdb
1325 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1327 if (!fFound && (fBlock || fMiner))
1328 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());
1331 CTransaction& txPrev = inputsRet[prevout.hash].second;
1332 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1334 // Get prev tx from single transactions in memory
1337 if (!mempool.exists(prevout.hash))
1338 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());
1339 txPrev = mempool.lookup(prevout.hash);
1342 txindex.vSpent.resize(txPrev.vout.size());
1346 // Get prev tx from disk
1347 if (!txPrev.ReadFromDisk(txindex.pos))
1348 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1352 // Make sure all prevout.n indexes are valid:
1353 for (unsigned int i = 0; i < vin.size(); i++)
1355 const COutPoint prevout = vin[i].prevout;
1356 assert(inputsRet.count(prevout.hash) != 0);
1357 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1358 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1359 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1361 // Revisit this if/when transaction replacement is implemented and allows
1364 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()));
1371 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1373 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1374 if (mi == inputs.end())
1375 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1377 const CTransaction& txPrev = (mi->second).second;
1378 if (input.prevout.n >= txPrev.vout.size())
1379 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1381 return txPrev.vout[input.prevout.n];
1384 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1389 int64_t nResult = 0;
1390 for (unsigned int i = 0; i < vin.size(); i++)
1392 nResult += GetOutputFor(vin[i], inputs).nValue;
1398 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1403 unsigned int nSigOps = 0;
1404 for (unsigned int i = 0; i < vin.size(); i++)
1406 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1407 if (prevout.scriptPubKey.IsPayToScriptHash())
1408 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1413 bool CScriptCheck::operator()() const {
1414 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1415 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1416 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1420 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1422 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1425 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1426 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1428 // Take over previous transactions' spent pointers
1429 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1430 // fMiner is true when called from the internal bitcoin miner
1431 // ... both are false when called from CTransaction::AcceptToMemoryPool
1435 int64_t nValueIn = 0;
1437 for (unsigned int i = 0; i < vin.size(); i++)
1439 COutPoint prevout = vin[i].prevout;
1440 assert(inputs.count(prevout.hash) > 0);
1441 CTxIndex& txindex = inputs[prevout.hash].first;
1442 CTransaction& txPrev = inputs[prevout.hash].second;
1444 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1445 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()));
1447 // If prev is coinbase or coinstake, check that it's matured
1448 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1449 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1450 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1451 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1453 // ppcoin: check transaction timestamp
1454 if (txPrev.nTime > nTime)
1455 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1457 // Check for negative or overflow input values
1458 nValueIn += txPrev.vout[prevout.n].nValue;
1459 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1460 return DoS(100, error("ConnectInputs() : txin values out of range"));
1465 pvChecks->reserve(vin.size());
1467 // The first loop above does all the inexpensive checks.
1468 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1469 // Helps prevent CPU exhaustion attacks.
1470 for (unsigned int i = 0; i < vin.size(); i++)
1472 COutPoint prevout = vin[i].prevout;
1473 assert(inputs.count(prevout.hash) > 0);
1474 CTxIndex& txindex = inputs[prevout.hash].first;
1475 CTransaction& txPrev = inputs[prevout.hash].second;
1477 // Check for conflicts (double-spend)
1478 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1479 // for an attacker to attempt to split the network.
1480 if (!txindex.vSpent[prevout.n].IsNull())
1481 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());
1483 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1484 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1485 // still computed and checked, and any change will be caught at the next checkpoint.
1489 CScriptCheck check(txPrev, *this, i, flags, 0);
1492 pvChecks->push_back(CScriptCheck());
1493 check.swap(pvChecks->back());
1497 if (flags & STRICT_FLAGS)
1499 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1500 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1502 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1504 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1508 // Mark outpoints as spent
1509 txindex.vSpent[prevout.n] = posThisTx;
1512 if (fBlock || fMiner)
1514 mapTestPool[prevout.hash] = txindex;
1520 if (nTime > Checkpoints::GetLastCheckpointTime())
1522 unsigned int nTxSize = GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
1524 // coin stake tx earns reward instead of paying fee
1526 if (!GetCoinAge(txdb, nCoinAge))
1527 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1529 int64_t nReward = GetValueOut() - nValueIn;
1530 int64_t nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1532 if (nReward > nCalculatedReward)
1533 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1538 if (nValueIn < GetValueOut())
1539 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1541 // Tally transaction fees
1542 int64_t nTxFee = nValueIn - GetValueOut();
1544 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1547 if (!MoneyRange(nFees))
1548 return DoS(100, error("ConnectInputs() : nFees out of range"));
1556 bool CTransaction::ClientConnectInputs()
1561 // Take over previous transactions' spent pointers
1564 int64_t nValueIn = 0;
1565 for (unsigned int i = 0; i < vin.size(); i++)
1567 // Get prev tx from single transactions in memory
1568 COutPoint prevout = vin[i].prevout;
1569 if (!mempool.exists(prevout.hash))
1571 CTransaction& txPrev = mempool.lookup(prevout.hash);
1573 if (prevout.n >= txPrev.vout.size())
1577 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1578 return error("ClientConnectInputs() : VerifySignature failed");
1580 ///// this is redundant with the mempool.mapNextTx stuff,
1581 ///// not sure which I want to get rid of
1582 ///// this has to go away now that posNext is gone
1583 // // Check for conflicts
1584 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1585 // return error("ConnectInputs() : prev tx already used");
1587 // // Flag outpoints as used
1588 // txPrev.vout[prevout.n].posNext = posThisTx;
1590 nValueIn += txPrev.vout[prevout.n].nValue;
1592 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1593 return error("ClientConnectInputs() : txin values out of range");
1595 if (GetValueOut() > nValueIn)
1605 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1607 // Disconnect in reverse order
1608 for (int i = vtx.size()-1; i >= 0; i--)
1609 if (!vtx[i].DisconnectInputs(txdb))
1612 // Update block index on disk without changing it in memory.
1613 // The memory index structure will be changed after the db commits.
1616 CDiskBlockIndex blockindexPrev(pindex->pprev);
1617 blockindexPrev.hashNext = 0;
1618 if (!txdb.WriteBlockIndex(blockindexPrev))
1619 return error("DisconnectBlock() : WriteBlockIndex failed");
1622 // ppcoin: clean up wallet after disconnecting coinstake
1623 for (CTransaction& tx : vtx)
1624 SyncWithWallets(tx, this, false, false);
1629 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1631 void ThreadScriptCheck(void*) {
1632 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1633 RenameThread("novacoin-scriptch");
1634 scriptcheckqueue.Thread();
1635 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1638 void ThreadScriptCheckQuit() {
1639 scriptcheckqueue.Quit();
1642 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1644 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1645 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1648 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1649 // unless those are already completely spent.
1650 // If such overwrites are allowed, coinbases and transactions depending upon those
1651 // can be duplicated to remove the ability to spend the first instance -- even after
1652 // being sent to another address.
1653 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1654 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1655 // already refuses previously-known transaction ids entirely.
1656 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1657 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1658 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1659 // initial block download.
1660 bool fEnforceBIP30 = true; // Always active in NovaCoin
1661 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1663 //// issue here: it doesn't know the version
1664 unsigned int nTxPos;
1666 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1667 // 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
1670 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1672 map<uint256, CTxIndex> mapQueuedChanges;
1673 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1676 int64_t nValueIn = 0;
1677 int64_t nValueOut = 0;
1678 unsigned int nSigOps = 0;
1679 for (CTransaction& tx : vtx)
1681 uint256 hashTx = tx.GetHash();
1683 if (fEnforceBIP30) {
1684 CTxIndex txindexOld;
1685 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1686 for (CDiskTxPos &pos : txindexOld.vSpent)
1692 nSigOps += tx.GetLegacySigOpCount();
1693 if (nSigOps > MAX_BLOCK_SIGOPS)
1694 return DoS(100, error("ConnectBlock() : too many sigops"));
1696 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1698 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1700 MapPrevTx mapInputs;
1701 if (tx.IsCoinBase())
1702 nValueOut += tx.GetValueOut();
1706 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1709 // Add in sigops done by pay-to-script-hash inputs;
1710 // this is to prevent a "rogue miner" from creating
1711 // an incredibly-expensive-to-validate block.
1712 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1713 if (nSigOps > MAX_BLOCK_SIGOPS)
1714 return DoS(100, error("ConnectBlock() : too many sigops"));
1716 int64_t nTxValueIn = tx.GetValueIn(mapInputs);
1717 int64_t nTxValueOut = tx.GetValueOut();
1718 nValueIn += nTxValueIn;
1719 nValueOut += nTxValueOut;
1720 if (!tx.IsCoinStake())
1721 nFees += nTxValueIn - nTxValueOut;
1723 unsigned int nFlags = SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH;
1725 if (tx.nTime >= CHECKLOCKTIMEVERIFY_SWITCH_TIME) {
1726 nFlags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;
1729 if (tx.nTime >= CHECKSEQUENCEVERIFY_SWITCH_TIME) {
1730 nFlags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;
1733 std::vector<CScriptCheck> vChecks;
1734 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, nFlags, nScriptCheckThreads ? &vChecks : NULL))
1736 control.Add(vChecks);
1739 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1742 if (!control.Wait())
1743 return DoS(100, false);
1745 if (IsProofOfWork())
1747 int64_t nBlockReward = GetProofOfWorkReward(nBits) + nFees;
1749 // Check coinbase reward
1750 if (vtx[0].GetValueOut() > nBlockReward)
1751 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1752 vtx[0].GetValueOut(),
1756 // track money supply and mint amount info
1757 pindex->nMint = nValueOut - nValueIn + nFees;
1758 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1759 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1760 return error("Connect() : WriteBlockIndex for pindex failed");
1762 // fees are not collected by proof-of-stake miners
1763 // fees are destroyed to compensate the entire network
1764 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1765 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
1770 // Write queued txindex changes
1771 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1773 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1774 return error("ConnectBlock() : UpdateTxIndex failed");
1777 // Update block index on disk without changing it in memory.
1778 // The memory index structure will be changed after the db commits.
1781 CDiskBlockIndex blockindexPrev(pindex->pprev);
1782 blockindexPrev.hashNext = pindex->GetBlockHash();
1783 if (!txdb.WriteBlockIndex(blockindexPrev))
1784 return error("ConnectBlock() : WriteBlockIndex failed");
1787 // Watch for transactions paying to me
1788 for (CTransaction& tx : vtx)
1789 SyncWithWallets(tx, this, true);
1795 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1797 printf("REORGANIZE\n");
1800 CBlockIndex* pfork = pindexBest;
1801 CBlockIndex* plonger = pindexNew;
1802 while (pfork != plonger)
1804 while (plonger->nHeight > pfork->nHeight)
1805 if ((plonger = plonger->pprev) == NULL)
1806 return error("Reorganize() : plonger->pprev is null");
1807 if (pfork == plonger)
1809 if ((pfork = pfork->pprev) == NULL)
1810 return error("Reorganize() : pfork->pprev is null");
1813 // List of what to disconnect
1814 vector<CBlockIndex*> vDisconnect;
1815 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1816 vDisconnect.push_back(pindex);
1818 // List of what to connect
1819 vector<CBlockIndex*> vConnect;
1820 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1821 vConnect.push_back(pindex);
1822 reverse(vConnect.begin(), vConnect.end());
1824 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());
1825 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());
1827 // Disconnect shorter branch
1828 vector<CTransaction> vResurrect;
1829 for (CBlockIndex* pindex : vDisconnect)
1832 if (!block.ReadFromDisk(pindex))
1833 return error("Reorganize() : ReadFromDisk for disconnect failed");
1834 if (!block.DisconnectBlock(txdb, pindex))
1835 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1837 // Queue memory transactions to resurrect
1838 for (const CTransaction& tx : block.vtx)
1839 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1840 vResurrect.push_back(tx);
1843 // Connect longer branch
1844 vector<CTransaction> vDelete;
1845 for (unsigned int i = 0; i < vConnect.size(); i++)
1847 CBlockIndex* pindex = vConnect[i];
1849 if (!block.ReadFromDisk(pindex))
1850 return error("Reorganize() : ReadFromDisk for connect failed");
1851 if (!block.ConnectBlock(txdb, pindex))
1854 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1857 // Queue memory transactions to delete
1858 for (const CTransaction& tx : block.vtx)
1859 vDelete.push_back(tx);
1861 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1862 return error("Reorganize() : WriteHashBestChain failed");
1864 // Make sure it's successfully written to disk before changing memory structure
1865 if (!txdb.TxnCommit())
1866 return error("Reorganize() : TxnCommit failed");
1868 // Disconnect shorter branch
1869 for (CBlockIndex* pindex : vDisconnect)
1871 pindex->pprev->pnext = NULL;
1873 // Connect longer branch
1874 for (CBlockIndex* pindex : vConnect)
1876 pindex->pprev->pnext = pindex;
1878 // Resurrect memory transactions that were in the disconnected branch
1879 for (CTransaction& tx : vResurrect)
1880 tx.AcceptToMemoryPool(txdb, false);
1882 // Delete redundant memory transactions that are in the connected branch
1883 for (CTransaction& tx : vDelete)
1886 printf("REORGANIZE: done\n");
1892 // Called from inside SetBestChain: attaches a block to the new best chain being built
1893 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1895 uint256 hash = GetHash();
1897 // Adding to current best branch
1898 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1901 InvalidChainFound(pindexNew);
1904 if (!txdb.TxnCommit())
1905 return error("SetBestChain() : TxnCommit failed");
1907 // Add to current best branch
1908 pindexNew->pprev->pnext = pindexNew;
1910 // Delete redundant memory transactions
1911 for (CTransaction& tx : vtx)
1917 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1919 uint256 hash = GetHash();
1921 if (!txdb.TxnBegin())
1922 return error("SetBestChain() : TxnBegin failed");
1924 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1926 txdb.WriteHashBestChain(hash);
1927 if (!txdb.TxnCommit())
1928 return error("SetBestChain() : TxnCommit failed");
1929 pindexGenesisBlock = pindexNew;
1931 else if (hashPrevBlock == hashBestChain)
1933 if (!SetBestChainInner(txdb, pindexNew))
1934 return error("SetBestChain() : SetBestChainInner failed");
1938 // the first block in the new chain that will cause it to become the new best chain
1939 CBlockIndex *pindexIntermediate = pindexNew;
1941 // list of blocks that need to be connected afterwards
1942 std::vector<CBlockIndex*> vpindexSecondary;
1944 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1945 // Try to limit how much needs to be done inside
1946 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1948 vpindexSecondary.push_back(pindexIntermediate);
1949 pindexIntermediate = pindexIntermediate->pprev;
1952 if (!vpindexSecondary.empty())
1953 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
1955 // Switch to new best branch
1956 if (!Reorganize(txdb, pindexIntermediate))
1959 InvalidChainFound(pindexNew);
1960 return error("SetBestChain() : Reorganize failed");
1963 // Connect further blocks
1964 for (std::vector<CBlockIndex*>::reverse_iterator rit = vpindexSecondary.rbegin(); rit != vpindexSecondary.rend(); ++rit)
1967 if (!block.ReadFromDisk(*rit))
1969 printf("SetBestChain() : ReadFromDisk failed\n");
1972 if (!txdb.TxnBegin()) {
1973 printf("SetBestChain() : TxnBegin 2 failed\n");
1976 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1977 if (!block.SetBestChainInner(txdb, *rit))
1982 // Update best block in wallet (so we can detect restored wallets)
1983 bool fIsInitialDownload = IsInitialBlockDownload();
1984 if (!fIsInitialDownload)
1986 const CBlockLocator locator(pindexNew);
1987 ::SetBestChain(locator);
1991 hashBestChain = hash;
1992 pindexBest = pindexNew;
1993 pblockindexFBBHLast = NULL;
1994 nBestHeight = pindexBest->nHeight;
1995 nBestChainTrust = pindexNew->nChainTrust;
1996 nTimeBestReceived = GetTime();
1997 nTransactionsUpdated++;
1999 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2001 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
2002 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2003 CBigNum(nBestChainTrust).ToString().c_str(),
2004 nBestBlockTrust.Get64(),
2005 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2007 // Check the version of the last 100 blocks to see if we need to upgrade:
2008 if (!fIsInitialDownload)
2011 const CBlockIndex* pindex = pindexBest;
2012 for (int i = 0; i < 100 && pindex != NULL; i++)
2014 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2016 pindex = pindex->pprev;
2019 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2020 if (nUpgraded > 100/2)
2021 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2022 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2025 std::string strCmd = GetArg("-blocknotify", "");
2027 if (!fIsInitialDownload && !strCmd.empty())
2029 boost::thread t(runCommand, regex_replace(strCmd, static_cast<std::regex>("%s"), hashBestChain.GetHex()));
2034 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2035 // Only those coins meeting minimum age requirement counts. As those
2036 // transactions not in main chain are not currently indexed so we
2037 // might not find out about their coin age. Older transactions are
2038 // guaranteed to be in main chain by sync-checkpoint. This rule is
2039 // introduced to help nodes establish a consistent view of the coin
2040 // age (trust score) of competing branches.
2041 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2043 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2049 for (const CTxIn& txin : vin)
2051 // First try finding the previous transaction in database
2052 CTransaction txPrev;
2054 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2055 continue; // previous transaction not in main chain
2056 if (nTime < txPrev.nTime)
2057 return false; // Transaction timestamp violation
2059 // Read block header
2061 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2062 return false; // unable to read block of previous transaction
2063 if (block.GetBlockTime() + nStakeMinAge > nTime)
2064 continue; // only count coins meeting min age requirement
2066 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
2067 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2069 if (fDebug && GetBoolArg("-printcoinage"))
2070 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2073 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / nOneDay;
2074 if (fDebug && GetBoolArg("-printcoinage"))
2075 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2076 nCoinAge = bnCoinDay.getuint64();
2080 // ppcoin: total coin age spent in block, in the unit of coin-days.
2081 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2086 for (const CTransaction& tx : vtx)
2088 uint64_t nTxCoinAge;
2089 if (tx.GetCoinAge(txdb, nTxCoinAge))
2090 nCoinAge += nTxCoinAge;
2095 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2097 if (fDebug && GetBoolArg("-printcoinage"))
2098 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2102 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2104 // Check for duplicate
2105 uint256 hash = GetHash();
2106 if (mapBlockIndex.count(hash))
2107 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2109 // Construct new block index object
2110 CBlockIndex* pindexNew = new(nothrow) CBlockIndex(nFile, nBlockPos, *this);
2112 return error("AddToBlockIndex() : new CBlockIndex failed");
2113 pindexNew->phashBlock = &hash;
2114 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2115 if (miPrev != mapBlockIndex.end())
2117 pindexNew->pprev = (*miPrev).second;
2118 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2121 // ppcoin: compute chain trust score
2122 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2124 // ppcoin: compute stake entropy bit for stake modifier
2125 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2126 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2128 // ppcoin: record proof-of-stake hash value
2129 if (pindexNew->IsProofOfStake())
2131 if (!mapProofOfStake.count(hash))
2132 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2133 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2136 // ppcoin: compute stake modifier
2137 uint64_t nStakeModifier = 0;
2138 bool fGeneratedStakeModifier = false;
2139 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2140 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2141 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2142 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2143 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2144 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2146 // Add to mapBlockIndex
2147 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2148 if (pindexNew->IsProofOfStake())
2149 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2150 pindexNew->phashBlock = &((*mi).first);
2152 // Write to disk block index
2154 if (!txdb.TxnBegin())
2156 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2157 if (!txdb.TxnCommit())
2161 if (pindexNew->nChainTrust > nBestChainTrust)
2162 if (!SetBestChain(txdb, pindexNew))
2165 if (pindexNew == pindexBest)
2167 // Notify UI to display prev block's coinbase if it was ours
2168 static uint256 hashPrevBestCoinBase;
2169 UpdatedTransaction(hashPrevBestCoinBase);
2170 hashPrevBestCoinBase = vtx[0].GetHash();
2173 static int8_t counter = 0;
2174 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2175 uiInterface.NotifyBlocksChanged();
2182 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2184 // These are checks that are independent of context
2185 // that can be verified before saving an orphan block.
2187 set<uint256> uniqueTx; // tx hashes
2188 unsigned int nSigOps = 0; // total sigops
2191 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2192 return DoS(100, error("CheckBlock() : size limits failed"));
2194 bool fProofOfStake = IsProofOfStake();
2196 // First transaction must be coinbase, the rest must not be
2197 if (!vtx[0].IsCoinBase())
2198 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2200 if (!vtx[0].CheckTransaction())
2201 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2203 uniqueTx.insert(vtx[0].GetHash());
2204 nSigOps += vtx[0].GetLegacySigOpCount();
2208 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2209 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2211 // nNonce must be zero for proof-of-stake blocks
2213 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2215 // Coinbase output should be empty if proof-of-stake block
2216 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2217 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2219 // Check coinstake timestamp
2220 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2221 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2223 // NovaCoin: check proof-of-stake block signature
2224 if (fCheckSig && !CheckBlockSignature())
2225 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2227 if (!vtx[1].CheckTransaction())
2228 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2230 uniqueTx.insert(vtx[1].GetHash());
2231 nSigOps += vtx[1].GetLegacySigOpCount();
2235 // Check proof of work matches claimed amount
2236 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2237 return DoS(50, error("CheckBlock() : proof of work failed"));
2240 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2241 return error("CheckBlock() : block timestamp too far in the future");
2243 // Check coinbase timestamp
2244 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2245 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2248 // Iterate all transactions starting from second for proof-of-stake block
2249 // or first for proof-of-work block
2250 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2252 const CTransaction& tx = vtx[i];
2254 // Reject coinbase transactions at non-zero index
2255 if (tx.IsCoinBase())
2256 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2258 // Reject coinstake transactions at index != 1
2259 if (tx.IsCoinStake())
2260 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2262 // Check transaction timestamp
2263 if (GetBlockTime() < (int64_t)tx.nTime)
2264 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2266 // Check transaction consistency
2267 if (!tx.CheckTransaction())
2268 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2270 // Add transaction hash into list of unique transaction IDs
2271 uniqueTx.insert(tx.GetHash());
2273 // Calculate sigops count
2274 nSigOps += tx.GetLegacySigOpCount();
2277 // Check for duplicate txids. This is caught by ConnectInputs(),
2278 // but catching it earlier avoids a potential DoS attack:
2279 if (uniqueTx.size() != vtx.size())
2280 return DoS(100, error("CheckBlock() : duplicate transaction"));
2282 // Reject block if validation would consume too much resources.
2283 if (nSigOps > MAX_BLOCK_SIGOPS)
2284 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2286 // Check merkle root
2287 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2288 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2293 bool CBlock::AcceptBlock()
2295 // Check for duplicate
2296 uint256 hash = GetHash();
2297 if (mapBlockIndex.count(hash))
2298 return error("AcceptBlock() : block already in mapBlockIndex");
2300 // Get prev block index
2301 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2302 if (mi == mapBlockIndex.end())
2303 return DoS(10, error("AcceptBlock() : prev block not found"));
2304 CBlockIndex* pindexPrev = (*mi).second;
2305 int nHeight = pindexPrev->nHeight+1;
2307 // Check proof-of-work or proof-of-stake
2308 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2309 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2311 int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
2312 int nMaxOffset = 12 * nOneHour; // 12 hours
2313 if (fTestNet || pindexPrev->nTime < 1450569600)
2314 nMaxOffset = 7 * nOneWeek; // One week (permanently on testNet or until 20 Dec, 2015 on mainNet)
2316 // Check timestamp against prev
2317 if (GetBlockTime() <= nMedianTimePast || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2318 return error("AcceptBlock() : block's timestamp is too early");
2320 // Don't accept blocks with future timestamps
2321 if (pindexPrev->nHeight > 1 && nMedianTimePast + nMaxOffset < GetBlockTime())
2322 return error("AcceptBlock() : block's timestamp is too far in the future");
2324 // Check that all transactions are finalized
2325 for (const CTransaction& tx : vtx)
2326 if (!tx.IsFinal(nHeight, GetBlockTime()))
2327 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2329 // Check that the block chain matches the known block chain up to a checkpoint
2330 if (!Checkpoints::CheckHardened(nHeight, hash))
2331 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2333 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2335 // Check that the block satisfies synchronized checkpoint
2336 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2337 return error("AcceptBlock() : rejected by synchronized checkpoint");
2339 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2340 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2342 // Enforce rule that the coinbase starts with serialized block height
2343 CScript expect = CScript() << nHeight;
2344 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2345 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2346 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2348 // Write block to history file
2349 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2350 return error("AcceptBlock() : out of disk space");
2351 unsigned int nFile = std::numeric_limits<unsigned int>::max();
2352 unsigned int nBlockPos = 0;
2353 if (!WriteToDisk(nFile, nBlockPos))
2354 return error("AcceptBlock() : WriteToDisk failed");
2355 if (!AddToBlockIndex(nFile, nBlockPos))
2356 return error("AcceptBlock() : AddToBlockIndex failed");
2358 // Relay inventory, but don't relay old inventory during initial block download
2359 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2360 if (hashBestChain == hash)
2363 for (CNode* pnode : vNodes)
2364 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2365 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2368 // ppcoin: check pending sync-checkpoint
2369 Checkpoints::AcceptPendingSyncCheckpoint();
2374 uint256 CBlockIndex::GetBlockTrust() const
2377 bnTarget.SetCompact(nBits);
2382 // Return 1 for the first 12 blocks
2383 if (pprev == NULL || pprev->nHeight < 12)
2386 const CBlockIndex* currentIndex = pprev;
2388 if(IsProofOfStake())
2390 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2392 // Return 1/3 of score if parent block is not the PoW block
2393 if (!pprev->IsProofOfWork())
2394 return (bnNewTrust / 3).getuint256();
2398 // Check last 12 blocks type
2399 while (pprev->nHeight - currentIndex->nHeight < 12)
2401 if (currentIndex->IsProofOfWork())
2403 currentIndex = currentIndex->pprev;
2406 // Return 1/3 of score if less than 3 PoW blocks found
2408 return (bnNewTrust / 3).getuint256();
2410 return bnNewTrust.getuint256();
2414 // Calculate work amount for block
2415 CBigNum bnPoWTrust = CBigNum(nPoWBase) / (bnTarget+1);
2417 // Set nPowTrust to 1 if PoW difficulty is too low
2421 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2423 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2424 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2425 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2429 // Check last 12 blocks type
2430 while (pprev->nHeight - currentIndex->nHeight < 12)
2432 if (currentIndex->IsProofOfStake())
2434 currentIndex = currentIndex->pprev;
2437 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2439 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2441 bnTarget.SetCompact(pprev->nBits);
2446 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2448 // Return nPoWTrust + full trust score for previous block nBits
2449 return (bnPoWTrust + bnNewTrust).getuint256();
2453 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2455 unsigned int nFound = 0;
2456 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2458 if (pstart->nVersion >= minVersion)
2460 pstart = pstart->pprev;
2462 return (nFound >= nRequired);
2465 bool static ReserealizeBlockSignature(CBlock* pblock)
2467 if (pblock->IsProofOfWork())
2469 pblock->vchBlockSig.clear();
2473 return CPubKey::ReserealizeSignature(pblock->vchBlockSig);
2476 bool static IsCanonicalBlockSignature(CBlock* pblock)
2478 if (pblock->IsProofOfWork())
2479 return pblock->vchBlockSig.empty();
2481 return IsDERSignature(pblock->vchBlockSig);
2484 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2486 // Check for duplicate
2487 uint256 hash = pblock->GetHash();
2488 if (mapBlockIndex.count(hash))
2489 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2490 if (mapOrphanBlocks.count(hash))
2491 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2493 // Check that block isn't listed as unconditionally banned.
2494 if (!Checkpoints::CheckBanned(hash)) {
2496 pfrom->Misbehaving(100);
2497 return error("ProcessBlock() : block %s is rejected by hard-coded banlist", hash.GetHex().substr(0,20).c_str());
2500 // Check proof-of-stake
2501 // Limited duplicity on stake: prevents block flood attack
2502 // Duplicate stake allowed only when there is orphan child block
2503 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2504 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());
2506 // Strip the garbage from newly received blocks, if we found some
2507 if (!IsCanonicalBlockSignature(pblock)) {
2508 if (!ReserealizeBlockSignature(pblock))
2509 printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2512 // Preliminary checks
2513 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2514 return error("ProcessBlock() : CheckBlock FAILED");
2516 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2517 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2519 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2520 int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2522 bnNewBlock.SetCompact(pblock->nBits);
2525 if (pblock->IsProofOfStake())
2526 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2528 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2530 if (bnNewBlock > bnRequired)
2533 pfrom->Misbehaving(100);
2534 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2539 // ppcoin: ask for pending sync-checkpoint if any
2540 if (!IsInitialBlockDownload())
2541 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2543 // If don't already have its previous block, shunt it off to holding area until we get it
2544 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2546 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2547 // ppcoin: check proof-of-stake
2548 if (pblock->IsProofOfStake())
2550 // Limited duplicity on stake: prevents block flood attack
2551 // Duplicate stake allowed only when there is orphan child block
2552 if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2553 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());
2555 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2557 CBlock* pblock2 = new CBlock(*pblock);
2558 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2559 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2561 // Ask this guy to fill in what we're missing
2564 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2565 // ppcoin: getblocks may not obtain the ancestor block rejected
2566 // earlier by duplicate-stake check so we ask for it again directly
2567 if (!IsInitialBlockDownload())
2568 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2573 // ppcoin: verify hash target and signature of coinstake tx
2574 if (pblock->IsProofOfStake())
2576 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2577 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2579 // Having prev block in index should be enough for validation
2580 if (mapBlockIndex.count(pblock->hashPrevBlock))
2581 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());
2583 // Orphan blocks should be validated later once all parents successfully added to local chain
2584 printf("ProcessBlock(): delaying proof-of-stake validation for orphan block %s\n", hash.ToString().c_str());
2585 return false; // do not error here as we expect this to happen here
2588 // Needed for AcceptBlock()
2589 if (!mapProofOfStake.count(hash))
2590 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2594 if (!pblock->AcceptBlock())
2595 return error("ProcessBlock() : AcceptBlock FAILED");
2597 // Process any orphan blocks that depended on this one
2598 vector<uint256> vWorkQueue;
2599 vWorkQueue.push_back(hash);
2600 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2602 uint256 hashPrev = vWorkQueue[i];
2603 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2604 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2607 CBlock* pblockOrphan = (*mi).second;
2608 uint256 hashOrphanBlock = pblockOrphan->GetHash();
2610 if (pblockOrphan->IsProofOfStake()) {
2611 // Check proof-of-stake and do other contextual
2612 // preparations before running AcceptBlock()
2613 uint256 hashOrphanProofOfStake = 0;
2614 uint256 targetOrphanProofOfStake = 0;
2616 if (CheckProofOfStake(pblockOrphan->vtx[1], pblockOrphan->nBits, hashOrphanProofOfStake, targetOrphanProofOfStake))
2618 // Needed for AcceptBlock()
2619 if (!mapProofOfStake.count(hashOrphanBlock))
2620 mapProofOfStake.insert(make_pair(hashOrphanBlock, hashOrphanProofOfStake));
2622 // Finally, we're ready to run AcceptBlock()
2623 if (pblockOrphan->AcceptBlock())
2624 vWorkQueue.push_back(hashOrphanBlock);
2625 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2628 // proof-of-work verification
2629 // is notoriously simpler
2630 if (pblockOrphan->AcceptBlock())
2631 vWorkQueue.push_back(hashOrphanBlock);
2634 mapOrphanBlocks.erase(hashOrphanBlock);
2635 delete pblockOrphan;
2638 mapOrphanBlocksByPrev.erase(hashPrev);
2641 printf("ProcessBlock: ACCEPTED\n");
2643 // ppcoin: if responsible for sync-checkpoint send it
2644 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2645 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2650 // ppcoin: check block signature
2651 bool CBlock::CheckBlockSignature() const
2653 if (vchBlockSig.empty())
2656 txnouttype whichType;
2657 vector<valtype> vSolutions;
2658 if (!Solver(vtx[1].vout[1].scriptPubKey, whichType, vSolutions))
2661 if (whichType == TX_PUBKEY)
2663 valtype& vchPubKey = vSolutions[0];
2664 CPubKey key(vchPubKey);
2667 return key.Verify(GetHash(), vchBlockSig);
2673 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2675 uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available;
2677 // Check for nMinDiskSpace bytes (currently 50MB)
2678 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2681 string strMessage = _("Warning: Disk space is low!");
2682 strMiscWarning = strMessage;
2683 printf("*** %s\n", strMessage.c_str());
2684 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2691 static boost::filesystem::path BlockFilePath(unsigned int nFile)
2693 string strBlockFn = strprintf("blk%04u.dat", nFile);
2694 return GetDataDir() / strBlockFn;
2697 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2699 if ((nFile < 1) || (nFile == std::numeric_limits<uint32_t>::max()))
2701 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2704 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2706 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2715 static unsigned int nCurrentBlockFile = 1;
2717 FILE* AppendBlockFile(unsigned int& nFileRet)
2722 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2725 if (fseek(file, 0, SEEK_END) != 0)
2727 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2728 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2730 nFileRet = nCurrentBlockFile;
2734 nCurrentBlockFile++;
2738 void UnloadBlockIndex()
2740 mapBlockIndex.clear();
2741 setStakeSeen.clear();
2742 pindexGenesisBlock = NULL;
2744 nBestChainTrust = 0;
2745 nBestInvalidTrust = 0;
2750 bool LoadBlockIndex(bool fAllowNew)
2754 pchMessageStart[0] = 0xcd;
2755 pchMessageStart[1] = 0xf2;
2756 pchMessageStart[2] = 0xc0;
2757 pchMessageStart[3] = 0xef;
2759 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2760 nStakeMinAge = 2 * nOneHour; // test net min age is 2 hours
2761 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2762 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2763 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2770 if (!txdb.LoadBlockIndex())
2774 // Init with genesis block
2776 if (mapBlockIndex.empty())
2785 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2786 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2787 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2789 // vMerkleTree: 4cb33b3b6a
2793 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2794 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2795 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2797 // vMerkleTree: 4cb33b3b6a
2799 const string strTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2801 txNew.nTime = 1360105017;
2802 txNew.vin.resize(1);
2803 txNew.vout.resize(1);
2804 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>(strTimestamp.begin(), strTimestamp.end());
2805 txNew.vout[0].SetEmpty();
2807 block.vtx.push_back(txNew);
2808 block.hashPrevBlock = 0;
2809 block.hashMerkleRoot = block.BuildMerkleTree();
2811 block.nTime = 1360105017;
2812 block.nBits = bnProofOfWorkLimit.GetCompact();
2813 block.nNonce = !fTestNet ? 1575379 : 46534;
2816 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2818 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2819 assert(block.CheckBlock());
2821 // Start new block file
2823 unsigned int nBlockPos;
2824 if (!block.WriteToDisk(nFile, nBlockPos))
2825 return error("LoadBlockIndex() : writing genesis block to disk failed");
2826 if (!block.AddToBlockIndex(nFile, nBlockPos))
2827 return error("LoadBlockIndex() : genesis block not accepted");
2829 // initialize synchronized checkpoint
2830 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2831 return error("LoadBlockIndex() : failed to init sync checkpoint");
2833 // upgrade time set to zero if txdb initialized
2835 if (!txdb.WriteModifierUpgradeTime(0))
2836 return error("LoadBlockIndex() : failed to init upgrade info");
2837 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2843 string strPubKey = "";
2844 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2846 // write checkpoint master key to db
2848 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2849 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2850 if (!txdb.TxnCommit())
2851 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2852 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2853 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2856 // upgrade time set to zero if blocktreedb initialized
2857 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2859 if (nModifierUpgradeTime)
2860 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2862 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2866 nModifierUpgradeTime = GetTime();
2867 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2868 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2869 return error("LoadBlockIndex() : failed to write upgrade info");
2878 void PrintBlockTree()
2880 // pre-compute tree structure
2881 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2882 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2884 CBlockIndex* pindex = (*mi).second;
2885 mapNext[pindex->pprev].push_back(pindex);
2887 //while (rand() % 3 == 0)
2888 // mapNext[pindex->pprev].push_back(pindex);
2891 vector<pair<int, CBlockIndex*> > vStack;
2892 vStack.push_back(make_pair(0, pindexGenesisBlock));
2895 while (!vStack.empty())
2897 int nCol = vStack.back().first;
2898 CBlockIndex* pindex = vStack.back().second;
2901 // print split or gap
2902 if (nCol > nPrevCol)
2904 for (int i = 0; i < nCol-1; i++)
2908 else if (nCol < nPrevCol)
2910 for (int i = 0; i < nCol; i++)
2917 for (int i = 0; i < nCol; i++)
2922 block.ReadFromDisk(pindex);
2923 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
2927 block.GetHash().ToString().c_str(),
2929 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2930 FormatMoney(pindex->nMint).c_str(),
2933 PrintWallets(block);
2935 // put the main time-chain first
2936 vector<CBlockIndex*>& vNext = mapNext[pindex];
2937 for (unsigned int i = 0; i < vNext.size(); i++)
2939 if (vNext[i]->pnext)
2941 swap(vNext[0], vNext[i]);
2947 for (unsigned int i = 0; i < vNext.size(); i++)
2948 vStack.push_back(make_pair(nCol+i, vNext[i]));
2952 bool LoadExternalBlockFile(FILE* fileIn)
2954 int64_t nStart = GetTimeMillis();
2960 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2961 unsigned int nPos = 0;
2962 while (nPos != std::numeric_limits<uint32_t>::max() && blkdat.good() && !fRequestShutdown)
2964 unsigned char pchData[65536];
2966 fseek(blkdat, nPos, SEEK_SET);
2967 size_t nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2970 nPos = std::numeric_limits<uint32_t>::max();
2973 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2976 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2978 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2981 nPos += ((unsigned char*)nFind - pchData) + 1;
2984 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2985 } while(!fRequestShutdown);
2986 if (nPos == std::numeric_limits<uint32_t>::max())
2988 fseek(blkdat, nPos, SEEK_SET);
2991 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2995 if (ProcessBlock(NULL,&block))
3003 catch (const std::exception&) {
3004 printf("%s() : Deserialize or I/O error caught during load\n",
3005 BOOST_CURRENT_FUNCTION);
3008 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3012 //////////////////////////////////////////////////////////////////////////////
3017 extern map<uint256, CAlert> mapAlerts;
3018 extern CCriticalSection cs_mapAlerts;
3020 string GetWarnings(string strFor)
3023 string strStatusBar;
3026 if (GetBoolArg("-testsafemode"))
3029 // Misc warnings like out of disk space and clock is wrong
3030 if (!strMiscWarning.empty())
3033 strStatusBar = strMiscWarning;
3036 // if detected unmet upgrade requirement enter safe mode
3037 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3038 if (IsFixedModifierInterval(nModifierUpgradeTime + nOneDay)) // 1 day margin
3041 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3044 // if detected invalid checkpoint enter safe mode
3045 if (Checkpoints::hashInvalidCheckpoint != 0)
3048 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3054 for (auto& item : mapAlerts)
3056 const CAlert& alert = item.second;
3057 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3059 nPriority = alert.nPriority;
3060 strStatusBar = alert.strStatusBar;
3061 if (nPriority > 1000)
3062 strRPC = strStatusBar;
3067 if (strFor == "statusbar")
3068 return strStatusBar;
3069 else if (strFor == "rpc")
3071 assert(!"GetWarnings() : invalid parameter");
3082 //////////////////////////////////////////////////////////////////////////////
3088 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3094 bool txInMap = false;
3097 txInMap = (mempool.exists(inv.hash));
3100 mapOrphanTransactions.count(inv.hash) ||
3101 txdb.ContainsTx(inv.hash);
3105 return mapBlockIndex.count(inv.hash) ||
3106 mapOrphanBlocks.count(inv.hash);
3108 // Don't know what it is, just say we already got one
3115 // The message start string is designed to be unlikely to occur in normal data.
3116 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3117 // a large 4-byte int at any alignment.
3118 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3120 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3122 RandAddSeedPerfmon();
3124 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3125 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3127 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3131 if (strCommand == "version")
3133 // Each connection can only send one version message
3134 if (pfrom->nVersion != 0)
3136 pfrom->Misbehaving(1);
3143 uint64_t nNonce = 1;
3144 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3145 if (pfrom->nVersion < MIN_PROTO_VERSION)
3147 // Since February 20, 2012, the protocol is initiated at version 209,
3148 // and earlier versions are no longer supported
3149 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3150 pfrom->fDisconnect = true;
3154 if (pfrom->nVersion == 10300)
3155 pfrom->nVersion = 300;
3157 vRecv >> addrFrom >> nNonce;
3159 vRecv >> pfrom->strSubVer;
3161 vRecv >> pfrom->nStartingHeight;
3163 if (pfrom->fInbound && addrMe.IsRoutable())
3165 pfrom->addrLocal = addrMe;
3169 // Disconnect if we connected to ourself
3170 if (nNonce == nLocalHostNonce && nNonce > 1)
3172 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3173 pfrom->fDisconnect = true;
3177 if (pfrom->nVersion < 60010)
3179 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3180 pfrom->fDisconnect = true;
3184 // record my external IP reported by peer
3185 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3186 addrSeenByPeer = addrMe;
3188 // Be shy and don't send version until we hear
3189 if (pfrom->fInbound)
3190 pfrom->PushVersion();
3192 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3194 AddTimeData(pfrom->addr, nTime);
3197 pfrom->PushMessage("verack");
3198 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3200 if (!pfrom->fInbound)
3202 // Advertise our address
3203 if (!fNoListen && !IsInitialBlockDownload())
3205 CAddress addr = GetLocalAddress(&pfrom->addr);
3206 if (addr.IsRoutable())
3207 pfrom->PushAddress(addr);
3210 // Get recent addresses
3211 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3213 pfrom->PushMessage("getaddr");
3214 pfrom->fGetAddr = true;
3216 addrman.Good(pfrom->addr);
3218 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3220 addrman.Add(addrFrom, addrFrom);
3221 addrman.Good(addrFrom);
3225 // Ask the first connected node for block updates
3226 static int nAskedForBlocks = 0;
3227 if (!pfrom->fClient && !pfrom->fOneShot &&
3228 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3229 (pfrom->nVersion < NOBLKS_VERSION_START ||
3230 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3231 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3234 pfrom->PushGetBlocks(pindexBest, uint256(0));
3240 for (auto& item : mapAlerts)
3241 item.second.RelayTo(pfrom);
3244 // Relay sync-checkpoint
3246 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3247 if (!Checkpoints::checkpointMessage.IsNull())
3248 Checkpoints::checkpointMessage.RelayTo(pfrom);
3251 pfrom->fSuccessfullyConnected = true;
3253 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());
3255 cPeerBlockCounts.input(pfrom->nStartingHeight);
3257 // ppcoin: ask for pending sync-checkpoint if any
3258 if (!IsInitialBlockDownload())
3259 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3263 else if (pfrom->nVersion == 0)
3265 // Must have a version message before anything else
3266 pfrom->Misbehaving(1);
3271 else if (strCommand == "verack")
3273 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3277 else if (strCommand == "addr")
3279 vector<CAddress> vAddr;
3282 // Don't want addr from older versions unless seeding
3283 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3285 if (vAddr.size() > 1000)
3287 pfrom->Misbehaving(20);
3288 return error("message addr size() = %" PRIszu "", vAddr.size());
3291 // Store the new addresses
3292 vector<CAddress> vAddrOk;
3293 int64_t nNow = GetAdjustedTime();
3294 int64_t nSince = nNow - 10 * 60;
3295 for (CAddress& addr : vAddr)
3299 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3300 addr.nTime = nNow - 5 * nOneDay;
3301 pfrom->AddAddressKnown(addr);
3302 bool fReachable = IsReachable(addr);
3303 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3305 // Relay to a limited number of other nodes
3308 // Use deterministic randomness to send to the same nodes for 24 hours
3309 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3310 static uint256 hashSalt;
3312 hashSalt = GetRandHash();
3313 uint64_t hashAddr = addr.GetHash();
3314 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/nOneDay);
3315 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3316 multimap<uint256, CNode*> mapMix;
3317 for (CNode* pnode : vNodes)
3319 if (pnode->nVersion < CADDR_TIME_VERSION)
3321 unsigned int nPointer;
3322 memcpy(&nPointer, &pnode, sizeof(nPointer));
3323 uint256 hashKey = hashRand ^ nPointer;
3324 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3325 mapMix.insert(make_pair(hashKey, pnode));
3327 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3328 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3329 ((*mi).second)->PushAddress(addr);
3332 // Do not store addresses outside our network
3334 vAddrOk.push_back(addr);
3336 addrman.Add(vAddrOk, pfrom->addr, 2 * nOneHour);
3337 if (vAddr.size() < 1000)
3338 pfrom->fGetAddr = false;
3339 if (pfrom->fOneShot)
3340 pfrom->fDisconnect = true;
3343 else if (strCommand == "inv")
3347 if (vInv.size() > MAX_INV_SZ)
3349 pfrom->Misbehaving(20);
3350 return error("message inv size() = %" PRIszu "", vInv.size());
3353 // find last block in inv vector
3354 size_t nLastBlock = std::numeric_limits<size_t>::max();
3355 for (size_t nInv = 0; nInv < vInv.size(); nInv++) {
3356 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3357 nLastBlock = vInv.size() - 1 - nInv;
3362 for (size_t nInv = 0; nInv < vInv.size(); nInv++)
3364 const CInv &inv = vInv[nInv];
3368 pfrom->AddInventoryKnown(inv);
3370 bool fAlreadyHave = AlreadyHave(txdb, inv);
3372 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3376 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3377 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3378 } else if (nInv == nLastBlock) {
3379 // In case we are on a very long side-chain, it is possible that we already have
3380 // the last block in an inv bundle sent in response to getblocks. Try to detect
3381 // this situation and push another getblocks to continue.
3382 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3384 printf("force request: %s\n", inv.ToString().c_str());
3387 // Track requests for our stuff
3388 Inventory(inv.hash);
3393 else if (strCommand == "getdata")
3397 if (vInv.size() > MAX_INV_SZ)
3399 pfrom->Misbehaving(20);
3400 return error("message getdata size() = %" PRIszu "", vInv.size());
3403 if (fDebugNet || (vInv.size() != 1))
3404 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3406 for (const CInv& inv : vInv)
3410 if (fDebugNet || (vInv.size() == 1))
3411 printf("received getdata for: %s\n", inv.ToString().c_str());
3413 if (inv.type == MSG_BLOCK)
3415 // Send block from disk
3416 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3417 if (mi != mapBlockIndex.end())
3420 block.ReadFromDisk((*mi).second);
3421 pfrom->PushMessage("block", block);
3423 // Trigger them to send a getblocks request for the next batch of inventory
3424 if (inv.hash == pfrom->hashContinue)
3426 // ppcoin: send latest proof-of-work block to allow the
3427 // download node to accept as orphan (proof-of-stake
3428 // block might be rejected by stake connection check)
3430 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3431 pfrom->PushMessage("inv", vInv);
3432 pfrom->hashContinue = 0;
3436 else if (inv.IsKnownType())
3438 // Send stream from relay memory
3439 bool pushed = false;
3442 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3443 if (mi != mapRelay.end()) {
3444 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3448 if (!pushed && inv.type == MSG_TX) {
3450 if (mempool.exists(inv.hash)) {
3451 CTransaction tx = mempool.lookup(inv.hash);
3452 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3455 pfrom->PushMessage("tx", ss);
3460 // Track requests for our stuff
3461 Inventory(inv.hash);
3466 else if (strCommand == "getblocks")
3468 CBlockLocator locator;
3470 vRecv >> locator >> hashStop;
3472 // Find the last block the caller has in the main chain
3473 CBlockIndex* pindex = locator.GetBlockIndex();
3475 // Send the rest of the chain
3477 pindex = pindex->pnext;
3479 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3480 for (; pindex; pindex = pindex->pnext)
3482 if (pindex->GetBlockHash() == hashStop)
3484 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3485 // ppcoin: tell downloading node about the latest block if it's
3486 // without risk being rejected due to stake connection check
3487 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3488 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3491 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3494 // When this block is requested, we'll send an inv that'll make them
3495 // getblocks the next batch of inventory.
3496 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3497 pfrom->hashContinue = pindex->GetBlockHash();
3502 else if (strCommand == "checkpoint")
3504 CSyncCheckpoint checkpoint;
3505 vRecv >> checkpoint;
3507 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3510 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3512 for (CNode* pnode : vNodes)
3513 checkpoint.RelayTo(pnode);
3517 else if (strCommand == "getheaders")
3519 CBlockLocator locator;
3521 vRecv >> locator >> hashStop;
3523 CBlockIndex* pindex = NULL;
3524 if (locator.IsNull())
3526 // If locator is null, return the hashStop block
3527 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3528 if (mi == mapBlockIndex.end())
3530 pindex = (*mi).second;
3534 // Find the last block the caller has in the main chain
3535 pindex = locator.GetBlockIndex();
3537 pindex = pindex->pnext;
3540 vector<CBlock> vHeaders;
3542 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3543 for (; pindex; pindex = pindex->pnext)
3545 vHeaders.push_back(pindex->GetBlockHeader());
3546 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3549 pfrom->PushMessage("headers", vHeaders);
3553 else if (strCommand == "tx")
3555 vector<uint256> vWorkQueue;
3556 vector<uint256> vEraseQueue;
3557 CDataStream vMsg(vRecv);
3562 CInv inv(MSG_TX, tx.GetHash());
3563 pfrom->AddInventoryKnown(inv);
3565 bool fMissingInputs = false;
3566 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3568 SyncWithWallets(tx, NULL, true);
3569 RelayTransaction(tx, inv.hash);
3570 mapAlreadyAskedFor.erase(inv);
3571 vWorkQueue.push_back(inv.hash);
3572 vEraseQueue.push_back(inv.hash);
3574 // Recursively process any orphan transactions that depended on this one
3575 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3577 uint256 hashPrev = vWorkQueue[i];
3578 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3579 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3582 const uint256& orphanTxHash = *mi;
3583 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3584 bool fMissingInputs2 = false;
3586 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3588 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3589 SyncWithWallets(tx, NULL, true);
3590 RelayTransaction(orphanTx, orphanTxHash);
3591 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3592 vWorkQueue.push_back(orphanTxHash);
3593 vEraseQueue.push_back(orphanTxHash);
3595 else if (!fMissingInputs2)
3598 vEraseQueue.push_back(orphanTxHash);
3599 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3604 for (uint256 hash : vEraseQueue)
3605 EraseOrphanTx(hash);
3607 else if (fMissingInputs)
3611 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3612 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3614 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3616 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3620 else if (strCommand == "block")
3624 uint256 hashBlock = block.GetHash();
3626 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3629 CInv inv(MSG_BLOCK, hashBlock);
3630 pfrom->AddInventoryKnown(inv);
3632 if (ProcessBlock(pfrom, &block))
3633 mapAlreadyAskedFor.erase(inv);
3634 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3638 // This asymmetric behavior for inbound and outbound connections was introduced
3639 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
3640 // to users' AddrMan and later request them by sending getaddr messages.
3641 // Making users (which are behind NAT and can only make outgoing connections) ignore
3642 // getaddr message mitigates the attack.
3643 else if ((strCommand == "getaddr") && (pfrom->fInbound))
3645 // Don't return addresses older than nCutOff timestamp
3646 int64_t nCutOff = GetTime() - (nNodeLifespan * nOneDay);
3647 pfrom->vAddrToSend.clear();
3648 vector<CAddress> vAddr = addrman.GetAddr();
3649 for (const CAddress &addr : vAddr)
3650 if(addr.nTime > nCutOff)
3651 pfrom->PushAddress(addr);
3655 else if (strCommand == "mempool")
3657 std::vector<uint256> vtxid;
3658 mempool.queryHashes(vtxid);
3660 for (unsigned int i = 0; i < vtxid.size(); i++) {
3661 CInv inv(MSG_TX, vtxid[i]);
3662 vInv.push_back(inv);
3663 if (i == (MAX_INV_SZ - 1))
3666 if (vInv.size() > 0)
3667 pfrom->PushMessage("inv", vInv);
3671 else if (strCommand == "ping")
3675 // Echo the message back with the nonce. This allows for two useful features:
3677 // 1) A remote node can quickly check if the connection is operational
3678 // 2) Remote nodes can measure the latency of the network thread. If this node
3679 // is overloaded it won't respond to pings quickly and the remote node can
3680 // avoid sending us more work, like chain download requests.
3682 // The nonce stops the remote getting confused between different pings: without
3683 // it, if the remote node sends a ping once per second and this node takes 5
3684 // seconds to respond to each, the 5th ping the remote sends would appear to
3685 // return very quickly.
3686 pfrom->PushMessage("pong", nonce);
3690 else if (strCommand == "alert")
3695 uint256 alertHash = alert.GetHash();
3696 if (pfrom->setKnown.count(alertHash) == 0)
3698 if (alert.ProcessAlert())
3701 pfrom->setKnown.insert(alertHash);
3704 for (CNode* pnode : vNodes)
3705 alert.RelayTo(pnode);
3709 // Small DoS penalty so peers that send us lots of
3710 // duplicate/expired/invalid-signature/whatever alerts
3711 // eventually get banned.
3712 // This isn't a Misbehaving(100) (immediate ban) because the
3713 // peer might be an older or different implementation with
3714 // a different signature key, etc.
3715 pfrom->Misbehaving(10);
3723 // Ignore unknown commands for extensibility
3727 // Update the last seen time for this node's address
3728 if (pfrom->fNetworkNode)
3729 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3730 AddressCurrentlyConnected(pfrom->addr);
3736 bool ProcessMessages(CNode* pfrom)
3738 CDataStream& vRecv = pfrom->vRecv;
3742 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3746 // (4) message start
3755 // Don't bother if send buffer is too full to respond anyway
3756 if (pfrom->vSend.size() >= SendBufferSize())
3759 // Scan for message start
3760 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3761 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3762 if (vRecv.end() - pstart < nHeaderSize)
3764 if ((int)vRecv.size() > nHeaderSize)
3766 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3767 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3771 if (pstart - vRecv.begin() > 0)
3772 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
3773 vRecv.erase(vRecv.begin(), pstart);
3776 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3781 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3784 string strCommand = hdr.GetCommand();
3787 unsigned int nMessageSize = hdr.nMessageSize;
3788 if (nMessageSize > MAX_SIZE)
3790 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3793 if (nMessageSize > vRecv.size())
3795 // Rewind and wait for rest of message
3796 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3801 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3802 unsigned int nChecksum = 0;
3803 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3804 if (nChecksum != hdr.nChecksum)
3806 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3807 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3811 // Copy message to its own buffer
3812 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3813 vRecv.ignore(nMessageSize);
3821 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3826 catch (std::ios_base::failure& e)
3828 if (strstr(e.what(), "end of data"))
3830 // Allow exceptions from under-length message on vRecv
3831 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());
3833 else if (strstr(e.what(), "size too large"))
3835 // Allow exceptions from over-long size
3836 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3840 PrintExceptionContinue(&e, "ProcessMessages()");
3843 catch (std::exception& e) {
3844 PrintExceptionContinue(&e, "ProcessMessages()");
3846 PrintExceptionContinue(NULL, "ProcessMessages()");
3850 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3860 bool SendMessages(CNode* pto)
3862 TRY_LOCK(cs_main, lockMain);
3864 // Current time in microseconds
3865 int64_t nNow = GetTimeMicros();
3867 // Don't send anything until we get their version message
3868 if (pto->nVersion == 0)
3871 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3873 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
3875 pto->PushMessage("ping", nonce);
3879 if (pto->fStartSync) {
3880 pto->fStartSync = false;
3881 pto->PushGetBlocks(pindexBest, uint256(0));
3884 // Resend wallet transactions that haven't gotten in a block yet
3885 ResendWalletTransactions();
3887 // Address refresh broadcast
3888 if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) {
3889 AdvertiseLocal(pto);
3890 pto->nNextLocalAddrSend = PoissonNextSend(nNow, nOneDay);
3896 if (pto->nNextAddrSend < nNow) {
3897 pto->nNextAddrSend = PoissonNextSend(nNow, 30);
3898 vector<CAddress> vAddr;
3899 vAddr.reserve(pto->vAddrToSend.size());
3900 for (const CAddress& addr : pto->vAddrToSend)
3902 if (pto->setAddrKnown.insert(addr).second)
3904 vAddr.push_back(addr);
3905 // receiver rejects addr messages larger than 1000
3906 if (vAddr.size() >= 1000)
3908 pto->PushMessage("addr", vAddr);
3913 pto->vAddrToSend.clear();
3915 pto->PushMessage("addr", vAddr);
3919 // Message: inventory
3922 vector<CInv> vInvWait;
3924 bool fSendTrickle = false;
3925 if (pto->nNextInvSend < nNow) {
3926 fSendTrickle = true;
3927 pto->nNextInvSend = PoissonNextSend(nNow, 5);
3929 LOCK(pto->cs_inventory);
3930 vInv.reserve(pto->vInventoryToSend.size());
3931 vInvWait.reserve(pto->vInventoryToSend.size());
3932 for (const CInv& inv : pto->vInventoryToSend)
3934 if (pto->setInventoryKnown.count(inv))
3937 // trickle out tx inv to protect privacy
3938 if (inv.type == MSG_TX && !fSendTrickle)
3940 // 1/4 of tx invs blast to all immediately
3941 static uint256 hashSalt;
3943 hashSalt = GetRandHash();
3944 uint256 hashRand = inv.hash ^ hashSalt;
3945 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3946 bool fTrickleWait = ((hashRand & 3) != 0);
3950 vInvWait.push_back(inv);
3955 // returns true if wasn't already contained in the set
3956 if (pto->setInventoryKnown.insert(inv).second)
3958 vInv.push_back(inv);
3959 if (vInv.size() >= 1000)
3961 pto->PushMessage("inv", vInv);
3966 pto->vInventoryToSend = vInvWait;
3969 pto->PushMessage("inv", vInv);
3975 vector<CInv> vGetData;
3977 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3979 const CInv& inv = (*pto->mapAskFor.begin()).second;
3980 if (!AlreadyHave(txdb, inv))
3983 printf("sending getdata: %s\n", inv.ToString().c_str());
3984 vGetData.push_back(inv);
3985 if (vGetData.size() >= 1000)
3987 pto->PushMessage("getdata", vGetData);
3990 mapAlreadyAskedFor[inv] = nNow;
3992 pto->mapAskFor.erase(pto->mapAskFor.begin());
3994 if (!vGetData.empty())
3995 pto->PushMessage("getdata", vGetData);
4008 std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4009 for (; it1 != mapBlockIndex.end(); it1++)
4010 delete (*it1).second;
4011 mapBlockIndex.clear();
4014 std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4015 for (; it2 != mapOrphanBlocks.end(); it2++)
4016 delete (*it2).second;
4017 mapOrphanBlocks.clear();
4019 // orphan transactions
4021 } instance_of_cmaincleanup;