1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
11 #include "ui_interface.h"
12 #include "checkqueue.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
21 using namespace boost;
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
31 unsigned int nTransactionsUpdated = 0;
33 map<uint256, CBlockIndex*> mapBlockIndex;
34 set<pair<COutPoint, unsigned int> > setStakeSeen;
36 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
37 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
38 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
39 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
40 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
42 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
44 unsigned int nStakeMinAge = 30 * nOneDay; // 30 days as zero time weight
45 unsigned int nStakeMaxAge = 90 * nOneDay; // 90 days as full weight
46 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
47 unsigned int nModifierInterval = 6 * nOneHour; // time to elapse before new modifier is computed
49 int nCoinbaseMaturity = 500;
51 CBlockIndex* pindexGenesisBlock = NULL;
54 uint256 nBestChainTrust = 0;
55 uint256 nBestInvalidTrust = 0;
57 uint256 hashBestChain = 0;
58 CBlockIndex* pindexBest = NULL;
59 int64_t nTimeBestReceived = 0;
60 int nScriptCheckThreads = 0;
62 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
64 map<uint256, CBlock*> mapOrphanBlocks;
65 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
66 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
67 map<uint256, uint256> mapProofOfStake;
69 map<uint256, CTransaction> mapOrphanTransactions;
70 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
72 // Constant stuff for coinbase transactions we create:
73 CScript COINBASE_FLAGS;
75 const string strMessageMagic = "NovaCoin Signed Message:\n";
78 int64_t nTransactionFee = MIN_TX_FEE;
79 int64_t nMinimumInputValue = MIN_TXOUT_AMOUNT;
81 // Ping and address broadcast intervals
82 int64_t nPingInterval = 30 * 60;
83 int64_t nBroadcastInterval = nOneDay;
85 extern enum Checkpoints::CPMode CheckpointsMode;
87 //////////////////////////////////////////////////////////////////////////////
89 // dispatching functions
92 // These functions dispatch to one or all registered wallets
95 void RegisterWallet(CWallet* pwalletIn)
98 LOCK(cs_setpwalletRegistered);
99 setpwalletRegistered.insert(pwalletIn);
103 void UnregisterWallet(CWallet* pwalletIn)
106 LOCK(cs_setpwalletRegistered);
107 setpwalletRegistered.erase(pwalletIn);
111 // check whether the passed transaction is from us
112 bool static IsFromMe(CTransaction& tx)
114 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
115 if (pwallet->IsFromMe(tx))
120 // get the wallet transaction with the given hash (if it exists)
121 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
123 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
124 if (pwallet->GetTransaction(hashTx,wtx))
129 // erases transaction with the given hash from all wallets
130 void static EraseFromWallets(uint256 hash)
132 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
133 pwallet->EraseFromWallet(hash);
136 // make sure all wallets know about the given transaction, in the given block
137 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
141 // wallets need to refund inputs when disconnecting coinstake
142 if (tx.IsCoinStake())
144 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
145 if (pwallet->IsFromMe(tx))
146 pwallet->DisableTransaction(tx);
151 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
152 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
155 // notify wallets about a new best chain
156 void static SetBestChain(const CBlockLocator& loc)
158 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
159 pwallet->SetBestChain(loc);
162 // notify wallets about an updated transaction
163 void static UpdatedTransaction(const uint256& hashTx)
165 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
166 pwallet->UpdatedTransaction(hashTx);
170 void static PrintWallets(const CBlock& block)
172 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
173 pwallet->PrintWallet(block);
176 // notify wallets about an incoming inventory (for request counts)
177 void static Inventory(const uint256& hash)
179 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
180 pwallet->Inventory(hash);
183 // ask wallets to resend their transactions
184 void ResendWalletTransactions()
186 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
187 pwallet->ResendWalletTransactions();
196 //////////////////////////////////////////////////////////////////////////////
198 // mapOrphanTransactions
201 bool AddOrphanTx(const CTransaction& tx)
203 uint256 hash = tx.GetHash();
204 if (mapOrphanTransactions.count(hash))
207 // Ignore big transactions, to avoid a
208 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
209 // large transaction with a missing parent then we assume
210 // it will rebroadcast it later, after the parent transaction(s)
211 // have been mined or received.
212 // 10,000 orphans, each of which is at most 5,000 bytes big is
213 // at most 500 megabytes of orphans:
215 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
219 printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
223 mapOrphanTransactions[hash] = tx;
224 BOOST_FOREACH(const CTxIn& txin, tx.vin)
225 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
227 printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
228 mapOrphanTransactions.size());
232 void static EraseOrphanTx(uint256 hash)
234 if (!mapOrphanTransactions.count(hash))
236 const CTransaction& tx = mapOrphanTransactions[hash];
237 BOOST_FOREACH(const CTxIn& txin, tx.vin)
239 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
240 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
241 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
243 mapOrphanTransactions.erase(hash);
246 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
248 unsigned int nEvicted = 0;
249 while (mapOrphanTransactions.size() > nMaxOrphans)
251 // Evict a random orphan:
252 uint256 randomhash = GetRandHash();
253 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
254 if (it == mapOrphanTransactions.end())
255 it = mapOrphanTransactions.begin();
256 EraseOrphanTx(it->first);
268 //////////////////////////////////////////////////////////////////////////////
270 // CTransaction and CTxIndex
273 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
276 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
278 if (!ReadFromDisk(txindexRet.pos))
280 if (prevout.n >= vout.size())
288 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
291 return ReadFromDisk(txdb, prevout, txindex);
294 bool CTransaction::ReadFromDisk(COutPoint prevout)
298 return ReadFromDisk(txdb, prevout, txindex);
301 bool CTransaction::IsStandard(string& strReason) const
303 if (nVersion > CTransaction::CURRENT_VERSION)
305 strReason = "version";
309 unsigned int nDataOut = 0;
310 txnouttype whichType;
311 BOOST_FOREACH(const CTxIn& txin, vin)
313 // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
314 // keys. (remember the 520 byte limit on redeemScript size) That works
315 // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)=1624
316 // bytes of scriptSig, which we round off to 1650 bytes for some minor
317 // future-proofing. That's also enough to spend a 20-of-20
318 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
319 // considered standard)
320 if (txin.scriptSig.size() > 1650)
322 strReason = "scriptsig-size";
325 if (!txin.scriptSig.IsPushOnly())
327 strReason = "scriptsig-not-pushonly";
330 if (!txin.scriptSig.HasCanonicalPushes()) {
331 strReason = "txin-scriptsig-not-canonicalpushes";
335 BOOST_FOREACH(const CTxOut& txout, vout) {
336 if (!::IsStandard(txout.scriptPubKey, whichType)) {
337 strReason = "scriptpubkey";
340 if (whichType == TX_NULL_DATA)
343 if (txout.nValue == 0) {
344 strReason = "txout-value=0";
347 if (!txout.scriptPubKey.HasCanonicalPushes()) {
348 strReason = "txout-scriptsig-not-canonicalpushes";
354 // only one OP_RETURN txout is permitted
356 strReason = "multi-op-return";
364 // Check transaction inputs, and make sure any
365 // pay-to-script-hash transactions are evaluating IsStandard scripts
367 // Why bother? To avoid denial-of-service attacks; an attacker
368 // can submit a standard HASH... OP_EQUAL transaction,
369 // which will get accepted into blocks. The redemption
370 // script can be anything; an attacker could use a very
371 // expensive-to-check-upon-redemption script like:
372 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
374 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
377 return true; // Coinbases don't use vin normally
379 for (unsigned int i = 0; i < vin.size(); i++)
381 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
383 vector<vector<unsigned char> > vSolutions;
384 txnouttype whichType;
385 // get the scriptPubKey corresponding to this input:
386 const CScript& prevScript = prev.scriptPubKey;
387 if (!Solver(prevScript, whichType, vSolutions))
389 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
390 if (nArgsExpected < 0)
393 // Transactions with extra stuff in their scriptSigs are
394 // non-standard. Note that this EvalScript() call will
395 // be quick, because if there are any operations
396 // beside "push data" in the scriptSig the
397 // IsStandard() call returns false
398 vector<vector<unsigned char> > stack;
399 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
402 if (whichType == TX_SCRIPTHASH)
406 CScript subscript(stack.back().begin(), stack.back().end());
407 vector<vector<unsigned char> > vSolutions2;
408 txnouttype whichType2;
409 if (!Solver(subscript, whichType2, vSolutions2))
411 if (whichType2 == TX_SCRIPTHASH)
415 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
418 nArgsExpected += tmpExpected;
421 if (stack.size() != (unsigned int)nArgsExpected)
429 CTransaction::GetLegacySigOpCount() const
431 unsigned int nSigOps = 0;
432 if (!IsCoinBase() || nTime < COINBASE_SIGOPS_SWITCH_TIME)
434 // Coinbase scriptsigs are never executed, so there is
435 // no sense in calculation of sigops.
436 BOOST_FOREACH(const CTxIn& txin, vin)
438 nSigOps += txin.scriptSig.GetSigOpCount(false);
441 BOOST_FOREACH(const CTxOut& txout, vout)
443 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
449 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
461 // Load the block this tx is in
463 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
465 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
470 // Update the tx's hashBlock
471 hashBlock = pblock->GetHash();
473 // Locate the transaction
474 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
475 if (pblock->vtx[nIndex] == *(CTransaction*)this)
477 if (nIndex == (int)pblock->vtx.size())
479 vMerkleBranch.clear();
481 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
485 // Fill in merkle branch
486 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
489 // Is the tx in a block that's in the main chain
490 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
491 if (mi == mapBlockIndex.end())
493 CBlockIndex* pindex = (*mi).second;
494 if (!pindex || !pindex->IsInMainChain())
497 return pindexBest->nHeight - pindex->nHeight + 1;
506 bool CTransaction::CheckTransaction() const
508 // Basic checks that don't depend on any context
510 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
512 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
513 // Time (prevent mempool memory exhaustion attack)
514 // Comes into force since 20 December 2015.
515 if (nTime > 1450569600 && nTime > FutureDrift(GetAdjustedTime()))
516 return DoS(10, error("CTransaction::CheckTransaction() : timestamp is too far into the future"));
518 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
519 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
521 // Check for negative or overflow output values
522 int64_t nValueOut = 0;
523 for (unsigned int i = 0; i < vout.size(); i++)
525 const CTxOut& txout = vout[i];
526 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
527 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
529 if (txout.nValue < 0)
530 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
531 if (txout.nValue > MAX_MONEY)
532 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
533 nValueOut += txout.nValue;
534 if (!MoneyRange(nValueOut))
535 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
538 // Check for duplicate inputs
539 set<COutPoint> vInOutPoints;
540 BOOST_FOREACH(const CTxIn& txin, vin)
542 if (vInOutPoints.count(txin.prevout))
544 vInOutPoints.insert(txin.prevout);
549 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
550 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
554 BOOST_FOREACH(const CTxIn& txin, vin)
555 if (txin.prevout.IsNull())
556 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
562 int64_t CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
564 int64_t nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
568 // Enforce 0.01 as minimum fee for coinstake
570 nMinRelayTxFee = CENT;
573 // Base fee is either nMinTxFee or nMinRelayTxFee
574 int64_t nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
576 unsigned int nNewBlockSize = nBlockSize + nBytes;
577 int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee;
583 // Transactions under 1K are free
589 // Free transaction area
590 if (nNewBlockSize < 27000)
595 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
596 // each non empty output which is less than 0.01
598 // It's safe to ignore empty outputs here, because these inputs are allowed
599 // only for coinbase and coinstake transactions.
600 BOOST_FOREACH(const CTxOut& txout, vout)
601 if (txout.nValue < CENT && !txout.IsEmpty())
604 // Raise the price as the block approaches full
605 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
607 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
609 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
612 if (!MoneyRange(nMinFee))
619 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
620 bool* pfMissingInputs)
623 *pfMissingInputs = false;
625 if (!tx.CheckTransaction())
626 return error("CTxMemPool::accept() : CheckTransaction failed");
628 // Coinbase is only valid in a block, not as a loose transaction
630 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
632 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
633 if (tx.IsCoinStake())
634 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
636 // To help v0.1.5 clients who would see it as a negative number
637 if ((int64_t)tx.nLockTime > std::numeric_limits<int>::max())
638 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
640 // Rather not work on nonstandard transactions (unless -testnet)
642 if (!fTestNet && !tx.IsStandard(strNonStd))
643 return error("CTxMemPool::accept() : nonstandard transaction (%s)", strNonStd.c_str());
645 // Do we already have it?
646 uint256 hash = tx.GetHash();
649 if (mapTx.count(hash))
653 if (txdb.ContainsTx(hash))
656 // Check for conflicts with in-memory transactions
657 CTransaction* ptxOld = NULL;
658 for (unsigned int i = 0; i < tx.vin.size(); i++)
660 COutPoint outpoint = tx.vin[i].prevout;
661 if (mapNextTx.count(outpoint))
663 // Disable replacement feature for now
666 // Allow replacing with a newer version of the same transaction
669 ptxOld = mapNextTx[outpoint].ptx;
670 if (ptxOld->IsFinal())
672 if (!tx.IsNewerThan(*ptxOld))
674 for (unsigned int i = 0; i < tx.vin.size(); i++)
676 COutPoint outpoint = tx.vin[i].prevout;
677 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
687 map<uint256, CTxIndex> mapUnused;
688 bool fInvalid = false;
689 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
692 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
694 *pfMissingInputs = true;
698 // Check for non-standard pay-to-script-hash in inputs
699 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
700 return error("CTxMemPool::accept() : nonstandard transaction input");
702 // Note: if you modify this code to accept non-standard transactions, then
703 // you should add code here to check that the transaction does a
704 // reasonable number of ECDSA signature verifications.
706 int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
707 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
709 // Don't accept it if it can't get into a block
710 int64_t txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
711 if (nFees < txMinFee)
712 return error("CTxMemPool::accept() : not enough fees %s, %" PRId64 " < %" PRId64,
713 hash.ToString().c_str(),
716 // Continuously rate-limit free transactions
717 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
718 // be annoying or make others' transactions take longer to confirm.
719 if (nFees < MIN_RELAY_TX_FEE)
721 static CCriticalSection cs;
722 static double dFreeCount;
723 static int64_t nLastTime;
724 int64_t nNow = GetTime();
728 // Use an exponentially decaying ~10-minute window:
729 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
731 // -limitfreerelay unit is thousand-bytes-per-minute
732 // At default rate it would take over a month to fill 1GB
733 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
734 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
736 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
741 // Check against previous transactions
742 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
743 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, STRICT_FLAGS))
745 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
749 // Store transaction in memory
754 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
757 addUnchecked(hash, tx);
760 ///// are we sure this is ok when loading transactions or restoring block txes
761 // If updated, erase old tx from wallet
763 EraseFromWallets(ptxOld->GetHash());
765 printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
766 hash.ToString().substr(0,10).c_str(),
771 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
773 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
776 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
778 // Add to memory pool without checking anything. Don't call this directly,
779 // call CTxMemPool::accept to properly check the transaction first.
782 for (unsigned int i = 0; i < tx.vin.size(); i++)
783 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
784 nTransactionsUpdated++;
790 bool CTxMemPool::remove(CTransaction &tx)
792 // Remove transaction from memory pool
795 uint256 hash = tx.GetHash();
796 if (mapTx.count(hash))
798 BOOST_FOREACH(const CTxIn& txin, tx.vin)
799 mapNextTx.erase(txin.prevout);
801 nTransactionsUpdated++;
807 void CTxMemPool::clear()
812 ++nTransactionsUpdated;
815 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
820 vtxid.reserve(mapTx.size());
821 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
822 vtxid.push_back((*mi).first);
828 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
830 if (hashBlock == 0 || nIndex == -1)
833 // Find the block it claims to be in
834 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
835 if (mi == mapBlockIndex.end())
837 CBlockIndex* pindex = (*mi).second;
838 if (!pindex || !pindex->IsInMainChain())
841 // Make sure the merkle branch connects to this block
842 if (!fMerkleVerified)
844 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
846 fMerkleVerified = true;
850 return pindexBest->nHeight - pindex->nHeight + 1;
854 int CMerkleTx::GetBlocksToMaturity() const
856 if (!(IsCoinBase() || IsCoinStake()))
858 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
862 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
866 if (!IsInMainChain() && !ClientConnectInputs())
868 return CTransaction::AcceptToMemoryPool(txdb, false);
872 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
876 bool CMerkleTx::AcceptToMemoryPool()
879 return AcceptToMemoryPool(txdb);
884 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
889 // Add previous supporting transactions first
890 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
892 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
894 uint256 hash = tx.GetHash();
895 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
896 tx.AcceptToMemoryPool(txdb, fCheckInputs);
899 return AcceptToMemoryPool(txdb, fCheckInputs);
904 bool CWalletTx::AcceptWalletTransaction()
907 return AcceptWalletTransaction(txdb);
910 int CTxIndex::GetDepthInMainChain() const
914 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
916 // Find the block in the index
917 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
918 if (mi == mapBlockIndex.end())
920 CBlockIndex* pindex = (*mi).second;
921 if (!pindex || !pindex->IsInMainChain())
923 return 1 + nBestHeight - pindex->nHeight;
926 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
927 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
933 if (mempool.exists(hash))
935 tx = mempool.lookup(hash);
941 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
944 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
945 hashBlock = block.GetHash();
959 //////////////////////////////////////////////////////////////////////////////
961 // CBlock and CBlockIndex
964 static CBlockIndex* pblockindexFBBHLast;
965 CBlockIndex* FindBlockByHeight(int nHeight)
967 CBlockIndex *pblockindex;
968 if (nHeight < nBestHeight / 2)
969 pblockindex = pindexGenesisBlock;
971 pblockindex = pindexBest;
972 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
973 pblockindex = pblockindexFBBHLast;
974 while (pblockindex->nHeight > nHeight)
975 pblockindex = pblockindex->pprev;
976 while (pblockindex->nHeight < nHeight)
977 pblockindex = pblockindex->pnext;
978 pblockindexFBBHLast = pblockindex;
982 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
984 if (!fReadTransactions)
986 *this = pindex->GetBlockHeader();
989 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
991 if (GetHash() != pindex->GetBlockHash())
992 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
996 uint256 static GetOrphanRoot(const CBlock* pblock)
998 // Work back to the first block in the orphan chain
999 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1000 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1001 return pblock->GetHash();
1004 // ppcoin: find block wanted by given orphan block
1005 uint256 WantedByOrphan(const CBlock* pblockOrphan)
1007 // Work back to the first block in the orphan chain
1008 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
1009 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
1010 return pblockOrphan->hashPrevBlock;
1013 // select stake target limit according to hard-coded conditions
1014 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1016 if(fTestNet) // separate proof of stake target limit for testnet
1017 return bnProofOfStakeLimit;
1018 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1019 return bnProofOfStakeLimit;
1020 if(nHeight + 1 > 15000) // 24 bits since block 15000
1021 return bnProofOfStakeLegacyLimit;
1022 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1023 return bnProofOfStakeHardLimit;
1025 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1028 // miner's coin base reward based on nBits
1029 int64_t GetProofOfWorkReward(unsigned int nBits, int64_t nFees)
1031 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1034 bnTarget.SetCompact(nBits);
1035 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1036 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1038 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1039 // A reasonably continuous curve is used to avoid shock to market
1040 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1042 // Human readable form:
1044 // nSubsidy = 100 / (diff ^ 1/6)
1046 // Please note that we're using bisection to find an approximate solutuion
1047 CBigNum bnLowerBound = CENT;
1048 CBigNum bnUpperBound = bnSubsidyLimit;
1049 while (bnLowerBound + CENT <= bnUpperBound)
1051 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1052 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1053 bnUpperBound = bnMidValue;
1055 bnLowerBound = bnMidValue;
1058 int64_t nSubsidy = bnUpperBound.getuint64();
1060 nSubsidy = (nSubsidy / CENT) * CENT;
1061 if (fDebug && GetBoolArg("-printcreation"))
1062 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%" PRId64 "\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1064 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1067 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1068 int64_t GetProofOfStakeReward(int64_t nCoinAge, unsigned int nBits, int64_t nTime, bool bCoinYearOnly)
1070 int64_t nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1072 // Stage 2 of emission process is mostly PoS-based.
1074 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1076 bnTarget.SetCompact(nBits);
1077 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1078 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1080 // A reasonably continuous curve is used to avoid shock to market
1082 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1083 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1084 bnMidPart, bnRewardPart;
1086 while (bnLowerBound + CENT <= bnUpperBound)
1088 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1091 // Reward for coin-year is cut in half every 8x multiply of PoS difficulty
1093 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1095 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1098 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1099 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1101 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1102 bnUpperBound = bnMidValue;
1104 bnLowerBound = bnMidValue;
1107 nRewardCoinYear = bnUpperBound.getuint64();
1108 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1111 return nRewardCoinYear;
1113 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1115 // Set reasonable reward limit for large inputs
1117 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1119 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1120 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1122 nSubsidy = min(nSubsidy, nSubsidyLimit);
1124 if (fDebug && GetBoolArg("-printcreation"))
1125 printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRId64 " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1130 static const int64_t nTargetTimespan = 7 * nOneDay; // one week
1132 // get proof of work blocks max spacing according to hard-coded conditions
1133 int64_t inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1135 if(nTime > TARGETS_SWITCH_TIME)
1136 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1139 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1141 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1145 // maximum nBits value could possible be required nTime after
1147 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime)
1150 bnResult.SetCompact(nBase);
1152 while (nTime > 0 && bnResult < bnTargetLimit)
1154 // Maximum 200% adjustment per day...
1158 if (bnResult > bnTargetLimit)
1159 bnResult = bnTargetLimit;
1160 return bnResult.GetCompact();
1164 // minimum amount of work that could possibly be required nTime after
1165 // minimum proof-of-work required was nBase
1167 unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime)
1169 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1173 // minimum amount of stake that could possibly be required nTime after
1174 // minimum proof-of-stake required was nBase
1176 unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime)
1178 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1182 // ppcoin: find last block index up to pindex
1183 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1185 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1186 pindex = pindex->pprev;
1190 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1192 if (pindexLast == NULL)
1193 return bnProofOfWorkLimit.GetCompact(); // genesis block
1195 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1197 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1198 if (pindexPrev->pprev == NULL)
1199 return bnTargetLimit.GetCompact(); // first block
1200 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1201 if (pindexPrevPrev->pprev == NULL)
1202 return bnTargetLimit.GetCompact(); // second block
1204 int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1206 // ppcoin: target change every block
1207 // ppcoin: retarget with exponential moving toward target spacing
1209 bnNew.SetCompact(pindexPrev->nBits);
1210 int64_t nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64_t) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1211 int64_t nInterval = nTargetTimespan / nTargetSpacing;
1212 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1213 bnNew /= ((nInterval + 1) * nTargetSpacing);
1215 if (bnNew > bnTargetLimit)
1216 bnNew = bnTargetLimit;
1218 return bnNew.GetCompact();
1221 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1224 bnTarget.SetCompact(nBits);
1227 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1228 return error("CheckProofOfWork() : nBits below minimum work");
1230 // Check proof of work matches claimed amount
1231 if (hash > bnTarget.getuint256())
1232 return error("CheckProofOfWork() : hash doesn't match nBits");
1237 // Return maximum amount of blocks that other nodes claim to have
1238 int GetNumBlocksOfPeers()
1240 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1243 bool IsInitialBlockDownload()
1245 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1247 static int64_t nLastUpdate;
1248 static CBlockIndex* pindexLastBest;
1249 int64_t nCurrentTime = GetTime();
1250 if (pindexBest != pindexLastBest)
1252 pindexLastBest = pindexBest;
1253 nLastUpdate = nCurrentTime;
1255 return (nCurrentTime - nLastUpdate < 10 &&
1256 pindexBest->GetBlockTime() < nCurrentTime - nOneDay);
1259 void static InvalidChainFound(CBlockIndex* pindexNew)
1261 if (pindexNew->nChainTrust > nBestInvalidTrust)
1263 nBestInvalidTrust = pindexNew->nChainTrust;
1264 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1265 uiInterface.NotifyBlocksChanged();
1268 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1269 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1271 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1272 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1273 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1274 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1275 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
1276 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1277 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1278 nBestBlockTrust.Get64(),
1279 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1283 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1285 nTime = max(GetBlockTime(), GetAdjustedTime());
1298 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1300 // Relinquish previous transactions' spent pointers
1303 BOOST_FOREACH(const CTxIn& txin, vin)
1305 COutPoint prevout = txin.prevout;
1307 // Get prev txindex from disk
1309 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1310 return error("DisconnectInputs() : ReadTxIndex failed");
1312 if (prevout.n >= txindex.vSpent.size())
1313 return error("DisconnectInputs() : prevout.n out of range");
1315 // Mark outpoint as not spent
1316 txindex.vSpent[prevout.n].SetNull();
1319 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1320 return error("DisconnectInputs() : UpdateTxIndex failed");
1324 // Remove transaction from index
1325 // This can fail if a duplicate of this transaction was in a chain that got
1326 // reorganized away. This is only possible if this transaction was completely
1327 // spent, so erasing it would be a no-op anyway.
1328 txdb.EraseTxIndex(*this);
1334 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1335 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1337 // FetchInputs can return false either because we just haven't seen some inputs
1338 // (in which case the transaction should be stored as an orphan)
1339 // or because the transaction is malformed (in which case the transaction should
1340 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1344 return true; // Coinbase transactions have no inputs to fetch.
1346 for (unsigned int i = 0; i < vin.size(); i++)
1348 COutPoint prevout = vin[i].prevout;
1349 if (inputsRet.count(prevout.hash))
1350 continue; // Got it already
1353 CTxIndex& txindex = inputsRet[prevout.hash].first;
1355 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1357 // Get txindex from current proposed changes
1358 txindex = mapTestPool.find(prevout.hash)->second;
1362 // Read txindex from txdb
1363 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1365 if (!fFound && (fBlock || fMiner))
1366 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());
1369 CTransaction& txPrev = inputsRet[prevout.hash].second;
1370 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1372 // Get prev tx from single transactions in memory
1375 if (!mempool.exists(prevout.hash))
1376 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());
1377 txPrev = mempool.lookup(prevout.hash);
1380 txindex.vSpent.resize(txPrev.vout.size());
1384 // Get prev tx from disk
1385 if (!txPrev.ReadFromDisk(txindex.pos))
1386 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1390 // Make sure all prevout.n indexes are valid:
1391 for (unsigned int i = 0; i < vin.size(); i++)
1393 const COutPoint prevout = vin[i].prevout;
1394 assert(inputsRet.count(prevout.hash) != 0);
1395 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1396 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1397 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1399 // Revisit this if/when transaction replacement is implemented and allows
1402 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()));
1409 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1411 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1412 if (mi == inputs.end())
1413 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1415 const CTransaction& txPrev = (mi->second).second;
1416 if (input.prevout.n >= txPrev.vout.size())
1417 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1419 return txPrev.vout[input.prevout.n];
1422 int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const
1427 int64_t nResult = 0;
1428 for (unsigned int i = 0; i < vin.size(); i++)
1430 nResult += GetOutputFor(vin[i], inputs).nValue;
1436 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1441 unsigned int nSigOps = 0;
1442 for (unsigned int i = 0; i < vin.size(); i++)
1444 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1445 if (prevout.scriptPubKey.IsPayToScriptHash())
1446 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1451 bool CScriptCheck::operator()() const {
1452 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1453 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1454 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1458 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1460 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1463 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1464 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1466 // Take over previous transactions' spent pointers
1467 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1468 // fMiner is true when called from the internal bitcoin miner
1469 // ... both are false when called from CTransaction::AcceptToMemoryPool
1473 int64_t nValueIn = 0;
1475 for (unsigned int i = 0; i < vin.size(); i++)
1477 COutPoint prevout = vin[i].prevout;
1478 assert(inputs.count(prevout.hash) > 0);
1479 CTxIndex& txindex = inputs[prevout.hash].first;
1480 CTransaction& txPrev = inputs[prevout.hash].second;
1482 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1483 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()));
1485 // If prev is coinbase or coinstake, check that it's matured
1486 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1487 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1488 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1489 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1491 // ppcoin: check transaction timestamp
1492 if (txPrev.nTime > nTime)
1493 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1495 // Check for negative or overflow input values
1496 nValueIn += txPrev.vout[prevout.n].nValue;
1497 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1498 return DoS(100, error("ConnectInputs() : txin values out of range"));
1503 pvChecks->reserve(vin.size());
1505 // The first loop above does all the inexpensive checks.
1506 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1507 // Helps prevent CPU exhaustion attacks.
1508 for (unsigned int i = 0; i < vin.size(); i++)
1510 COutPoint prevout = vin[i].prevout;
1511 assert(inputs.count(prevout.hash) > 0);
1512 CTxIndex& txindex = inputs[prevout.hash].first;
1513 CTransaction& txPrev = inputs[prevout.hash].second;
1515 // Check for conflicts (double-spend)
1516 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1517 // for an attacker to attempt to split the network.
1518 if (!txindex.vSpent[prevout.n].IsNull())
1519 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());
1521 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1522 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1523 // still computed and checked, and any change will be caught at the next checkpoint.
1527 CScriptCheck check(txPrev, *this, i, flags, 0);
1530 pvChecks->push_back(CScriptCheck());
1531 check.swap(pvChecks->back());
1535 if (flags & STRICT_FLAGS)
1537 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1538 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1540 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1542 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1546 // Mark outpoints as spent
1547 txindex.vSpent[prevout.n] = posThisTx;
1550 if (fBlock || fMiner)
1552 mapTestPool[prevout.hash] = txindex;
1558 if (nTime > Checkpoints::GetLastCheckpointTime())
1560 unsigned int nTxSize = GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
1562 // coin stake tx earns reward instead of paying fee
1564 if (!GetCoinAge(txdb, nCoinAge))
1565 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1567 int64_t nReward = GetValueOut() - nValueIn;
1568 int64_t nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1570 if (nReward > nCalculatedReward)
1571 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%" PRId64 " vs calculated=%" PRId64 ")", nReward, nCalculatedReward));
1576 if (nValueIn < GetValueOut())
1577 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1579 // Tally transaction fees
1580 int64_t nTxFee = nValueIn - GetValueOut();
1582 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1585 if (!MoneyRange(nFees))
1586 return DoS(100, error("ConnectInputs() : nFees out of range"));
1594 bool CTransaction::ClientConnectInputs()
1599 // Take over previous transactions' spent pointers
1602 int64_t nValueIn = 0;
1603 for (unsigned int i = 0; i < vin.size(); i++)
1605 // Get prev tx from single transactions in memory
1606 COutPoint prevout = vin[i].prevout;
1607 if (!mempool.exists(prevout.hash))
1609 CTransaction& txPrev = mempool.lookup(prevout.hash);
1611 if (prevout.n >= txPrev.vout.size())
1615 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1616 return error("ClientConnectInputs() : VerifySignature failed");
1618 ///// this is redundant with the mempool.mapNextTx stuff,
1619 ///// not sure which I want to get rid of
1620 ///// this has to go away now that posNext is gone
1621 // // Check for conflicts
1622 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1623 // return error("ConnectInputs() : prev tx already used");
1625 // // Flag outpoints as used
1626 // txPrev.vout[prevout.n].posNext = posThisTx;
1628 nValueIn += txPrev.vout[prevout.n].nValue;
1630 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1631 return error("ClientConnectInputs() : txin values out of range");
1633 if (GetValueOut() > nValueIn)
1643 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1645 // Disconnect in reverse order
1646 for (int i = vtx.size()-1; i >= 0; i--)
1647 if (!vtx[i].DisconnectInputs(txdb))
1650 // Update block index on disk without changing it in memory.
1651 // The memory index structure will be changed after the db commits.
1654 CDiskBlockIndex blockindexPrev(pindex->pprev);
1655 blockindexPrev.hashNext = 0;
1656 if (!txdb.WriteBlockIndex(blockindexPrev))
1657 return error("DisconnectBlock() : WriteBlockIndex failed");
1660 // ppcoin: clean up wallet after disconnecting coinstake
1661 BOOST_FOREACH(CTransaction& tx, vtx)
1662 SyncWithWallets(tx, this, false, false);
1667 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1669 void ThreadScriptCheck(void*) {
1670 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1671 RenameThread("novacoin-scriptch");
1672 scriptcheckqueue.Thread();
1673 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1676 void ThreadScriptCheckQuit() {
1677 scriptcheckqueue.Quit();
1680 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1682 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1683 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1686 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1687 // unless those are already completely spent.
1688 // If such overwrites are allowed, coinbases and transactions depending upon those
1689 // can be duplicated to remove the ability to spend the first instance -- even after
1690 // being sent to another address.
1691 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1692 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1693 // already refuses previously-known transaction ids entirely.
1694 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1695 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1696 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1697 // initial block download.
1698 bool fEnforceBIP30 = true; // Always active in NovaCoin
1699 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1701 //// issue here: it doesn't know the version
1702 unsigned int nTxPos;
1704 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1705 // 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
1708 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1710 map<uint256, CTxIndex> mapQueuedChanges;
1711 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1714 int64_t nValueIn = 0;
1715 int64_t nValueOut = 0;
1716 unsigned int nSigOps = 0;
1717 BOOST_FOREACH(CTransaction& tx, vtx)
1719 uint256 hashTx = tx.GetHash();
1721 if (fEnforceBIP30) {
1722 CTxIndex txindexOld;
1723 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1724 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1730 nSigOps += tx.GetLegacySigOpCount();
1731 if (nSigOps > MAX_BLOCK_SIGOPS)
1732 return DoS(100, error("ConnectBlock() : too many sigops"));
1734 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1736 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1738 MapPrevTx mapInputs;
1739 if (tx.IsCoinBase())
1740 nValueOut += tx.GetValueOut();
1744 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1747 // Add in sigops done by pay-to-script-hash inputs;
1748 // this is to prevent a "rogue miner" from creating
1749 // an incredibly-expensive-to-validate block.
1750 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1751 if (nSigOps > MAX_BLOCK_SIGOPS)
1752 return DoS(100, error("ConnectBlock() : too many sigops"));
1754 int64_t nTxValueIn = tx.GetValueIn(mapInputs);
1755 int64_t nTxValueOut = tx.GetValueOut();
1756 nValueIn += nTxValueIn;
1757 nValueOut += nTxValueOut;
1758 if (!tx.IsCoinStake())
1759 nFees += nTxValueIn - nTxValueOut;
1761 std::vector<CScriptCheck> vChecks;
1762 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, nScriptCheckThreads ? &vChecks : NULL))
1764 control.Add(vChecks);
1767 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1770 if (!control.Wait())
1771 return DoS(100, false);
1773 if (IsProofOfWork())
1775 int64_t nBlockReward = GetProofOfWorkReward(nBits, nFees);
1777 // Check coinbase reward
1778 if (vtx[0].GetValueOut() > nBlockReward)
1779 return error("CheckBlock() : coinbase reward exceeded (actual=%" PRId64 " vs calculated=%" PRId64 ")",
1780 vtx[0].GetValueOut(),
1784 // track money supply and mint amount info
1785 pindex->nMint = nValueOut - nValueIn + nFees;
1786 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1787 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1788 return error("Connect() : WriteBlockIndex for pindex failed");
1790 // fees are not collected by proof-of-stake miners
1791 // fees are destroyed to compensate the entire network
1792 if (fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1793 printf("ConnectBlock() : destroy=%s nFees=%" PRId64 "\n", FormatMoney(nFees).c_str(), nFees);
1798 // Write queued txindex changes
1799 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1801 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1802 return error("ConnectBlock() : UpdateTxIndex failed");
1805 // Update block index on disk without changing it in memory.
1806 // The memory index structure will be changed after the db commits.
1809 CDiskBlockIndex blockindexPrev(pindex->pprev);
1810 blockindexPrev.hashNext = pindex->GetBlockHash();
1811 if (!txdb.WriteBlockIndex(blockindexPrev))
1812 return error("ConnectBlock() : WriteBlockIndex failed");
1815 // Watch for transactions paying to me
1816 BOOST_FOREACH(CTransaction& tx, vtx)
1817 SyncWithWallets(tx, this, true);
1823 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1825 printf("REORGANIZE\n");
1828 CBlockIndex* pfork = pindexBest;
1829 CBlockIndex* plonger = pindexNew;
1830 while (pfork != plonger)
1832 while (plonger->nHeight > pfork->nHeight)
1833 if (!(plonger = plonger->pprev))
1834 return error("Reorganize() : plonger->pprev is null");
1835 if (pfork == plonger)
1837 if (!(pfork = pfork->pprev))
1838 return error("Reorganize() : pfork->pprev is null");
1841 // List of what to disconnect
1842 vector<CBlockIndex*> vDisconnect;
1843 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1844 vDisconnect.push_back(pindex);
1846 // List of what to connect
1847 vector<CBlockIndex*> vConnect;
1848 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1849 vConnect.push_back(pindex);
1850 reverse(vConnect.begin(), vConnect.end());
1852 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());
1853 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());
1855 // Disconnect shorter branch
1856 vector<CTransaction> vResurrect;
1857 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1860 if (!block.ReadFromDisk(pindex))
1861 return error("Reorganize() : ReadFromDisk for disconnect failed");
1862 if (!block.DisconnectBlock(txdb, pindex))
1863 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1865 // Queue memory transactions to resurrect
1866 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1867 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1868 vResurrect.push_back(tx);
1871 // Connect longer branch
1872 vector<CTransaction> vDelete;
1873 for (unsigned int i = 0; i < vConnect.size(); i++)
1875 CBlockIndex* pindex = vConnect[i];
1877 if (!block.ReadFromDisk(pindex))
1878 return error("Reorganize() : ReadFromDisk for connect failed");
1879 if (!block.ConnectBlock(txdb, pindex))
1882 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1885 // Queue memory transactions to delete
1886 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1887 vDelete.push_back(tx);
1889 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1890 return error("Reorganize() : WriteHashBestChain failed");
1892 // Make sure it's successfully written to disk before changing memory structure
1893 if (!txdb.TxnCommit())
1894 return error("Reorganize() : TxnCommit failed");
1896 // Disconnect shorter branch
1897 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1899 pindex->pprev->pnext = NULL;
1901 // Connect longer branch
1902 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1904 pindex->pprev->pnext = pindex;
1906 // Resurrect memory transactions that were in the disconnected branch
1907 BOOST_FOREACH(CTransaction& tx, vResurrect)
1908 tx.AcceptToMemoryPool(txdb, false);
1910 // Delete redundant memory transactions that are in the connected branch
1911 BOOST_FOREACH(CTransaction& tx, vDelete)
1914 printf("REORGANIZE: done\n");
1920 // Called from inside SetBestChain: attaches a block to the new best chain being built
1921 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1923 uint256 hash = GetHash();
1925 // Adding to current best branch
1926 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1929 InvalidChainFound(pindexNew);
1932 if (!txdb.TxnCommit())
1933 return error("SetBestChain() : TxnCommit failed");
1935 // Add to current best branch
1936 pindexNew->pprev->pnext = pindexNew;
1938 // Delete redundant memory transactions
1939 BOOST_FOREACH(CTransaction& tx, vtx)
1945 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1947 uint256 hash = GetHash();
1949 if (!txdb.TxnBegin())
1950 return error("SetBestChain() : TxnBegin failed");
1952 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1954 txdb.WriteHashBestChain(hash);
1955 if (!txdb.TxnCommit())
1956 return error("SetBestChain() : TxnCommit failed");
1957 pindexGenesisBlock = pindexNew;
1959 else if (hashPrevBlock == hashBestChain)
1961 if (!SetBestChainInner(txdb, pindexNew))
1962 return error("SetBestChain() : SetBestChainInner failed");
1966 // the first block in the new chain that will cause it to become the new best chain
1967 CBlockIndex *pindexIntermediate = pindexNew;
1969 // list of blocks that need to be connected afterwards
1970 std::vector<CBlockIndex*> vpindexSecondary;
1972 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1973 // Try to limit how much needs to be done inside
1974 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1976 vpindexSecondary.push_back(pindexIntermediate);
1977 pindexIntermediate = pindexIntermediate->pprev;
1980 if (!vpindexSecondary.empty())
1981 printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
1983 // Switch to new best branch
1984 if (!Reorganize(txdb, pindexIntermediate))
1987 InvalidChainFound(pindexNew);
1988 return error("SetBestChain() : Reorganize failed");
1991 // Connect further blocks
1992 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1995 if (!block.ReadFromDisk(pindex))
1997 printf("SetBestChain() : ReadFromDisk failed\n");
2000 if (!txdb.TxnBegin()) {
2001 printf("SetBestChain() : TxnBegin 2 failed\n");
2004 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
2005 if (!block.SetBestChainInner(txdb, pindex))
2010 // Update best block in wallet (so we can detect restored wallets)
2011 bool fIsInitialDownload = IsInitialBlockDownload();
2012 if (!fIsInitialDownload)
2014 const CBlockLocator locator(pindexNew);
2015 ::SetBestChain(locator);
2019 hashBestChain = hash;
2020 pindexBest = pindexNew;
2021 pblockindexFBBHLast = NULL;
2022 nBestHeight = pindexBest->nHeight;
2023 nBestChainTrust = pindexNew->nChainTrust;
2024 nTimeBestReceived = GetTime();
2025 nTransactionsUpdated++;
2027 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2029 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%" PRId64 " date=%s\n",
2030 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2031 CBigNum(nBestChainTrust).ToString().c_str(),
2032 nBestBlockTrust.Get64(),
2033 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2035 // Check the version of the last 100 blocks to see if we need to upgrade:
2036 if (!fIsInitialDownload)
2039 const CBlockIndex* pindex = pindexBest;
2040 for (int i = 0; i < 100 && pindex != NULL; i++)
2042 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2044 pindex = pindex->pprev;
2047 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2048 if (nUpgraded > 100/2)
2049 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2050 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2053 std::string strCmd = GetArg("-blocknotify", "");
2055 if (!fIsInitialDownload && !strCmd.empty())
2057 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
2058 boost::thread t(runCommand, strCmd); // thread runs free
2064 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2065 // Only those coins meeting minimum age requirement counts. As those
2066 // transactions not in main chain are not currently indexed so we
2067 // might not find out about their coin age. Older transactions are
2068 // guaranteed to be in main chain by sync-checkpoint. This rule is
2069 // introduced to help nodes establish a consistent view of the coin
2070 // age (trust score) of competing branches.
2071 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const
2073 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2079 BOOST_FOREACH(const CTxIn& txin, vin)
2081 // First try finding the previous transaction in database
2082 CTransaction txPrev;
2084 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2085 continue; // previous transaction not in main chain
2086 if (nTime < txPrev.nTime)
2087 return false; // Transaction timestamp violation
2089 // Read block header
2091 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2092 return false; // unable to read block of previous transaction
2093 if (block.GetBlockTime() + nStakeMinAge > nTime)
2094 continue; // only count coins meeting min age requirement
2096 int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue;
2097 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2099 if (fDebug && GetBoolArg("-printcoinage"))
2100 printf("coin age nValueIn=%" PRId64 " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2103 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / nOneDay;
2104 if (fDebug && GetBoolArg("-printcoinage"))
2105 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2106 nCoinAge = bnCoinDay.getuint64();
2110 // ppcoin: total coin age spent in block, in the unit of coin-days.
2111 bool CBlock::GetCoinAge(uint64_t& nCoinAge) const
2116 BOOST_FOREACH(const CTransaction& tx, vtx)
2118 uint64_t nTxCoinAge;
2119 if (tx.GetCoinAge(txdb, nTxCoinAge))
2120 nCoinAge += nTxCoinAge;
2125 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2127 if (fDebug && GetBoolArg("-printcoinage"))
2128 printf("block coin age total nCoinDays=%" PRId64 "\n", nCoinAge);
2132 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2134 // Check for duplicate
2135 uint256 hash = GetHash();
2136 if (mapBlockIndex.count(hash))
2137 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2139 // Construct new block index object
2140 CBlockIndex* pindexNew = new(nothrow) CBlockIndex(nFile, nBlockPos, *this);
2142 return error("AddToBlockIndex() : new CBlockIndex failed");
2143 pindexNew->phashBlock = &hash;
2144 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2145 if (miPrev != mapBlockIndex.end())
2147 pindexNew->pprev = (*miPrev).second;
2148 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2151 // ppcoin: compute chain trust score
2152 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2154 // ppcoin: compute stake entropy bit for stake modifier
2155 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2156 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2158 // ppcoin: record proof-of-stake hash value
2159 if (pindexNew->IsProofOfStake())
2161 if (!mapProofOfStake.count(hash))
2162 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2163 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2166 // ppcoin: compute stake modifier
2167 uint64_t nStakeModifier = 0;
2168 bool fGeneratedStakeModifier = false;
2169 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2170 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2171 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2172 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2173 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2174 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindexNew->nHeight, nStakeModifier);
2176 // Add to mapBlockIndex
2177 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2178 if (pindexNew->IsProofOfStake())
2179 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2180 pindexNew->phashBlock = &((*mi).first);
2182 // Write to disk block index
2184 if (!txdb.TxnBegin())
2186 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2187 if (!txdb.TxnCommit())
2191 if (pindexNew->nChainTrust > nBestChainTrust)
2192 if (!SetBestChain(txdb, pindexNew))
2195 if (pindexNew == pindexBest)
2197 // Notify UI to display prev block's coinbase if it was ours
2198 static uint256 hashPrevBestCoinBase;
2199 UpdatedTransaction(hashPrevBestCoinBase);
2200 hashPrevBestCoinBase = vtx[0].GetHash();
2203 static int8_t counter = 0;
2204 if( (++counter & 0x0F) == 0 || !IsInitialBlockDownload()) // repaint every 16 blocks if not in initial block download
2205 uiInterface.NotifyBlocksChanged();
2212 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2214 // These are checks that are independent of context
2215 // that can be verified before saving an orphan block.
2217 set<uint256> uniqueTx; // tx hashes
2218 unsigned int nSigOps = 0; // total sigops
2221 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2222 return DoS(100, error("CheckBlock() : size limits failed"));
2224 bool fProofOfStake = IsProofOfStake();
2226 // First transaction must be coinbase, the rest must not be
2227 if (!vtx[0].IsCoinBase())
2228 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2230 if (!vtx[0].CheckTransaction())
2231 return DoS(vtx[0].nDoS, error("CheckBlock() : CheckTransaction failed on coinbase"));
2233 uniqueTx.insert(vtx[0].GetHash());
2234 nSigOps += vtx[0].GetLegacySigOpCount();
2238 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
2239 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
2241 // nNonce must be zero for proof-of-stake blocks
2243 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2245 // Coinbase output should be empty if proof-of-stake block
2246 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2247 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2249 // Check coinstake timestamp
2250 if (GetBlockTime() != (int64_t)vtx[1].nTime)
2251 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRId64 " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2253 // NovaCoin: check proof-of-stake block signature
2254 if (fCheckSig && !CheckBlockSignature())
2255 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2257 if (!vtx[1].CheckTransaction())
2258 return DoS(vtx[1].nDoS, error("CheckBlock() : CheckTransaction failed on coinstake"));
2260 uniqueTx.insert(vtx[1].GetHash());
2261 nSigOps += vtx[1].GetLegacySigOpCount();
2265 // Check proof of work matches claimed amount
2266 if (fCheckPOW && !CheckProofOfWork(GetHash(), nBits))
2267 return DoS(50, error("CheckBlock() : proof of work failed"));
2270 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2271 return error("CheckBlock() : block timestamp too far in the future");
2273 // Check coinbase timestamp
2274 if (GetBlockTime() < PastDrift((int64_t)vtx[0].nTime))
2275 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2278 // Iterate all transactions starting from second for proof-of-stake block
2279 // or first for proof-of-work block
2280 for (unsigned int i = fProofOfStake ? 2 : 1; i < vtx.size(); i++)
2282 const CTransaction& tx = vtx[i];
2284 // Reject coinbase transactions at non-zero index
2285 if (tx.IsCoinBase())
2286 return DoS(100, error("CheckBlock() : coinbase at wrong index"));
2288 // Reject coinstake transactions at index != 1
2289 if (tx.IsCoinStake())
2290 return DoS(100, error("CheckBlock() : coinstake at wrong index"));
2292 // Check transaction timestamp
2293 if (GetBlockTime() < (int64_t)tx.nTime)
2294 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2296 // Check transaction consistency
2297 if (!tx.CheckTransaction())
2298 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2300 // Add transaction hash into list of unique transaction IDs
2301 uniqueTx.insert(tx.GetHash());
2303 // Calculate sigops count
2304 nSigOps += tx.GetLegacySigOpCount();
2307 // Check for duplicate txids. This is caught by ConnectInputs(),
2308 // but catching it earlier avoids a potential DoS attack:
2309 if (uniqueTx.size() != vtx.size())
2310 return DoS(100, error("CheckBlock() : duplicate transaction"));
2312 // Reject block if validation would consume too much resources.
2313 if (nSigOps > MAX_BLOCK_SIGOPS)
2314 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2316 // Check merkle root
2317 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2318 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2323 bool CBlock::AcceptBlock()
2325 // Check for duplicate
2326 uint256 hash = GetHash();
2327 if (mapBlockIndex.count(hash))
2328 return error("AcceptBlock() : block already in mapBlockIndex");
2330 // Get prev block index
2331 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2332 if (mi == mapBlockIndex.end())
2333 return DoS(10, error("AcceptBlock() : prev block not found"));
2334 CBlockIndex* pindexPrev = (*mi).second;
2335 int nHeight = pindexPrev->nHeight+1;
2337 // Check proof-of-work or proof-of-stake
2338 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2339 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2341 int64_t nMedianTimePast = pindexPrev->GetMedianTimePast();
2342 int nMaxOffset = 12 * 3600; // 12 hours
2343 if (pindexPrev->nTime < 1450569600)
2344 nMaxOffset = 7 * 86400; // One week until 20 Dec, 2015
2346 // Check timestamp against prev
2347 if (GetBlockTime() <= nMedianTimePast || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2348 return error("AcceptBlock() : block's timestamp is too early");
2350 // Don't accept blocks with future timestamps
2351 if (pindexPrev->nHeight > 1 && nMedianTimePast + nMaxOffset < GetBlockTime())
2352 return error("AcceptBlock() : block's timestamp is too far in the future");
2354 // Check that all transactions are finalized
2355 BOOST_FOREACH(const CTransaction& tx, vtx)
2356 if (!tx.IsFinal(nHeight, GetBlockTime()))
2357 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2359 // Check that the block chain matches the known block chain up to a checkpoint
2360 if (!Checkpoints::CheckHardened(nHeight, hash))
2361 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2363 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2365 // Check that the block satisfies synchronized checkpoint
2366 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2367 return error("AcceptBlock() : rejected by synchronized checkpoint");
2369 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2370 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2372 // Enforce rule that the coinbase starts with serialized block height
2373 CScript expect = CScript() << nHeight;
2374 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2375 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2376 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2378 // Write block to history file
2379 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2380 return error("AcceptBlock() : out of disk space");
2381 unsigned int nFile = std::numeric_limits<unsigned int>::max();
2382 unsigned int nBlockPos = 0;
2383 if (!WriteToDisk(nFile, nBlockPos))
2384 return error("AcceptBlock() : WriteToDisk failed");
2385 if (!AddToBlockIndex(nFile, nBlockPos))
2386 return error("AcceptBlock() : AddToBlockIndex failed");
2388 // Relay inventory, but don't relay old inventory during initial block download
2389 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2390 if (hashBestChain == hash)
2393 BOOST_FOREACH(CNode* pnode, vNodes)
2394 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2395 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2398 // ppcoin: check pending sync-checkpoint
2399 Checkpoints::AcceptPendingSyncCheckpoint();
2404 uint256 CBlockIndex::GetBlockTrust() const
2407 bnTarget.SetCompact(nBits);
2412 // Return 1 for the first 12 blocks
2413 if (pprev == NULL || pprev->nHeight < 12)
2416 const CBlockIndex* currentIndex = pprev;
2418 if(IsProofOfStake())
2420 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2422 // Return 1/3 of score if parent block is not the PoW block
2423 if (!pprev->IsProofOfWork())
2424 return (bnNewTrust / 3).getuint256();
2428 // Check last 12 blocks type
2429 while (pprev->nHeight - currentIndex->nHeight < 12)
2431 if (currentIndex->IsProofOfWork())
2433 currentIndex = currentIndex->pprev;
2436 // Return 1/3 of score if less than 3 PoW blocks found
2438 return (bnNewTrust / 3).getuint256();
2440 return bnNewTrust.getuint256();
2444 // Calculate work amount for block
2445 CBigNum bnPoWTrust = CBigNum(nPoWBase) / (bnTarget+1);
2447 // Set nPowTrust to 1 if PoW difficulty is too low
2451 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2453 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2454 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2455 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2459 // Check last 12 blocks type
2460 while (pprev->nHeight - currentIndex->nHeight < 12)
2462 if (currentIndex->IsProofOfStake())
2464 currentIndex = currentIndex->pprev;
2467 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2469 return (bnPoWTrust + 2 * bnLastBlockTrust / 3).getuint256();
2471 bnTarget.SetCompact(pprev->nBits);
2476 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2478 // Return nPoWTrust + full trust score for previous block nBits
2479 return (bnPoWTrust + bnNewTrust).getuint256();
2483 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2485 unsigned int nFound = 0;
2486 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2488 if (pstart->nVersion >= minVersion)
2490 pstart = pstart->pprev;
2492 return (nFound >= nRequired);
2495 bool static ReserealizeBlockSignature(CBlock* pblock)
2497 if (pblock->IsProofOfWork())
2499 pblock->vchBlockSig.clear();
2503 return CKey::ReserealizeSignature(pblock->vchBlockSig);
2506 bool static IsCanonicalBlockSignature(CBlock* pblock)
2508 if (pblock->IsProofOfWork())
2509 return pblock->vchBlockSig.empty();
2511 return IsDERSignature(pblock->vchBlockSig);
2514 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2516 // Check for duplicate
2517 uint256 hash = pblock->GetHash();
2518 if (mapBlockIndex.count(hash))
2519 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2520 if (mapOrphanBlocks.count(hash))
2521 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2523 // Check proof-of-stake
2524 // Limited duplicity on stake: prevents block flood attack
2525 // Duplicate stake allowed only when there is orphan child block
2526 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2527 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
2529 // Strip the garbage from newly received blocks, if we found some
2530 if (!IsCanonicalBlockSignature(pblock)) {
2531 if (!ReserealizeBlockSignature(pblock))
2532 printf("WARNING: ProcessBlock() : ReserealizeBlockSignature FAILED\n");
2535 // Preliminary checks
2536 if (!pblock->CheckBlock(true, true, (pblock->nTime > Checkpoints::GetLastCheckpointTime())))
2537 return error("ProcessBlock() : CheckBlock FAILED");
2539 // ppcoin: verify hash target and signature of coinstake tx
2540 if (pblock->IsProofOfStake())
2542 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2543 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2545 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2546 return false; // do not error here as we expect this during initial block download
2548 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2549 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2552 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2553 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2555 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2556 int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2558 bnNewBlock.SetCompact(pblock->nBits);
2561 if (pblock->IsProofOfStake())
2562 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2564 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2566 if (bnNewBlock > bnRequired)
2569 pfrom->Misbehaving(100);
2570 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2574 // ppcoin: ask for pending sync-checkpoint if any
2575 if (!IsInitialBlockDownload())
2576 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2578 // If don't already have its previous block, shunt it off to holding area until we get it
2579 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2581 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2582 // ppcoin: check proof-of-stake
2583 if (pblock->IsProofOfStake())
2585 // Limited duplicity on stake: prevents block flood attack
2586 // Duplicate stake allowed only when there is orphan child block
2587 if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2588 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());
2590 setStakeSeenOrphan.insert(pblock->GetProofOfStake());
2592 CBlock* pblock2 = new CBlock(*pblock);
2593 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2594 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2596 // Ask this guy to fill in what we're missing
2599 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2600 // ppcoin: getblocks may not obtain the ancestor block rejected
2601 // earlier by duplicate-stake check so we ask for it again directly
2602 if (!IsInitialBlockDownload())
2603 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2609 if (!pblock->AcceptBlock())
2610 return error("ProcessBlock() : AcceptBlock FAILED");
2612 // Recursively process any orphan blocks that depended on this one
2613 vector<uint256> vWorkQueue;
2614 vWorkQueue.push_back(hash);
2615 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2617 uint256 hashPrev = vWorkQueue[i];
2618 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2619 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2622 CBlock* pblockOrphan = (*mi).second;
2623 if (pblockOrphan->AcceptBlock())
2624 vWorkQueue.push_back(pblockOrphan->GetHash());
2625 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2626 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2627 delete pblockOrphan;
2629 mapOrphanBlocksByPrev.erase(hashPrev);
2632 printf("ProcessBlock: ACCEPTED\n");
2634 // ppcoin: if responsible for sync-checkpoint send it
2635 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2636 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2641 // ppcoin: check block signature
2642 bool CBlock::CheckBlockSignature() const
2644 if (vchBlockSig.empty())
2647 txnouttype whichType;
2648 vector<valtype> vSolutions;
2649 if (!Solver(vtx[1].vout[1].scriptPubKey, whichType, vSolutions))
2652 if (whichType == TX_PUBKEY)
2654 valtype& vchPubKey = vSolutions[0];
2656 if (!key.SetPubKey(vchPubKey))
2658 return key.Verify(GetHash(), vchBlockSig);
2664 bool CheckDiskSpace(uint64_t nAdditionalBytes)
2666 uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2668 // Check for nMinDiskSpace bytes (currently 50MB)
2669 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2672 string strMessage = _("Warning: Disk space is low!");
2673 strMiscWarning = strMessage;
2674 printf("*** %s\n", strMessage.c_str());
2675 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2682 static filesystem::path BlockFilePath(unsigned int nFile)
2684 string strBlockFn = strprintf("blk%04u.dat", nFile);
2685 return GetDataDir() / strBlockFn;
2688 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2690 if ((nFile < 1) || (nFile == std::numeric_limits<uint32_t>::max()))
2692 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2695 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2697 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2706 static unsigned int nCurrentBlockFile = 1;
2708 FILE* AppendBlockFile(unsigned int& nFileRet)
2713 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2716 if (fseek(file, 0, SEEK_END) != 0)
2718 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2719 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2721 nFileRet = nCurrentBlockFile;
2725 nCurrentBlockFile++;
2729 void UnloadBlockIndex()
2731 mapBlockIndex.clear();
2732 setStakeSeen.clear();
2733 pindexGenesisBlock = NULL;
2735 nBestChainTrust = 0;
2736 nBestInvalidTrust = 0;
2741 bool LoadBlockIndex(bool fAllowNew)
2745 pchMessageStart[0] = 0xcd;
2746 pchMessageStart[1] = 0xf2;
2747 pchMessageStart[2] = 0xc0;
2748 pchMessageStart[3] = 0xef;
2750 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2751 nStakeMinAge = 2 * nOneHour; // test net min age is 2 hours
2752 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2753 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2754 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2761 if (!txdb.LoadBlockIndex())
2765 // Init with genesis block
2767 if (mapBlockIndex.empty())
2776 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2777 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2778 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2780 // vMerkleTree: 4cb33b3b6a
2784 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2785 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2786 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2788 // vMerkleTree: 4cb33b3b6a
2790 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2792 txNew.nTime = 1360105017;
2793 txNew.vin.resize(1);
2794 txNew.vout.resize(1);
2795 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2796 txNew.vout[0].SetEmpty();
2798 block.vtx.push_back(txNew);
2799 block.hashPrevBlock = 0;
2800 block.hashMerkleRoot = block.BuildMerkleTree();
2802 block.nTime = 1360105017;
2803 block.nBits = bnProofOfWorkLimit.GetCompact();
2804 block.nNonce = !fTestNet ? 1575379 : 46534;
2807 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2809 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2810 assert(block.CheckBlock());
2812 // Start new block file
2814 unsigned int nBlockPos;
2815 if (!block.WriteToDisk(nFile, nBlockPos))
2816 return error("LoadBlockIndex() : writing genesis block to disk failed");
2817 if (!block.AddToBlockIndex(nFile, nBlockPos))
2818 return error("LoadBlockIndex() : genesis block not accepted");
2820 // initialize synchronized checkpoint
2821 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2822 return error("LoadBlockIndex() : failed to init sync checkpoint");
2824 // upgrade time set to zero if txdb initialized
2826 if (!txdb.WriteModifierUpgradeTime(0))
2827 return error("LoadBlockIndex() : failed to init upgrade info");
2828 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2834 string strPubKey = "";
2835 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2837 // write checkpoint master key to db
2839 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2840 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2841 if (!txdb.TxnCommit())
2842 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2843 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2844 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2847 // upgrade time set to zero if blocktreedb initialized
2848 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2850 if (nModifierUpgradeTime)
2851 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2853 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2857 nModifierUpgradeTime = GetTime();
2858 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2859 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2860 return error("LoadBlockIndex() : failed to write upgrade info");
2873 void PrintBlockTree()
2875 // pre-compute tree structure
2876 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2877 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2879 CBlockIndex* pindex = (*mi).second;
2880 mapNext[pindex->pprev].push_back(pindex);
2882 //while (rand() % 3 == 0)
2883 // mapNext[pindex->pprev].push_back(pindex);
2886 vector<pair<int, CBlockIndex*> > vStack;
2887 vStack.push_back(make_pair(0, pindexGenesisBlock));
2890 while (!vStack.empty())
2892 int nCol = vStack.back().first;
2893 CBlockIndex* pindex = vStack.back().second;
2896 // print split or gap
2897 if (nCol > nPrevCol)
2899 for (int i = 0; i < nCol-1; i++)
2903 else if (nCol < nPrevCol)
2905 for (int i = 0; i < nCol; i++)
2912 for (int i = 0; i < nCol; i++)
2917 block.ReadFromDisk(pindex);
2918 printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
2922 block.GetHash().ToString().c_str(),
2924 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2925 FormatMoney(pindex->nMint).c_str(),
2928 PrintWallets(block);
2930 // put the main time-chain first
2931 vector<CBlockIndex*>& vNext = mapNext[pindex];
2932 for (unsigned int i = 0; i < vNext.size(); i++)
2934 if (vNext[i]->pnext)
2936 swap(vNext[0], vNext[i]);
2942 for (unsigned int i = 0; i < vNext.size(); i++)
2943 vStack.push_back(make_pair(nCol+i, vNext[i]));
2947 bool LoadExternalBlockFile(FILE* fileIn)
2949 int64_t nStart = GetTimeMillis();
2955 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2956 unsigned int nPos = 0;
2957 while (nPos != std::numeric_limits<uint32_t>::max() && blkdat.good() && !fRequestShutdown)
2959 unsigned char pchData[65536];
2961 fseek(blkdat, nPos, SEEK_SET);
2962 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2965 nPos = std::numeric_limits<uint32_t>::max();
2968 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2971 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2973 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2976 nPos += ((unsigned char*)nFind - pchData) + 1;
2979 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2980 } while(!fRequestShutdown);
2981 if (nPos == std::numeric_limits<uint32_t>::max())
2983 fseek(blkdat, nPos, SEEK_SET);
2986 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2990 if (ProcessBlock(NULL,&block))
2998 catch (const std::exception&) {
2999 printf("%s() : Deserialize or I/O error caught during load\n",
3000 BOOST_CURRENT_FUNCTION);
3003 printf("Loaded %i blocks from external file in %" PRId64 "ms\n", nLoaded, GetTimeMillis() - nStart);
3007 //////////////////////////////////////////////////////////////////////////////
3012 extern map<uint256, CAlert> mapAlerts;
3013 extern CCriticalSection cs_mapAlerts;
3015 string GetWarnings(string strFor)
3018 string strStatusBar;
3021 if (GetBoolArg("-testsafemode"))
3024 // Misc warnings like out of disk space and clock is wrong
3025 if (strMiscWarning != "")
3028 strStatusBar = strMiscWarning;
3031 // if detected unmet upgrade requirement enter safe mode
3032 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3033 if (IsFixedModifierInterval(nModifierUpgradeTime + nOneDay)) // 1 day margin
3036 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3039 // if detected invalid checkpoint enter safe mode
3040 if (Checkpoints::hashInvalidCheckpoint != 0)
3043 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3049 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3051 const CAlert& alert = item.second;
3052 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3054 nPriority = alert.nPriority;
3055 strStatusBar = alert.strStatusBar;
3056 if (nPriority > 1000)
3057 strRPC = strStatusBar;
3062 if (strFor == "statusbar")
3063 return strStatusBar;
3064 else if (strFor == "rpc")
3066 assert(!"GetWarnings() : invalid parameter");
3077 //////////////////////////////////////////////////////////////////////////////
3083 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3089 bool txInMap = false;
3092 txInMap = (mempool.exists(inv.hash));
3095 mapOrphanTransactions.count(inv.hash) ||
3096 txdb.ContainsTx(inv.hash);
3100 return mapBlockIndex.count(inv.hash) ||
3101 mapOrphanBlocks.count(inv.hash);
3103 // Don't know what it is, just say we already got one
3110 // The message start string is designed to be unlikely to occur in normal data.
3111 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3112 // a large 4-byte int at any alignment.
3113 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3115 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3117 static map<CService, CPubKey> mapReuseKey;
3118 RandAddSeedPerfmon();
3120 printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
3121 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3123 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3127 if (strCommand == "version")
3129 // Each connection can only send one version message
3130 if (pfrom->nVersion != 0)
3132 pfrom->Misbehaving(1);
3139 uint64_t nNonce = 1;
3140 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3141 if (pfrom->nVersion < MIN_PROTO_VERSION)
3143 // Since February 20, 2012, the protocol is initiated at version 209,
3144 // and earlier versions are no longer supported
3145 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3146 pfrom->fDisconnect = true;
3150 if (pfrom->nVersion == 10300)
3151 pfrom->nVersion = 300;
3153 vRecv >> addrFrom >> nNonce;
3155 vRecv >> pfrom->strSubVer;
3157 vRecv >> pfrom->nStartingHeight;
3159 if (pfrom->fInbound && addrMe.IsRoutable())
3161 pfrom->addrLocal = addrMe;
3165 // Disconnect if we connected to ourself
3166 if (nNonce == nLocalHostNonce && nNonce > 1)
3168 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3169 pfrom->fDisconnect = true;
3173 if (pfrom->nVersion < 60010)
3175 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3176 pfrom->fDisconnect = true;
3180 // record my external IP reported by peer
3181 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3182 addrSeenByPeer = addrMe;
3184 // Be shy and don't send version until we hear
3185 if (pfrom->fInbound)
3186 pfrom->PushVersion();
3188 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3190 AddTimeData(pfrom->addr, nTime);
3193 pfrom->PushMessage("verack");
3194 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3196 if (!pfrom->fInbound)
3198 // Advertise our address
3199 if (!fNoListen && !IsInitialBlockDownload())
3201 CAddress addr = GetLocalAddress(&pfrom->addr);
3202 if (addr.IsRoutable())
3203 pfrom->PushAddress(addr);
3206 // Get recent addresses
3207 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3209 pfrom->PushMessage("getaddr");
3210 pfrom->fGetAddr = true;
3212 addrman.Good(pfrom->addr);
3214 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3216 addrman.Add(addrFrom, addrFrom);
3217 addrman.Good(addrFrom);
3221 // Ask the first connected node for block updates
3222 static int nAskedForBlocks = 0;
3223 if (!pfrom->fClient && !pfrom->fOneShot &&
3224 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3225 (pfrom->nVersion < NOBLKS_VERSION_START ||
3226 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3227 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3230 pfrom->PushGetBlocks(pindexBest, uint256(0));
3236 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3237 item.second.RelayTo(pfrom);
3240 // Relay sync-checkpoint
3242 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3243 if (!Checkpoints::checkpointMessage.IsNull())
3244 Checkpoints::checkpointMessage.RelayTo(pfrom);
3247 pfrom->fSuccessfullyConnected = true;
3249 printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
3251 cPeerBlockCounts.input(pfrom->nStartingHeight);
3253 // ppcoin: ask for pending sync-checkpoint if any
3254 if (!IsInitialBlockDownload())
3255 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3259 else if (pfrom->nVersion == 0)
3261 // Must have a version message before anything else
3262 pfrom->Misbehaving(1);
3267 else if (strCommand == "verack")
3269 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3273 else if (strCommand == "addr")
3275 vector<CAddress> vAddr;
3278 // Don't want addr from older versions unless seeding
3279 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3281 if (vAddr.size() > 1000)
3283 pfrom->Misbehaving(20);
3284 return error("message addr size() = %" PRIszu "", vAddr.size());
3287 // Store the new addresses
3288 vector<CAddress> vAddrOk;
3289 int64_t nNow = GetAdjustedTime();
3290 int64_t nSince = nNow - 10 * 60;
3291 BOOST_FOREACH(CAddress& addr, vAddr)
3295 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3296 addr.nTime = nNow - 5 * nOneDay;
3297 pfrom->AddAddressKnown(addr);
3298 bool fReachable = IsReachable(addr);
3299 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3301 // Relay to a limited number of other nodes
3304 // Use deterministic randomness to send to the same nodes for 24 hours
3305 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3306 static uint256 hashSalt;
3308 hashSalt = GetRandHash();
3309 uint64_t hashAddr = addr.GetHash();
3310 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/nOneDay);
3311 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3312 multimap<uint256, CNode*> mapMix;
3313 BOOST_FOREACH(CNode* pnode, vNodes)
3315 if (pnode->nVersion < CADDR_TIME_VERSION)
3317 unsigned int nPointer;
3318 memcpy(&nPointer, &pnode, sizeof(nPointer));
3319 uint256 hashKey = hashRand ^ nPointer;
3320 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3321 mapMix.insert(make_pair(hashKey, pnode));
3323 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3324 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3325 ((*mi).second)->PushAddress(addr);
3328 // Do not store addresses outside our network
3330 vAddrOk.push_back(addr);
3332 addrman.Add(vAddrOk, pfrom->addr, 2 * nOneHour);
3333 if (vAddr.size() < 1000)
3334 pfrom->fGetAddr = false;
3335 if (pfrom->fOneShot)
3336 pfrom->fDisconnect = true;
3339 else if (strCommand == "inv")
3343 if (vInv.size() > MAX_INV_SZ)
3345 pfrom->Misbehaving(20);
3346 return error("message inv size() = %" PRIszu "", vInv.size());
3349 // find last block in inv vector
3350 unsigned int nLastBlock = std::numeric_limits<uint32_t>::max();
3351 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3352 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3353 nLastBlock = vInv.size() - 1 - nInv;
3358 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3360 const CInv &inv = vInv[nInv];
3364 pfrom->AddInventoryKnown(inv);
3366 bool fAlreadyHave = AlreadyHave(txdb, inv);
3368 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3372 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3373 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3374 } else if (nInv == nLastBlock) {
3375 // In case we are on a very long side-chain, it is possible that we already have
3376 // the last block in an inv bundle sent in response to getblocks. Try to detect
3377 // this situation and push another getblocks to continue.
3378 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3380 printf("force request: %s\n", inv.ToString().c_str());
3383 // Track requests for our stuff
3384 Inventory(inv.hash);
3389 else if (strCommand == "getdata")
3393 if (vInv.size() > MAX_INV_SZ)
3395 pfrom->Misbehaving(20);
3396 return error("message getdata size() = %" PRIszu "", vInv.size());
3399 if (fDebugNet || (vInv.size() != 1))
3400 printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
3402 BOOST_FOREACH(const CInv& inv, vInv)
3406 if (fDebugNet || (vInv.size() == 1))
3407 printf("received getdata for: %s\n", inv.ToString().c_str());
3409 if (inv.type == MSG_BLOCK)
3411 // Send block from disk
3412 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3413 if (mi != mapBlockIndex.end())
3416 block.ReadFromDisk((*mi).second);
3417 pfrom->PushMessage("block", block);
3419 // Trigger them to send a getblocks request for the next batch of inventory
3420 if (inv.hash == pfrom->hashContinue)
3422 // ppcoin: send latest proof-of-work block to allow the
3423 // download node to accept as orphan (proof-of-stake
3424 // block might be rejected by stake connection check)
3426 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3427 pfrom->PushMessage("inv", vInv);
3428 pfrom->hashContinue = 0;
3432 else if (inv.IsKnownType())
3434 // Send stream from relay memory
3435 bool pushed = false;
3438 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3439 if (mi != mapRelay.end()) {
3440 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3444 if (!pushed && inv.type == MSG_TX) {
3446 if (mempool.exists(inv.hash)) {
3447 CTransaction tx = mempool.lookup(inv.hash);
3448 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3451 pfrom->PushMessage("tx", ss);
3456 // Track requests for our stuff
3457 Inventory(inv.hash);
3462 else if (strCommand == "getblocks")
3464 CBlockLocator locator;
3466 vRecv >> locator >> hashStop;
3468 // Find the last block the caller has in the main chain
3469 CBlockIndex* pindex = locator.GetBlockIndex();
3471 // Send the rest of the chain
3473 pindex = pindex->pnext;
3475 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3476 for (; pindex; pindex = pindex->pnext)
3478 if (pindex->GetBlockHash() == hashStop)
3480 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3481 // ppcoin: tell downloading node about the latest block if it's
3482 // without risk being rejected due to stake connection check
3483 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3484 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3487 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3490 // When this block is requested, we'll send an inv that'll make them
3491 // getblocks the next batch of inventory.
3492 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3493 pfrom->hashContinue = pindex->GetBlockHash();
3498 else if (strCommand == "checkpoint")
3500 CSyncCheckpoint checkpoint;
3501 vRecv >> checkpoint;
3503 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3506 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3508 BOOST_FOREACH(CNode* pnode, vNodes)
3509 checkpoint.RelayTo(pnode);
3513 else if (strCommand == "getheaders")
3515 CBlockLocator locator;
3517 vRecv >> locator >> hashStop;
3519 CBlockIndex* pindex = NULL;
3520 if (locator.IsNull())
3522 // If locator is null, return the hashStop block
3523 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3524 if (mi == mapBlockIndex.end())
3526 pindex = (*mi).second;
3530 // Find the last block the caller has in the main chain
3531 pindex = locator.GetBlockIndex();
3533 pindex = pindex->pnext;
3536 vector<CBlock> vHeaders;
3538 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3539 for (; pindex; pindex = pindex->pnext)
3541 vHeaders.push_back(pindex->GetBlockHeader());
3542 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3545 pfrom->PushMessage("headers", vHeaders);
3549 else if (strCommand == "tx")
3551 vector<uint256> vWorkQueue;
3552 vector<uint256> vEraseQueue;
3553 CDataStream vMsg(vRecv);
3558 CInv inv(MSG_TX, tx.GetHash());
3559 pfrom->AddInventoryKnown(inv);
3561 bool fMissingInputs = false;
3562 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3564 SyncWithWallets(tx, NULL, true);
3565 RelayTransaction(tx, inv.hash);
3566 mapAlreadyAskedFor.erase(inv);
3567 vWorkQueue.push_back(inv.hash);
3568 vEraseQueue.push_back(inv.hash);
3570 // Recursively process any orphan transactions that depended on this one
3571 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3573 uint256 hashPrev = vWorkQueue[i];
3574 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3575 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3578 const uint256& orphanTxHash = *mi;
3579 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3580 bool fMissingInputs2 = false;
3582 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3584 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3585 SyncWithWallets(tx, NULL, true);
3586 RelayTransaction(orphanTx, orphanTxHash);
3587 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3588 vWorkQueue.push_back(orphanTxHash);
3589 vEraseQueue.push_back(orphanTxHash);
3591 else if (!fMissingInputs2)
3594 vEraseQueue.push_back(orphanTxHash);
3595 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3600 BOOST_FOREACH(uint256 hash, vEraseQueue)
3601 EraseOrphanTx(hash);
3603 else if (fMissingInputs)
3607 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3608 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3610 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3612 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3616 else if (strCommand == "block")
3620 uint256 hashBlock = block.GetHash();
3622 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3625 CInv inv(MSG_BLOCK, hashBlock);
3626 pfrom->AddInventoryKnown(inv);
3628 if (ProcessBlock(pfrom, &block))
3629 mapAlreadyAskedFor.erase(inv);
3630 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3634 // This asymmetric behavior for inbound and outbound connections was introduced
3635 // to prevent a fingerprinting attack: an attacker can send specific fake addresses
3636 // to users' AddrMan and later request them by sending getaddr messages.
3637 // Making users (which are behind NAT and can only make outgoing connections) ignore
3638 // getaddr message mitigates the attack.
3639 else if ((strCommand == "getaddr") && (pfrom->fInbound))
3641 // Don't return addresses older than nCutOff timestamp
3642 int64_t nCutOff = GetTime() - (nNodeLifespan * nOneDay);
3643 pfrom->vAddrToSend.clear();
3644 vector<CAddress> vAddr = addrman.GetAddr();
3645 BOOST_FOREACH(const CAddress &addr, vAddr)
3646 if(addr.nTime > nCutOff)
3647 pfrom->PushAddress(addr);
3651 else if (strCommand == "mempool")
3653 std::vector<uint256> vtxid;
3654 mempool.queryHashes(vtxid);
3656 for (unsigned int i = 0; i < vtxid.size(); i++) {
3657 CInv inv(MSG_TX, vtxid[i]);
3658 vInv.push_back(inv);
3659 if (i == (MAX_INV_SZ - 1))
3662 if (vInv.size() > 0)
3663 pfrom->PushMessage("inv", vInv);
3667 else if (strCommand == "checkorder")
3672 if (!GetBoolArg("-allowreceivebyip"))
3674 pfrom->PushMessage("reply", hashReply, 2, string(""));
3681 /// we have a chance to check the order here
3683 // Keep giving the same key to the same ip until they use it
3684 if (!mapReuseKey.count(pfrom->addr))
3685 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3687 // Send back approval of order and pubkey to use
3688 CScript scriptPubKey;
3689 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3690 pfrom->PushMessage("reply", hashReply, 0, scriptPubKey);
3694 else if (strCommand == "reply")
3699 CRequestTracker tracker;
3701 LOCK(pfrom->cs_mapRequests);
3702 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3703 if (mi != pfrom->mapRequests.end())
3705 tracker = (*mi).second;
3706 pfrom->mapRequests.erase(mi);
3709 if (!tracker.IsNull())
3710 tracker.fn(tracker.param1, vRecv);
3714 else if (strCommand == "ping")
3716 if (pfrom->nVersion > BIP0031_VERSION)
3720 // Echo the message back with the nonce. This allows for two useful features:
3722 // 1) A remote node can quickly check if the connection is operational
3723 // 2) Remote nodes can measure the latency of the network thread. If this node
3724 // is overloaded it won't respond to pings quickly and the remote node can
3725 // avoid sending us more work, like chain download requests.
3727 // The nonce stops the remote getting confused between different pings: without
3728 // it, if the remote node sends a ping once per second and this node takes 5
3729 // seconds to respond to each, the 5th ping the remote sends would appear to
3730 // return very quickly.
3731 pfrom->PushMessage("pong", nonce);
3736 else if (strCommand == "alert")
3741 uint256 alertHash = alert.GetHash();
3742 if (pfrom->setKnown.count(alertHash) == 0)
3744 if (alert.ProcessAlert())
3747 pfrom->setKnown.insert(alertHash);
3750 BOOST_FOREACH(CNode* pnode, vNodes)
3751 alert.RelayTo(pnode);
3755 // Small DoS penalty so peers that send us lots of
3756 // duplicate/expired/invalid-signature/whatever alerts
3757 // eventually get banned.
3758 // This isn't a Misbehaving(100) (immediate ban) because the
3759 // peer might be an older or different implementation with
3760 // a different signature key, etc.
3761 pfrom->Misbehaving(10);
3769 // Ignore unknown commands for extensibility
3773 // Update the last seen time for this node's address
3774 if (pfrom->fNetworkNode)
3775 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3776 AddressCurrentlyConnected(pfrom->addr);
3782 bool ProcessMessages(CNode* pfrom)
3784 CDataStream& vRecv = pfrom->vRecv;
3788 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3792 // (4) message start
3801 // Don't bother if send buffer is too full to respond anyway
3802 if (pfrom->vSend.size() >= SendBufferSize())
3805 // Scan for message start
3806 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3807 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3808 if (vRecv.end() - pstart < nHeaderSize)
3810 if ((int)vRecv.size() > nHeaderSize)
3812 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3813 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3817 if (pstart - vRecv.begin() > 0)
3818 printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
3819 vRecv.erase(vRecv.begin(), pstart);
3822 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3827 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3830 string strCommand = hdr.GetCommand();
3833 unsigned int nMessageSize = hdr.nMessageSize;
3834 if (nMessageSize > MAX_SIZE)
3836 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3839 if (nMessageSize > vRecv.size())
3841 // Rewind and wait for rest of message
3842 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3847 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3848 unsigned int nChecksum = 0;
3849 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3850 if (nChecksum != hdr.nChecksum)
3852 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3853 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3857 // Copy message to its own buffer
3858 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3859 vRecv.ignore(nMessageSize);
3867 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3872 catch (std::ios_base::failure& e)
3874 if (strstr(e.what(), "end of data"))
3876 // Allow exceptions from under-length message on vRecv
3877 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());
3879 else if (strstr(e.what(), "size too large"))
3881 // Allow exceptions from over-long size
3882 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3886 PrintExceptionContinue(&e, "ProcessMessages()");
3889 catch (std::exception& e) {
3890 PrintExceptionContinue(&e, "ProcessMessages()");
3892 PrintExceptionContinue(NULL, "ProcessMessages()");
3896 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3904 bool SendMessages(CNode* pto, bool fSendTrickle)
3906 TRY_LOCK(cs_main, lockMain);
3908 // Don't send anything until we get their version message
3909 if (pto->nVersion == 0)
3912 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3914 if (pto->nLastSend && GetTime() - pto->nLastSend > nPingInterval && pto->vSend.empty()) {
3916 if (pto->nVersion > BIP0031_VERSION)
3917 pto->PushMessage("ping", nonce);
3919 pto->PushMessage("ping");
3923 if (pto->fStartSync) {
3924 pto->fStartSync = false;
3925 pto->PushGetBlocks(pindexBest, uint256(0));
3928 // Resend wallet transactions that haven't gotten in a block yet
3929 ResendWalletTransactions();
3931 // Address refresh broadcast
3932 static int64_t nLastRebroadcast;
3933 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > nBroadcastInterval))
3937 BOOST_FOREACH(CNode* pnode, vNodes)
3939 // Periodically clear setAddrKnown to allow refresh broadcasts
3940 if (nLastRebroadcast)
3941 pnode->setAddrKnown.clear();
3943 // Rebroadcast our address
3946 CAddress addr = GetLocalAddress(&pnode->addr);
3947 if (addr.IsRoutable())
3948 pnode->PushAddress(addr);
3952 nLastRebroadcast = GetTime();
3960 vector<CAddress> vAddr;
3961 vAddr.reserve(pto->vAddrToSend.size());
3962 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3964 // returns true if wasn't already contained in the set
3965 if (pto->setAddrKnown.insert(addr).second)
3967 vAddr.push_back(addr);
3968 // receiver rejects addr messages larger than 1000
3969 if (vAddr.size() >= 1000)
3971 pto->PushMessage("addr", vAddr);
3976 pto->vAddrToSend.clear();
3978 pto->PushMessage("addr", vAddr);
3983 // Message: inventory
3986 vector<CInv> vInvWait;
3988 LOCK(pto->cs_inventory);
3989 vInv.reserve(pto->vInventoryToSend.size());
3990 vInvWait.reserve(pto->vInventoryToSend.size());
3991 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3993 if (pto->setInventoryKnown.count(inv))
3996 // trickle out tx inv to protect privacy
3997 if (inv.type == MSG_TX && !fSendTrickle)
3999 // 1/4 of tx invs blast to all immediately
4000 static uint256 hashSalt;
4002 hashSalt = GetRandHash();
4003 uint256 hashRand = inv.hash ^ hashSalt;
4004 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4005 bool fTrickleWait = ((hashRand & 3) != 0);
4007 // always trickle our own transactions
4011 if (GetTransaction(inv.hash, wtx))
4013 fTrickleWait = true;
4018 vInvWait.push_back(inv);
4023 // returns true if wasn't already contained in the set
4024 if (pto->setInventoryKnown.insert(inv).second)
4026 vInv.push_back(inv);
4027 if (vInv.size() >= 1000)
4029 pto->PushMessage("inv", vInv);
4034 pto->vInventoryToSend = vInvWait;
4037 pto->PushMessage("inv", vInv);
4043 vector<CInv> vGetData;
4044 int64_t nNow = GetTime() * 1000000;
4046 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4048 const CInv& inv = (*pto->mapAskFor.begin()).second;
4049 if (!AlreadyHave(txdb, inv))
4052 printf("sending getdata: %s\n", inv.ToString().c_str());
4053 vGetData.push_back(inv);
4054 if (vGetData.size() >= 1000)
4056 pto->PushMessage("getdata", vGetData);
4059 mapAlreadyAskedFor[inv] = nNow;
4061 pto->mapAskFor.erase(pto->mapAskFor.begin());
4063 if (!vGetData.empty())
4064 pto->PushMessage("getdata", vGetData);
4077 std::map<uint256, CBlockIndex*>::iterator it1 = mapBlockIndex.begin();
4078 for (; it1 != mapBlockIndex.end(); it1++)
4079 delete (*it1).second;
4080 mapBlockIndex.clear();
4083 std::map<uint256, CBlock*>::iterator it2 = mapOrphanBlocks.begin();
4084 for (; it2 != mapOrphanBlocks.end(); it2++)
4085 delete (*it2).second;
4086 mapOrphanBlocks.clear();
4088 // orphan transactions
4090 } instance_of_cmaincleanup;