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"
13 #include "zerocoin/Zerocoin.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
20 using namespace boost;
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
29 CCriticalSection cs_main;
32 unsigned int nTransactionsUpdated = 0;
34 map<uint256, CBlockIndex*> mapBlockIndex;
35 set<pair<COutPoint, unsigned int> > setStakeSeen;
36 libzerocoin::Params* ZCParams;
38 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
39 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
40 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
41 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
42 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
44 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
46 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as zero time weight
47 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
48 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
49 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
51 int nCoinbaseMaturity = 500;
52 CBlockIndex* pindexGenesisBlock = NULL;
55 uint256 nBestChainTrust = 0;
56 uint256 nBestInvalidTrust = 0;
58 uint256 hashBestChain = 0;
59 CBlockIndex* pindexBest = NULL;
60 int64 nTimeBestReceived = 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 nTransactionFee = MIN_TX_FEE;
79 int64 nMinimumInputValue = MIN_TX_FEE;
81 extern enum Checkpoints::CPMode CheckpointsMode;
83 //////////////////////////////////////////////////////////////////////////////
85 // dispatching functions
88 // These functions dispatch to one or all registered wallets
91 void RegisterWallet(CWallet* pwalletIn)
94 LOCK(cs_setpwalletRegistered);
95 setpwalletRegistered.insert(pwalletIn);
99 void UnregisterWallet(CWallet* pwalletIn)
102 LOCK(cs_setpwalletRegistered);
103 setpwalletRegistered.erase(pwalletIn);
107 // check whether the passed transaction is from us
108 bool static IsFromMe(CTransaction& tx)
110 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
111 if (pwallet->IsFromMe(tx))
116 // get the wallet transaction with the given hash (if it exists)
117 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
119 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
120 if (pwallet->GetTransaction(hashTx,wtx))
125 // erases transaction with the given hash from all wallets
126 void static EraseFromWallets(uint256 hash)
128 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
129 pwallet->EraseFromWallet(hash);
132 // make sure all wallets know about the given transaction, in the given block
133 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
137 // ppcoin: wallets need to refund inputs when disconnecting coinstake
138 if (tx.IsCoinStake())
140 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
141 if (pwallet->IsFromMe(tx))
142 pwallet->DisableTransaction(tx);
147 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
148 pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
151 // notify wallets about a new best chain
152 void static SetBestChain(const CBlockLocator& loc)
154 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
155 pwallet->SetBestChain(loc);
158 // notify wallets about an updated transaction
159 void static UpdatedTransaction(const uint256& hashTx)
161 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
162 pwallet->UpdatedTransaction(hashTx);
166 void static PrintWallets(const CBlock& block)
168 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
169 pwallet->PrintWallet(block);
172 // notify wallets about an incoming inventory (for request counts)
173 void static Inventory(const uint256& hash)
175 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
176 pwallet->Inventory(hash);
179 // ask wallets to resend their transactions
180 void ResendWalletTransactions()
182 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
183 pwallet->ResendWalletTransactions();
187 //////////////////////////////////////////////////////////////////////////////
189 // CCoinsView implementations
192 bool CCoinsView::GetCoins(uint256 txid, CCoins &coins) { return false; }
193 bool CCoinsView::SetCoins(uint256 txid, const CCoins &coins) { return false; }
194 bool CCoinsView::HaveCoins(uint256 txid) { return false; }
195 CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
196 bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
197 bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
199 CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
200 bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); }
201 bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
202 bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); }
203 CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
204 bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
205 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
207 bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
209 CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
211 bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) {
212 if (cacheCoins.count(txid)) {
213 coins = cacheCoins[txid];
216 if (base->GetCoins(txid, coins)) {
217 cacheCoins[txid] = coins;
223 // Select coins from read-only cache or database
224 bool CCoinsViewCache::GetCoinsReadOnly(uint256 txid, CCoins &coins) {
225 if (cacheCoins.count(txid)) {
226 coins = cacheCoins[txid]; // get from cache
229 if (cacheCoinsReadOnly.count(txid)) {
230 coins = cacheCoinsReadOnly[txid]; // get from read-only cache
233 if (base->GetCoins(txid, coins)) {
234 cacheCoinsReadOnly[txid] = coins; // save to read-only cache
240 std::map<uint256,CCoins>::iterator CCoinsViewCache::FetchCoins(uint256 txid) {
241 std::map<uint256,CCoins>::iterator it = cacheCoins.find(txid);
242 if (it != cacheCoins.end())
245 if (!base->GetCoins(txid,tmp))
247 std::pair<std::map<uint256,CCoins>::iterator,bool> ret = cacheCoins.insert(std::make_pair(txid, tmp));
251 CCoins &CCoinsViewCache::GetCoins(uint256 txid) {
252 std::map<uint256,CCoins>::iterator it = FetchCoins(txid);
253 assert(it != cacheCoins.end());
257 bool CCoinsViewCache::SetCoins(uint256 txid, const CCoins &coins) {
258 cacheCoins[txid] = coins;
262 bool CCoinsViewCache::HaveCoins(uint256 txid) {
263 return FetchCoins(txid) != cacheCoins.end();
266 CBlockIndex *CCoinsViewCache::GetBestBlock() {
267 if (pindexTip == NULL)
268 pindexTip = base->GetBestBlock();
272 bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
277 bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
278 for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
279 cacheCoins[it->first] = it->second;
284 bool CCoinsViewCache::Flush() {
285 cacheCoinsReadOnly.clear(); // purge read-only cache
287 bool fOk = base->BatchWrite(cacheCoins, pindexTip);
293 unsigned int CCoinsViewCache::GetCacheSize() {
294 return cacheCoins.size();
297 /** CCoinsView that brings transactions from a memorypool into view.
298 It does not check for spendings by memory pool transactions. */
299 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
301 bool CCoinsViewMemPool::GetCoins(uint256 txid, CCoins &coins) {
302 if (base->GetCoins(txid, coins))
304 if (mempool.exists(txid)) {
305 const CTransaction &tx = mempool.lookup(txid);
306 coins = CCoins(tx, MEMPOOL_HEIGHT, -1);
312 bool CCoinsViewMemPool::HaveCoins(uint256 txid) {
313 return mempool.exists(txid) || base->HaveCoins(txid);
316 CCoinsViewCache *pcoinsTip = NULL;
318 //////////////////////////////////////////////////////////////////////////////
320 // mapOrphanTransactions
323 bool AddOrphanTx(const CTransaction& tx)
325 uint256 hash = tx.GetHash();
326 if (mapOrphanTransactions.count(hash))
329 // Ignore big transactions, to avoid a
330 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
331 // large transaction with a missing parent then we assume
332 // it will rebroadcast it later, after the parent transaction(s)
333 // have been mined or received.
334 // 10,000 orphans, each of which is at most 5,000 bytes big is
335 // at most 500 megabytes of orphans:
337 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
341 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
345 mapOrphanTransactions[hash] = tx;
346 BOOST_FOREACH(const CTxIn& txin, tx.vin)
347 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
349 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
350 mapOrphanTransactions.size());
354 void static EraseOrphanTx(uint256 hash)
356 if (!mapOrphanTransactions.count(hash))
358 const CTransaction& tx = mapOrphanTransactions[hash];
359 BOOST_FOREACH(const CTxIn& txin, tx.vin)
361 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
362 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
363 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
365 mapOrphanTransactions.erase(hash);
368 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
370 unsigned int nEvicted = 0;
371 while (mapOrphanTransactions.size() > nMaxOrphans)
373 // Evict a random orphan:
374 uint256 randomhash = GetRandHash();
375 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
376 if (it == mapOrphanTransactions.end())
377 it = mapOrphanTransactions.begin();
378 EraseOrphanTx(it->first);
390 //////////////////////////////////////////////////////////////////////////////
395 bool CTransaction::IsStandard() const
397 if (nVersion > CTransaction::CURRENT_VERSION)
400 BOOST_FOREACH(const CTxIn& txin, vin)
402 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
403 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
404 // ~65-byte public keys, plus a few script ops.
405 if (txin.scriptSig.size() > 500)
407 if (!txin.scriptSig.IsPushOnly())
410 BOOST_FOREACH(const CTxOut& txout, vout) {
411 if (!::IsStandard(txout.scriptPubKey))
413 if (txout.nValue == 0)
420 // Check transaction inputs, and make sure any
421 // pay-to-script-hash transactions are evaluating IsStandard scripts
423 // Why bother? To avoid denial-of-service attacks; an attacker
424 // can submit a standard HASH... OP_EQUAL transaction,
425 // which will get accepted into blocks. The redemption
426 // script can be anything; an attacker could use a very
427 // expensive-to-check-upon-redemption script like:
428 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
430 bool CTransaction::AreInputsStandard(CCoinsViewCache& mapInputs) const
433 return true; // Coinbases don't use vin normally
435 for (unsigned int i = 0; i < vin.size(); i++)
437 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
439 vector<vector<unsigned char> > vSolutions;
440 txnouttype whichType;
441 // get the scriptPubKey corresponding to this input:
442 const CScript& prevScript = prev.scriptPubKey;
443 if (!Solver(prevScript, whichType, vSolutions))
445 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
446 if (nArgsExpected < 0)
449 // Transactions with extra stuff in their scriptSigs are
450 // non-standard. Note that this EvalScript() call will
451 // be quick, because if there are any operations
452 // beside "push data" in the scriptSig the
453 // IsStandard() call returns false
454 vector<vector<unsigned char> > stack;
455 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
458 if (whichType == TX_SCRIPTHASH)
462 CScript subscript(stack.back().begin(), stack.back().end());
463 vector<vector<unsigned char> > vSolutions2;
464 txnouttype whichType2;
465 if (!Solver(subscript, whichType2, vSolutions2))
467 if (whichType2 == TX_SCRIPTHASH)
471 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
474 nArgsExpected += tmpExpected;
477 if (stack.size() != (unsigned int)nArgsExpected)
485 CTransaction::GetLegacySigOpCount() const
487 unsigned int nSigOps = 0;
488 BOOST_FOREACH(const CTxIn& txin, vin)
490 nSigOps += txin.scriptSig.GetSigOpCount(false);
492 BOOST_FOREACH(const CTxOut& txout, vout)
494 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
500 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
510 if (pblock == NULL) {
512 if (pcoinsTip->GetCoins(GetHash(), coins)) {
513 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
515 if (!blockTmp.ReadFromDisk(pindex))
523 // Update the tx's hashBlock
524 hashBlock = pblock->GetHash();
526 // Locate the transaction
527 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
528 if (pblock->vtx[nIndex] == *(CTransaction*)this)
530 if (nIndex == (int)pblock->vtx.size())
532 vMerkleBranch.clear();
534 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
538 // Fill in merkle branch
539 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
543 // Is the tx in a block that's in the main chain
544 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
545 if (mi == mapBlockIndex.end())
547 CBlockIndex* pindex = (*mi).second;
548 if (!pindex || !pindex->IsInMainChain())
551 return pindexBest->nHeight - pindex->nHeight + 1;
554 bool CTransaction::CheckTransaction() const
556 // Basic checks that don't depend on any context
558 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
560 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
562 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
563 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
565 // Check for negative or overflow output values
567 for (unsigned int i = 0; i < vout.size(); i++)
569 const CTxOut& txout = vout[i];
570 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
571 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
573 // Enforce minimum output amount for user transactions until 1 May 2014 04:00:00 GMT
574 if (!fTestNet && !IsCoinBase() && !txout.IsEmpty() && nTime < OUTPUT_SWITCH_TIME && txout.nValue < MIN_TXOUT_AMOUNT)
575 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
577 if (txout.nValue > MAX_MONEY)
578 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
579 nValueOut += txout.nValue;
580 if (!MoneyRange(nValueOut))
581 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
584 // Check for duplicate inputs
585 set<COutPoint> vInOutPoints;
586 BOOST_FOREACH(const CTxIn& txin, vin)
588 if (vInOutPoints.count(txin.prevout))
590 vInOutPoints.insert(txin.prevout);
595 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
596 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
600 BOOST_FOREACH(const CTxIn& txin, vin)
601 if (txin.prevout.IsNull())
602 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
608 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
609 enum GetMinFee_mode mode, unsigned int nBytes) const
611 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
612 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
614 unsigned int nNewBlockSize = nBlockSize + nBytes;
615 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
617 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
618 if (nMinFee < nBaseFee)
620 BOOST_FOREACH(const CTxOut& txout, vout)
621 if (txout.nValue < CENT)
625 // Raise the price as the block approaches full
626 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
628 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
630 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
633 if (!MoneyRange(nMinFee))
638 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
642 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
644 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
645 while (it != mapNextTx.end() && it->first.hash == hashTx) {
646 coins.Spend(it->first.n); // and remove those outputs from coins
651 bool CTxMemPool::accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs)
654 *pfMissingInputs = false;
656 if (!tx.CheckTransaction())
657 return error("CTxMemPool::accept() : CheckTransaction failed");
659 // Coinbase is only valid in a block, not as a loose transaction
661 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
663 // Coinstake is also only valid in a block, not as a loose transaction
664 if (tx.IsCoinStake())
665 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
667 // To help v0.1.5 clients who would see it as a negative number
668 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
669 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
671 // Rather not work on nonstandard transactions (unless -testnet)
672 if (!fTestNet && !tx.IsStandard())
673 return error("CTxMemPool::accept() : nonstandard transaction type");
675 // is it already in the memory pool?
676 uint256 hash = tx.GetHash();
679 if (mapTx.count(hash))
683 // Check for conflicts with in-memory transactions
684 CTransaction* ptxOld = NULL;
685 for (unsigned int i = 0; i < tx.vin.size(); i++)
687 COutPoint outpoint = tx.vin[i].prevout;
688 if (mapNextTx.count(outpoint))
690 // Disable replacement feature for now
693 // Allow replacing with a newer version of the same transaction
696 ptxOld = mapNextTx[outpoint].ptx;
697 if (ptxOld->IsFinal())
699 if (!tx.IsNewerThan(*ptxOld))
701 for (unsigned int i = 0; i < tx.vin.size(); i++)
703 COutPoint outpoint = tx.vin[i].prevout;
704 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
713 CCoinsViewCache &view = *pcoinsTip;
715 // do we already have it?
716 if (view.HaveCoins(hash))
719 // do all inputs exist?
720 BOOST_FOREACH(const CTxIn txin, tx.vin) {
721 if (!view.HaveCoins(txin.prevout.hash)) {
723 *pfMissingInputs = true;
728 if (!tx.HaveInputs(view))
729 return error("CTxMemPool::accept() : inputs already spent");
731 // Check for non-standard pay-to-script-hash in inputs
732 if (!tx.AreInputsStandard(view) && !fTestNet)
733 return error("CTxMemPool::accept() : nonstandard transaction input");
735 // Note: if you modify this code to accept non-standard transactions, then
736 // you should add code here to check that the transaction does a
737 // reasonable number of ECDSA signature verifications.
739 int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
740 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
742 // Don't accept it if it can't get into a block
743 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY, nSize);
744 if (nFees < txMinFee)
745 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
746 hash.ToString().c_str(),
750 // Continuously rate-limit free transactions
751 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
752 // be annoying or make others' transactions take longer to confirm.
753 if (nFees < MIN_RELAY_TX_FEE)
755 static CCriticalSection cs;
756 static double dFreeCount;
757 static int64 nLastTime;
758 int64 nNow = GetTime();
762 // Use an exponentially decaying ~10-minute window:
763 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
765 // -limitfreerelay unit is thousand-bytes-per-minute
766 // At default rate it would take over a month to fill 1GB
767 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
768 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
770 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
775 // Check against previous transactions
776 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
777 if (!tx.CheckInputs(view, CS_ALWAYS, true, false))
779 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
783 // Store transaction in memory
788 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
791 addUnchecked(hash, tx);
794 ///// are we sure this is ok when loading transactions or restoring block txes
795 // If updated, erase old tx from wallet
797 EraseFromWallets(ptxOld->GetHash());
799 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
800 hash.ToString().substr(0,10).c_str(),
805 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
807 return mempool.accept(*this, fCheckInputs, pfMissingInputs);
810 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
812 // Add to memory pool without checking anything. Don't call this directly,
813 // call CTxMemPool::accept to properly check the transaction first.
816 for (unsigned int i = 0; i < tx.vin.size(); i++)
817 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
818 nTransactionsUpdated++;
824 bool CTxMemPool::remove(CTransaction &tx)
826 // Remove transaction from memory pool
829 uint256 hash = tx.GetHash();
830 if (mapTx.count(hash))
832 BOOST_FOREACH(const CTxIn& txin, tx.vin)
833 mapNextTx.erase(txin.prevout);
835 nTransactionsUpdated++;
841 void CTxMemPool::clear()
846 ++nTransactionsUpdated;
849 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
854 vtxid.reserve(mapTx.size());
855 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
856 vtxid.push_back((*mi).first);
862 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
864 if (hashBlock == 0 || nIndex == -1)
867 // Find the block it claims to be in
868 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
869 if (mi == mapBlockIndex.end())
871 CBlockIndex* pindex = (*mi).second;
872 if (!pindex || !pindex->IsInMainChain())
875 // Make sure the merkle branch connects to this block
876 if (!fMerkleVerified)
878 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
880 fMerkleVerified = true;
884 return pindexBest->nHeight - pindex->nHeight + 1;
887 int CMerkleTx::GetBlocksToMaturity() const
889 if (!(IsCoinBase() || IsCoinStake()))
891 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
895 bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs)
899 if (!IsInMainChain() && !ClientCheckInputs())
901 return CTransaction::AcceptToMemoryPool(false);
905 return CTransaction::AcceptToMemoryPool(fCheckInputs);
909 bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
914 // Add previous supporting transactions first
915 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
917 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
919 uint256 hash = tx.GetHash();
920 if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
921 tx.AcceptToMemoryPool(fCheckInputs);
924 return AcceptToMemoryPool(fCheckInputs);
929 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
930 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
932 CBlockIndex *pindexSlow = NULL;
937 if (mempool.exists(hash))
939 txOut = mempool.lookup(hash);
944 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
947 CCoinsViewCache &view = *pcoinsTip;
949 if (view.GetCoins(hash, coins))
950 nHeight = coins.nHeight;
953 pindexSlow = FindBlockByHeight(nHeight);
959 if (block.ReadFromDisk(pindexSlow)) {
960 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
961 if (tx.GetHash() == hash) {
963 hashBlock = pindexSlow->GetBlockHash();
974 //////////////////////////////////////////////////////////////////////////////
976 // CBlock and CBlockIndex
979 static CBlockIndex* pblockindexFBBHLast;
980 CBlockIndex* FindBlockByHeight(int nHeight)
982 CBlockIndex *pblockindex;
983 if (nHeight < nBestHeight / 2)
984 pblockindex = pindexGenesisBlock;
986 pblockindex = pindexBest;
987 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
988 pblockindex = pblockindexFBBHLast;
989 while (pblockindex->nHeight > nHeight)
990 pblockindex = pblockindex->pprev;
991 while (pblockindex->nHeight < nHeight)
992 pblockindex = pblockindex->pnext;
993 pblockindexFBBHLast = pblockindex;
997 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
999 if (!fReadTransactions)
1001 *this = pindex->GetBlockHeader();
1004 if (!ReadFromDisk(pindex->GetBlockPos(), fReadTransactions))
1006 if (GetHash() != pindex->GetBlockHash())
1007 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
1011 uint256 static GetOrphanRoot(const CBlock* pblock)
1013 // Work back to the first block in the orphan chain
1014 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
1015 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
1016 return pblock->GetHash();
1019 // ppcoin: find block wanted by given orphan block
1020 uint256 WantedByOrphan(const CBlock* pblockOrphan)
1022 // Work back to the first block in the orphan chain
1023 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
1024 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
1025 return pblockOrphan->hashPrevBlock;
1028 // select stake target limit according to hard-coded conditions
1029 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1031 if(fTestNet) // separate proof of stake target limit for testnet
1032 return bnProofOfStakeLimit;
1033 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1034 return bnProofOfStakeLimit;
1035 if(nHeight + 1 > 15000) // 24 bits since block 15000
1036 return bnProofOfStakeLegacyLimit;
1037 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1038 return bnProofOfStakeHardLimit;
1040 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1043 // miner's coin base reward based on nBits
1044 int64 GetProofOfWorkReward(unsigned int nBits)
1046 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1049 bnTarget.SetCompact(nBits);
1050 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1051 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1053 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1054 // A reasonably continuous curve is used to avoid shock to market
1055 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1057 // Human readable form:
1059 // nSubsidy = 100 / (diff ^ 1/6)
1060 CBigNum bnLowerBound = CENT;
1061 CBigNum bnUpperBound = bnSubsidyLimit;
1062 while (bnLowerBound + CENT <= bnUpperBound)
1064 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1065 if (fDebug && GetBoolArg("-printcreation"))
1066 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1067 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1068 bnUpperBound = bnMidValue;
1070 bnLowerBound = bnMidValue;
1073 int64 nSubsidy = bnUpperBound.getuint64();
1075 nSubsidy = (nSubsidy / CENT) * CENT;
1076 if (fDebug && GetBoolArg("-printcreation"))
1077 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1079 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
1082 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1083 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
1085 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1087 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1089 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1091 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1093 bnTarget.SetCompact(nBits);
1094 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1095 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1097 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1099 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1100 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1101 bnMidPart, bnRewardPart;
1103 while (bnLowerBound + CENT <= bnUpperBound)
1105 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1106 if (fDebug && GetBoolArg("-printcreation"))
1107 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1109 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1112 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1114 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1116 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1119 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1120 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1125 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1127 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1129 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1132 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1133 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1136 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1137 bnUpperBound = bnMidValue;
1139 bnLowerBound = bnMidValue;
1142 nRewardCoinYear = bnUpperBound.getuint64();
1143 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1147 // Old creation amount per coin-year, 5% fixed stake mint rate
1148 nRewardCoinYear = 5 * CENT;
1152 return nRewardCoinYear;
1154 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1156 // Set reasonable reward limit for large inputs since 20 Oct 2013
1158 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1159 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1161 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1162 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1164 nSubsidy = min(nSubsidy, nSubsidyLimit);
1167 if (fDebug && GetBoolArg("-printcreation"))
1168 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1172 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1174 // get proof of work blocks max spacing according to hard-coded conditions
1175 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1177 if(nTime > TARGETS_SWITCH_TIME)
1178 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1181 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1183 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1187 // maximum nBits value could possible be required nTime after
1189 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1192 bnResult.SetCompact(nBase);
1194 while (nTime > 0 && bnResult < bnTargetLimit)
1196 // Maximum 200% adjustment per day...
1198 nTime -= 24 * 60 * 60;
1200 if (bnResult > bnTargetLimit)
1201 bnResult = bnTargetLimit;
1202 return bnResult.GetCompact();
1206 // minimum amount of work that could possibly be required nTime after
1207 // minimum proof-of-work required was nBase
1209 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1211 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1215 // minimum amount of stake that could possibly be required nTime after
1216 // minimum proof-of-stake required was nBase
1218 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1220 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1224 // ppcoin: find last block index up to pindex
1225 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1227 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1228 pindex = pindex->pprev;
1232 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1234 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1236 if (pindexLast == NULL)
1237 return bnTargetLimit.GetCompact(); // genesis block
1239 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1240 if (pindexPrev->pprev == NULL)
1241 return bnTargetLimit.GetCompact(); // first block
1242 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1243 if (pindexPrevPrev->pprev == NULL)
1244 return bnTargetLimit.GetCompact(); // second block
1246 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1248 // ppcoin: target change every block
1249 // ppcoin: retarget with exponential moving toward target spacing
1251 bnNew.SetCompact(pindexPrev->nBits);
1252 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1253 int64 nInterval = nTargetTimespan / nTargetSpacing;
1254 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1255 bnNew /= ((nInterval + 1) * nTargetSpacing);
1257 if (bnNew > bnTargetLimit)
1258 bnNew = bnTargetLimit;
1260 return bnNew.GetCompact();
1263 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1266 bnTarget.SetCompact(nBits);
1269 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1270 return error("CheckProofOfWork() : nBits below minimum work");
1272 // Check proof of work matches claimed amount
1273 if (hash > bnTarget.getuint256())
1274 return error("CheckProofOfWork() : hash doesn't match nBits");
1279 // Return maximum amount of blocks that other nodes claim to have
1280 int GetNumBlocksOfPeers()
1282 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1285 bool IsInitialBlockDownload()
1287 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1289 static int64 nLastUpdate;
1290 static CBlockIndex* pindexLastBest;
1291 if (pindexBest != pindexLastBest)
1293 pindexLastBest = pindexBest;
1294 nLastUpdate = GetTime();
1296 return (GetTime() - nLastUpdate < 10 &&
1297 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1300 void static InvalidChainFound(CBlockIndex* pindexNew)
1302 if (pindexNew->nChainTrust > nBestInvalidTrust)
1304 nBestInvalidTrust = pindexNew->nChainTrust;
1305 CChainDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1306 uiInterface.NotifyBlocksChanged();
1309 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1310 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1312 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1313 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1314 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1315 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1316 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1317 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1318 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1319 nBestBlockTrust.Get64(),
1320 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1324 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1326 nTime = max(GetBlockTime(), GetAdjustedTime());
1329 const CTxOut &CTransaction::GetOutputFor(const CTxIn& input, CCoinsViewCache& view)
1331 const CCoins &coins = view.GetCoins(input.prevout.hash);
1332 assert(coins.IsAvailable(input.prevout.n));
1333 return coins.vout[input.prevout.n];
1336 int64 CTransaction::GetValueIn(CCoinsViewCache& inputs) const
1342 for (unsigned int i = 0; i < vin.size(); i++)
1343 nResult += GetOutputFor(vin[i], inputs).nValue;
1348 unsigned int CTransaction::GetP2SHSigOpCount(CCoinsViewCache& inputs) const
1353 unsigned int nSigOps = 0;
1354 for (unsigned int i = 0; i < vin.size(); i++)
1356 const CTxOut &prevout = GetOutputFor(vin[i], inputs);
1357 if (prevout.scriptPubKey.IsPayToScriptHash())
1358 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1363 bool CTransaction::UpdateCoins(CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, unsigned int nTimeStamp, const uint256 &txhash) const
1365 // mark inputs spent
1366 if (!IsCoinBase()) {
1367 BOOST_FOREACH(const CTxIn &txin, vin) {
1368 CCoins &coins = inputs.GetCoins(txin.prevout.hash);
1369 if (coins.nTime > nTimeStamp)
1370 return error("UpdateCoins() : timestamp violation");
1372 if (!coins.Spend(txin.prevout, undo))
1373 return error("UpdateCoins() : cannot spend input");
1374 txundo.vprevout.push_back(undo);
1379 if (!inputs.SetCoins(txhash, CCoins(*this, nHeight, nTimeStamp)))
1380 return error("UpdateCoins() : cannot update output");
1385 bool CTransaction::HaveInputs(CCoinsViewCache &inputs) const
1387 if (!IsCoinBase()) {
1388 // first check whether information about the prevout hash is available
1389 for (unsigned int i = 0; i < vin.size(); i++) {
1390 const COutPoint &prevout = vin[i].prevout;
1391 if (!inputs.HaveCoins(prevout.hash))
1395 // then check whether the actual outputs are available
1396 for (unsigned int i = 0; i < vin.size(); i++) {
1397 const COutPoint &prevout = vin[i].prevout;
1398 const CCoins &coins = inputs.GetCoins(prevout.hash);
1399 if (!coins.IsAvailable(prevout.n))
1406 bool CTransaction::CheckInputs(CCoinsViewCache &inputs, enum CheckSig_mode csmode, bool fStrictPayToScriptHash, bool fStrictEncodings, CBlock *pblock) const
1410 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1411 // for an attacker to attempt to split the network.
1412 if (!HaveInputs(inputs))
1413 return error("CheckInputs() : %s inputs unavailable", GetHash().ToString().substr(0,10).c_str());
1415 CBlockIndex *pindexBlock = inputs.GetBestBlock();
1418 for (unsigned int i = 0; i < vin.size(); i++)
1420 const COutPoint &prevout = vin[i].prevout;
1421 const CCoins &coins = inputs.GetCoins(prevout.hash);
1423 // If prev is coinbase or coinstake, check that it's matured
1424 if (coins.IsCoinBase() || coins.IsCoinStake()) {
1425 if (pindexBlock->nHeight - coins.nHeight < nCoinbaseMaturity)
1426 return error("CheckInputs() : tried to spend %s at depth %d", coins.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - coins.nHeight);
1429 // Check transaction timestamp
1430 if (coins.nTime > nTime)
1431 return DoS(100, error("CheckInputs() : transaction timestamp earlier than input transaction"));
1433 // Check for negative or overflow input values
1434 nValueIn += coins.vout[prevout.n].nValue;
1435 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1436 return DoS(100, error("CheckInputs() : txin values out of range"));
1442 return error("CheckInputs() : %s is a coinstake, but no block specified", GetHash().ToString().substr(0,10).c_str());
1444 // Coin stake tx earns reward instead of paying fee
1446 if (!GetCoinAge(nCoinAge))
1447 return error("CheckInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1449 int64 nStakeReward = GetValueOut() - nValueIn;
1450 int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pblock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1452 if (nStakeReward > nCalculatedStakeReward)
1453 return DoS(100, error("CheckInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1457 if (nValueIn < GetValueOut())
1458 return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1460 // Tally transaction fees
1461 int64 nTxFee = nValueIn - GetValueOut();
1463 return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1465 if (!MoneyRange(nFees))
1466 return DoS(100, error("CheckInputs() : nFees out of range"));
1468 // enforce transaction fees for every block until 1 May 2014 04:00:00 GMT
1469 if (!fTestNet && nTxFee < GetMinFee() && nTime < OUTPUT_SWITCH_TIME)
1470 return pblock? DoS(100, error("CheckInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false;
1473 // The first loop above does all the inexpensive checks.
1474 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1475 // Helps prevent CPU exhaustion attacks.
1477 // Skip ECDSA signature verification when connecting blocks
1478 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1479 // still computed and checked, and any change will be caught at the next checkpoint.
1480 if (csmode == CS_ALWAYS ||
1481 (csmode == CS_AFTER_CHECKPOINT && inputs.GetBestBlock()->nHeight >= Checkpoints::GetTotalBlocksEstimate())) {
1482 for (unsigned int i = 0; i < vin.size(); i++) {
1483 const COutPoint &prevout = vin[i].prevout;
1484 const CCoins &coins = inputs.GetCoins(prevout.hash);
1487 if (!VerifySignature(coins, *this, i, fStrictPayToScriptHash, fStrictEncodings, 0)) {
1488 // only during transition phase for P2SH: do not invoke anti-DoS code for
1489 // potentially old clients relaying bad P2SH transactions
1490 if (fStrictPayToScriptHash && VerifySignature(coins, *this, i, false, fStrictEncodings, 0))
1491 return error("CheckInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1493 return DoS(100,error("CheckInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1503 bool CTransaction::ClientCheckInputs() const
1508 // Take over previous transactions' spent pointers
1512 for (unsigned int i = 0; i < vin.size(); i++)
1514 // Get prev tx from single transactions in memory
1515 COutPoint prevout = vin[i].prevout;
1516 if (!mempool.exists(prevout.hash))
1518 CTransaction& txPrev = mempool.lookup(prevout.hash);
1520 if (prevout.n >= txPrev.vout.size())
1524 if (!VerifySignature(CCoins(txPrev, -1, -1), *this, i, true, false, 0))
1525 return error("ConnectInputs() : VerifySignature failed");
1527 ///// this is redundant with the mempool.mapNextTx stuff,
1528 ///// not sure which I want to get rid of
1529 ///// this has to go away now that posNext is gone
1530 // // Check for conflicts
1531 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1532 // return error("ConnectInputs() : prev tx already used");
1534 // // Flag outpoints as used
1535 // txPrev.vout[prevout.n].posNext = posThisTx;
1537 nValueIn += txPrev.vout[prevout.n].nValue;
1539 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1540 return error("ClientConnectInputs() : txin values out of range");
1542 if (GetValueOut() > nValueIn)
1549 bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsViewCache &view)
1551 assert(pindex == view.GetBestBlock());
1553 CBlockUndo blockUndo;
1555 CDiskBlockPos pos = pindex->GetUndoPos();
1557 return error("DisconnectBlock() : no undo data available");
1558 FILE *file = OpenUndoFile(pos, true);
1560 return error("DisconnectBlock() : undo file not available");
1561 CAutoFile fileUndo(file, SER_DISK, CLIENT_VERSION);
1562 fileUndo >> blockUndo;
1565 assert(blockUndo.vtxundo.size() + 1 == vtx.size());
1567 // undo transactions in reverse order
1568 for (int i = vtx.size() - 1; i >= 0; i--) {
1569 const CTransaction &tx = vtx[i];
1570 uint256 hash = tx.GetHash();
1572 // don't check coinbase coins for proof-of-stake block
1573 if(IsProofOfStake() && tx.IsCoinBase())
1576 // check that all outputs are available
1577 if (!view.HaveCoins(hash))
1578 return error("DisconnectBlock() : outputs still spent? database corrupted");
1579 CCoins &outs = view.GetCoins(hash);
1581 CCoins outsBlock = CCoins(tx, pindex->nHeight, pindex->nTime);
1582 if (outs != outsBlock)
1583 return error("DisconnectBlock() : added transaction mismatch? database corrupted");
1589 if (i > 0) { // not coinbases
1590 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1591 assert(txundo.vprevout.size() == tx.vin.size());
1592 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1593 const COutPoint &out = tx.vin[j].prevout;
1594 const CTxInUndo &undo = txundo.vprevout[j];
1596 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1597 if (coins.IsPruned()) {
1598 if (undo.nHeight == 0)
1599 return error("DisconnectBlock() : undo data doesn't contain tx metadata? database corrupted");
1600 coins.fCoinBase = undo.fCoinBase;
1601 coins.fCoinStake = undo.fCoinStake;
1602 coins.nHeight = undo.nHeight;
1603 coins.nTime = undo.nTime;
1604 coins.nBlockTime = undo.nBlockTime;
1605 coins.nVersion = undo.nVersion;
1607 if (undo.nHeight != 0)
1608 return error("DisconnectBlock() : undo data contains unneeded tx metadata? database corrupted");
1610 if (coins.IsAvailable(out.n))
1611 return error("DisconnectBlock() : prevout output not spent? database corrupted");
1612 if (coins.vout.size() < out.n+1)
1613 coins.vout.resize(out.n+1);
1614 coins.vout[out.n] = undo.txout;
1615 if (!view.SetCoins(out.hash, coins))
1616 return error("DisconnectBlock() : cannot restore coin inputs");
1621 // move best block pointer to prevout block
1622 view.SetBestBlock(pindex->pprev);
1627 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1629 bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsViewCache &view, bool fJustCheck)
1631 // Check it again in case a previous version let a bad block in
1632 if (!CheckBlock(!fJustCheck, !fJustCheck))
1635 // verify that the view's current state corresponds to the previous block
1636 assert(pindex->pprev == view.GetBestBlock());
1638 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1639 // unless those are already completely spent.
1640 // If such overwrites are allowed, coinbases and transactions depending upon those
1641 // can be duplicated to remove the ability to spend the first instance -- even after
1642 // being sent to another address.
1643 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1644 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1645 // already refuses previously-known transaction ids entirely.
1646 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1647 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1648 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1649 // initial block download.
1650 bool fEnforceBIP30 = true;
1652 if (fEnforceBIP30) {
1653 for (unsigned int i=0; i<vtx.size(); i++) {
1654 uint256 hash = GetTxHash(i);
1655 if (view.HaveCoins(hash) && !view.GetCoins(hash).IsPruned())
1656 return error("ConnectBlock() : tried to overwrite transaction");
1660 // BIP16 always active
1661 bool fStrictPayToScriptHash = true;
1663 CBlockUndo blockundo;
1665 int64 nFees = 0, nValueIn = 0, nValueOut = 0;
1666 unsigned int nSigOps = 0;
1667 for (unsigned int i=0; i<vtx.size(); i++)
1669 const CTransaction &tx = vtx[i];
1670 nSigOps += tx.GetLegacySigOpCount();
1671 if (nSigOps > MAX_BLOCK_SIGOPS)
1672 return DoS(100, error("ConnectBlock() : too many sigops"));
1674 if (!tx.IsCoinBase())
1676 if (!tx.HaveInputs(view))
1677 return DoS(100, error("ConnectBlock() : inputs missing/spent"));
1679 if (fStrictPayToScriptHash)
1681 // Add in sigops done by pay-to-script-hash inputs;
1682 // this is to prevent a "rogue miner" from creating
1683 // an incredibly-expensive-to-validate block.
1684 nSigOps += tx.GetP2SHSigOpCount(view);
1685 if (nSigOps > MAX_BLOCK_SIGOPS)
1686 return DoS(100, error("ConnectBlock() : too many sigops"));
1689 int64 nTxValueOut = tx.GetValueOut();
1690 int64 nTxValueIn = tx.GetValueIn(view);
1692 nValueIn += nTxValueIn;
1693 nValueOut += nTxValueOut;
1695 if (!tx.IsCoinStake())
1696 nFees += nTxValueIn - nTxValueOut;
1698 if (!tx.CheckInputs(view, CS_AFTER_CHECKPOINT, fStrictPayToScriptHash, false, this))
1703 nValueOut += tx.GetValueOut();
1706 // don't create coinbase coins for proof-of-stake block
1707 if(IsProofOfStake() && tx.IsCoinBase())
1711 if (!tx.UpdateCoins(view, txundo, pindex->nHeight, pindex->nTime, GetTxHash(i)))
1712 return error("ConnectBlock() : UpdateInputs failed");
1713 if (!tx.IsCoinBase())
1714 blockundo.vtxundo.push_back(txundo);
1717 pindex->nMint = nValueOut - nValueIn + nFees;
1718 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1726 // Write undo information to disk
1727 if (pindex->GetUndoPos().IsNull())
1729 if (!FindUndoPos(chaindb, pindex->pos.nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 8))
1730 return error("ConnectBlock() : FindUndoPos failed");
1731 if (!blockundo.WriteToDisk(pos))
1732 return error("ConnectBlock() : CBlockUndo::WriteToDisk failed");
1734 // update nUndoPos in block index
1735 pindex->nUndoPos = pos.nPos + 1;
1738 CDiskBlockIndex blockindex(pindex);
1739 if (!chaindb.WriteBlockIndex(blockindex))
1740 return error("ConnectBlock() : WriteBlockIndex failed");
1742 // add this block to the view's blockchain
1743 if (!view.SetBestBlock(pindex))
1746 // fees are destroyed to compensate the entire network
1747 if (fDebug && GetBoolArg("-printcreation"))
1748 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1750 // Watch for transactions paying to me
1751 for (unsigned int i=0; i<vtx.size(); i++)
1752 SyncWithWallets(GetTxHash(i), vtx[i], this, true);
1757 bool CBlock::SetBestChain(CBlockIndex* pindexNew)
1759 CCoinsViewCache &view = *pcoinsTip;
1761 // special case for attaching the genesis block
1762 // note that no ConnectBlock is called, so its coinbase output is non-spendable
1763 if (pindexGenesisBlock == NULL && pindexNew->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1765 view.SetBestBlock(pindexNew);
1768 pindexGenesisBlock = pindexNew;
1769 pindexBest = pindexNew;
1770 hashBestChain = pindexNew->GetBlockHash();
1771 nBestHeight = pindexBest->nHeight;
1772 nBestChainTrust = pindexNew->nChainTrust;
1776 // Find the fork (typically, there is none)
1777 CBlockIndex* pfork = view.GetBestBlock();
1778 CBlockIndex* plonger = pindexNew;
1779 while (pfork != plonger)
1781 while (plonger->nHeight > pfork->nHeight)
1782 if (!(plonger = plonger->pprev))
1783 return error("SetBestChain() : plonger->pprev is null");
1784 if (pfork == plonger)
1786 if (!(pfork = pfork->pprev))
1787 return error("SetBestChain() : pfork->pprev is null");
1790 // List of what to disconnect (typically nothing)
1791 vector<CBlockIndex*> vDisconnect;
1792 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1793 vDisconnect.push_back(pindex);
1795 // List of what to connect (typically only pindexNew)
1796 vector<CBlockIndex*> vConnect;
1797 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1798 vConnect.push_back(pindex);
1799 reverse(vConnect.begin(), vConnect.end());
1801 if (vDisconnect.size() > 0) {
1802 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());
1803 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());
1806 // Disconnect shorter branch
1807 vector<CTransaction> vResurrect;
1808 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
1810 if (!block.ReadFromDisk(pindex))
1811 return error("SetBestBlock() : ReadFromDisk for disconnect failed");
1812 CCoinsViewCache viewTemp(view, true);
1813 if (!block.DisconnectBlock(pindex, viewTemp))
1814 return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1815 if (!viewTemp.Flush())
1816 return error("SetBestBlock() : Cache flush failed after disconnect");
1818 // Queue memory transactions to resurrect
1819 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1820 if (!tx.IsCoinBase() && !tx.IsCoinStake())
1821 vResurrect.push_back(tx);
1824 // Connect longer branch
1825 vector<CTransaction> vDelete;
1826 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
1829 if (pindex == pindexNew) // connecting *this block
1831 else { // other block; read it from disk
1832 if (!block.ReadFromDisk(pindex))
1833 return error("SetBestBlock() : ReadFromDisk for connect failed");
1836 CCoinsViewCache viewTemp(view, true);
1837 if (!pblock->ConnectBlock(pindex, viewTemp)) {
1838 InvalidChainFound(pindexNew);
1839 return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1841 if (!viewTemp.Flush())
1842 return error("SetBestBlock() : Cache flush failed after connect");
1844 // Queue memory transactions to delete
1845 BOOST_FOREACH(const CTransaction& tx, pblock->vtx)
1846 vDelete.push_back(tx);
1849 // Make sure it's successfully written to disk before changing memory structure
1850 bool fIsInitialDownload = IsInitialBlockDownload();
1851 if (!fIsInitialDownload || view.GetCacheSize()>5000)
1855 // At this point, all changes have been done to the database.
1856 // Proceed by updating the memory structures.
1858 // Disconnect shorter branch
1859 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1861 pindex->pprev->pnext = NULL;
1863 // Connect longer branch
1864 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1866 pindex->pprev->pnext = pindex;
1868 // Resurrect memory transactions that were in the disconnected branch
1869 BOOST_FOREACH(CTransaction& tx, vResurrect)
1870 tx.AcceptToMemoryPool(false);
1872 // Delete redundant memory transactions that are in the connected branch
1873 BOOST_FOREACH(CTransaction& tx, vDelete)
1876 // Update best block in wallet (so we can detect restored wallets)
1877 if (!fIsInitialDownload)
1879 const CBlockLocator locator(pindexNew);
1880 ::SetBestChain(locator);
1884 hashBestChain = pindexNew->GetBlockHash();
1885 pindexBest = pindexNew;
1886 pblockindexFBBHLast = NULL;
1887 nBestHeight = pindexBest->nHeight;
1888 nBestChainTrust = pindexNew->nChainTrust;
1889 nTimeBestReceived = GetTime();
1890 nTransactionsUpdated++;
1892 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1894 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1895 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1896 CBigNum(nBestChainTrust).ToString().c_str(),
1897 nBestBlockTrust.Get64(),
1898 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1900 // Check the version of the last 100 blocks to see if we need to upgrade:
1901 if (!fIsInitialDownload)
1904 const CBlockIndex* pindex = pindexBest;
1905 for (int i = 0; i < 100 && pindex != NULL; i++)
1907 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1909 pindex = pindex->pprev;
1912 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1913 if (nUpgraded > 100/2)
1914 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1915 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1918 std::string strCmd = GetArg("-blocknotify", "");
1920 if (!fIsInitialDownload && !strCmd.empty())
1922 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1923 boost::thread t(runCommand, strCmd); // thread runs free
1929 // Total coin age spent in transaction, in the unit of coin-days.
1930 // Only those coins meeting minimum age requirement counts. As those
1931 // transactions not in main chain are not currently indexed so we
1932 // might not find out about their coin age. Older transactions are
1933 // guaranteed to be in main chain by sync-checkpoint. This rule is
1934 // introduced to help nodes establish a consistent view of the coin
1935 // age (trust score) of competing branches.
1936 bool CTransaction::GetCoinAge(uint64& nCoinAge) const
1938 CCoinsViewCache &inputs = *pcoinsTip;
1940 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1946 for (unsigned int i = 0; i < vin.size(); i++)
1948 const COutPoint &prevout = vin[i].prevout;
1950 if (!inputs.GetCoins(prevout.hash, coins))
1953 if (nTime < coins.nTime)
1954 return false; // Transaction timestamp violation
1956 // only count coins meeting min age requirement
1957 if (coins.nBlockTime + nStakeMinAge > nTime)
1960 int64 nValueIn = coins.vout[vin[i].prevout.n].nValue;
1961 bnCentSecond += CBigNum(nValueIn) * (nTime-coins.nTime) / CENT;
1964 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1965 if (fDebug && GetBoolArg("-printcoinage"))
1966 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1967 nCoinAge = bnCoinDay.getuint64();
1971 // Total coin age spent in block, in the unit of coin-days.
1972 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1976 BOOST_FOREACH(const CTransaction& tx, vtx)
1979 if (tx.GetCoinAge(nTxCoinAge))
1980 nCoinAge += nTxCoinAge;
1985 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1987 if (fDebug && GetBoolArg("-printcoinage"))
1988 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1992 bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
1994 // Check for duplicate
1995 uint256 hash = GetHash();
1996 if (mapBlockIndex.count(hash))
1997 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1999 // Construct new block index object
2000 CBlockIndex* pindexNew = new CBlockIndex(*this);
2002 return error("AddToBlockIndex() : new CBlockIndex failed");
2003 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2004 pindexNew->phashBlock = &((*mi).first);
2005 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2006 if (miPrev != mapBlockIndex.end())
2008 pindexNew->pprev = (*miPrev).second;
2009 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2011 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2012 pindexNew->pos = pos;
2013 pindexNew->nUndoPos = 0;
2015 // Compute stake entropy bit for stake modifier
2016 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2017 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2019 // Record proof-of-stake hash value
2020 if (pindexNew->IsProofOfStake())
2022 if (!mapProofOfStake.count(hash))
2023 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2024 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2027 // Compute stake modifier
2028 uint64 nStakeModifier = 0;
2029 bool fGeneratedStakeModifier = false;
2030 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2031 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2032 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2033 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2034 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2035 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2038 if (!chaindb.TxnBegin())
2040 chaindb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2041 if (!chaindb.TxnCommit())
2045 if (!SetBestChain(pindexNew))
2048 if (pindexNew == pindexBest)
2050 // Notify UI to display prev block's coinbase if it was ours
2051 static uint256 hashPrevBestCoinBase;
2052 UpdatedTransaction(hashPrevBestCoinBase);
2053 hashPrevBestCoinBase = GetTxHash(0);
2056 uiInterface.NotifyBlocksChanged();
2060 bool FindBlockPos(CChainDB &chaindb, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime)
2062 bool fUpdatedLast = false;
2064 LOCK(cs_LastBlockFile);
2066 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2067 printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
2068 FILE *file = OpenBlockFile(pos);
2071 file = OpenUndoFile(pos);
2075 infoLastBlockFile.SetNull();
2076 chaindb.ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
2077 fUpdatedLast = true;
2080 pos.nFile = nLastBlockFile;
2081 pos.nPos = infoLastBlockFile.nSize;
2082 infoLastBlockFile.nSize += nAddSize;
2083 infoLastBlockFile.AddBlock(nHeight, nTime);
2085 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2086 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2087 if (nNewChunks > nOldChunks) {
2088 FILE *file = OpenBlockFile(pos);
2090 printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2091 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2096 if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2097 return error("FindBlockPos() : cannot write updated block info");
2099 chaindb.WriteLastBlockFile(nLastBlockFile);
2104 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2108 LOCK(cs_LastBlockFile);
2110 unsigned int nNewSize;
2111 if (nFile == nLastBlockFile) {
2112 pos.nPos = infoLastBlockFile.nUndoSize;
2113 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2114 if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2115 return error("FindUndoPos() : cannot write updated block info");
2117 CBlockFileInfo info;
2118 if (!chaindb.ReadBlockFileInfo(nFile, info))
2119 return error("FindUndoPos() : cannot read block info");
2120 pos.nPos = info.nUndoSize;
2121 nNewSize = (info.nUndoSize += nAddSize);
2122 if (!chaindb.WriteBlockFileInfo(nFile, info))
2123 return error("FindUndoPos() : cannot write updated block info");
2126 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2127 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2128 if (nNewChunks > nOldChunks) {
2129 FILE *file = OpenUndoFile(pos);
2131 printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2132 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2140 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2142 // These are checks that are independent of context
2143 // that can be verified before saving an orphan block.
2146 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2147 return DoS(100, error("CheckBlock() : size limits failed"));
2149 // Check proof of work matches claimed amount
2150 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2151 return DoS(50, error("CheckBlock() : proof of work failed"));
2154 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2155 return error("CheckBlock() : block timestamp too far in the future");
2157 // First transaction must be coinbase, the rest must not be
2158 if (vtx.empty() || !vtx[0].IsCoinBase())
2159 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2160 for (unsigned int i = 1; i < vtx.size(); i++)
2161 if (vtx[i].IsCoinBase())
2162 return DoS(100, error("CheckBlock() : more than one coinbase"));
2164 // Check coinbase timestamp
2165 if (GetBlockTime() > FutureDrift((int64)vtx[0].nTime))
2166 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2168 if (IsProofOfStake())
2170 // Coinbase output should be empty if proof-of-stake block
2171 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2172 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2174 // Second transaction must be coinstake, the rest must not be
2175 if (vtx.empty() || !vtx[1].IsCoinStake())
2176 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2177 for (unsigned int i = 2; i < vtx.size(); i++)
2178 if (vtx[i].IsCoinStake())
2179 return DoS(100, error("CheckBlock() : more than one coinstake"));
2181 // Check coinstake timestamp
2182 if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2183 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2187 int64 nReward = GetProofOfWorkReward(nBits);
2188 // Check coinbase reward
2189 if (vtx[0].GetValueOut() > nReward)
2190 return DoS(50, error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
2191 vtx[0].GetValueOut(),
2194 // Should we check proof-of-work block signature or not?
2196 // * Always skip on TestNet
2197 // * Perform checking for the first 9689 blocks
2198 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2200 if(!fTestNet && fCheckSig)
2202 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2204 // check legacy proof-of-work block signature
2205 if (checkEntropySig && !CheckLegacySignature())
2206 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2211 // Check transactions
2212 BOOST_FOREACH(const CTransaction& tx, vtx)
2214 if (!tx.CheckTransaction())
2215 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2217 // check transaction timestamp
2218 if (GetBlockTime() < (int64)tx.nTime)
2219 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2222 // Check for duplicate txids. This is caught by ConnectInputs(),
2223 // but catching it earlier avoids a potential DoS attack:
2225 set<uint256> uniqueTx;
2226 for (unsigned int i=0; i<vtx.size(); i++) {
2227 uniqueTx.insert(GetTxHash(i));
2229 if (uniqueTx.size() != vtx.size())
2230 return DoS(100, error("CheckBlock() : duplicate transaction"));
2232 unsigned int nSigOps = 0;
2233 BOOST_FOREACH(const CTransaction& tx, vtx)
2235 nSigOps += tx.GetLegacySigOpCount();
2237 if (nSigOps > MAX_BLOCK_SIGOPS)
2238 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2240 // Check merkle root
2241 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2242 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2248 bool CBlock::AcceptBlock()
2250 // Check for duplicate
2251 uint256 hash = GetHash();
2252 if (mapBlockIndex.count(hash))
2253 return error("AcceptBlock() : block already in mapBlockIndex");
2255 // Get prev block index
2256 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2257 if (mi == mapBlockIndex.end())
2258 return DoS(10, error("AcceptBlock() : prev block not found"));
2259 CBlockIndex* pindexPrev = (*mi).second;
2260 int nHeight = pindexPrev->nHeight+1;
2262 // Check proof-of-work or proof-of-stake
2263 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2264 return DoS(100, error("AcceptBlock() : incorrect proof-of-%s amount", IsProofOfWork() ? "work" : "stake"));
2266 // Check timestamp against prev
2267 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2268 return error("AcceptBlock() : block's timestamp is too early");
2270 // Check that all transactions are finalized
2271 BOOST_FOREACH(const CTransaction& tx, vtx)
2272 if (!tx.IsFinal(nHeight, GetBlockTime()))
2273 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2275 // Check that the block chain matches the known block chain up to a checkpoint
2276 if (!Checkpoints::CheckHardened(nHeight, hash))
2277 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2279 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2281 // Check that the block satisfies synchronized checkpoint
2282 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2283 return error("AcceptBlock() : rejected by synchronized checkpoint");
2285 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2286 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2288 // Enforce rule that the coinbase starts with serialized block height
2289 CScript expect = CScript() << nHeight;
2290 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2291 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2292 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2294 // Write block to history file
2295 unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
2296 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2297 return error("AcceptBlock() : out of disk space");
2298 CDiskBlockPos blockPos;
2301 if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, nHeight, nTime))
2302 return error("AcceptBlock() : FindBlockPos failed");
2304 if (!WriteToDisk(blockPos))
2305 return error("AcceptBlock() : WriteToDisk failed");
2306 if (!AddToBlockIndex(blockPos))
2307 return error("AcceptBlock() : AddToBlockIndex failed");
2309 // Relay inventory, but don't relay old inventory during initial block download
2310 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2311 if (hashBestChain == hash)
2314 BOOST_FOREACH(CNode* pnode, vNodes)
2315 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2316 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2319 // Check pending sync-checkpoint
2320 Checkpoints::AcceptPendingSyncCheckpoint();
2325 uint256 CBlockIndex::GetBlockTrust() const
2328 bnTarget.SetCompact(nBits);
2334 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2335 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2339 // Calculate work amount for block
2340 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2342 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2343 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2345 // Return nPoWTrust for the first 12 blocks
2346 if (pprev == NULL || pprev->nHeight < 12)
2349 const CBlockIndex* currentIndex = pprev;
2351 if(IsProofOfStake())
2353 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2355 // Return 1/3 of score if parent block is not the PoW block
2356 if (!pprev->IsProofOfWork())
2357 return (bnNewTrust / 3).getuint256();
2361 // Check last 12 blocks type
2362 while (pprev->nHeight - currentIndex->nHeight < 12)
2364 if (currentIndex->IsProofOfWork())
2366 currentIndex = currentIndex->pprev;
2369 // Return 1/3 of score if less than 3 PoW blocks found
2371 return (bnNewTrust / 3).getuint256();
2373 return bnNewTrust.getuint256();
2377 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2379 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2380 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2381 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2385 // Check last 12 blocks type
2386 while (pprev->nHeight - currentIndex->nHeight < 12)
2388 if (currentIndex->IsProofOfStake())
2390 currentIndex = currentIndex->pprev;
2393 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2395 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2397 bnTarget.SetCompact(pprev->nBits);
2402 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2404 // Return nPoWTrust + full trust score for previous block nBits
2405 return nPoWTrust + bnNewTrust.getuint256();
2409 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2411 unsigned int nFound = 0;
2412 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2414 if (pstart->nVersion >= minVersion)
2416 pstart = pstart->pprev;
2418 return (nFound >= nRequired);
2421 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2423 // Check for duplicate
2424 uint256 hash = pblock->GetHash();
2425 if (mapBlockIndex.count(hash))
2426 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2427 if (mapOrphanBlocks.count(hash))
2428 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2430 // Preliminary checks
2431 if (!pblock->CheckBlock())
2432 return error("ProcessBlock() : CheckBlock FAILED");
2434 if (pblock->IsProofOfStake())
2436 // Limited duplicity on stake: prevents block flood attack
2437 // Duplicate stake allowed only when there is orphan child block
2438 if (setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2439 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());
2441 bool fFatal = false;
2442 uint256 hashProofOfStake;
2444 // Verify proof-of-stake script, hash target and signature
2445 if (!pblock->CheckSignature(fFatal, hashProofOfStake))
2449 // Invalid coinstake script, blockhash signature or no generator defined, nothing to do here
2450 // This also may occur when supplied proof-of-stake doesn't satisfy required target
2452 pfrom->Misbehaving(100);
2453 return error("ProcessBlock() : invalid signatures found in proof-of-stake block %s", hash.ToString().c_str());
2457 // Blockhash and coinstake signatures are OK but target checkings failed
2458 // This may occur during initial block download
2461 pfrom->Misbehaving(1); // Small DoS penalty
2463 printf("WARNING: ProcessBlock(): proof-of-stake target checkings failed for block %s, we'll try again later\n", hash.ToString().c_str());
2468 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2469 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2472 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2473 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2475 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2476 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2478 bnNewBlock.SetCompact(pblock->nBits);
2481 if (pblock->IsProofOfStake())
2482 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2484 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2486 if (bnNewBlock > bnRequired)
2489 pfrom->Misbehaving(100);
2490 return error("ProcessBlock() : block with too little proof-of-%s", pblock->IsProofOfStake() ? "stake" : "work");
2494 // Ask for pending sync-checkpoint if any
2495 if (!IsInitialBlockDownload())
2496 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2498 // If don't already have its previous block, shunt it off to holding area until we get it
2499 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2501 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2502 CBlock* pblock2 = new CBlock(*pblock);
2504 if (pblock2->IsProofOfStake())
2506 // Limited duplicity on stake: prevents block flood attack
2507 // Duplicate stake allowed only when there is orphan child block
2508 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2509 return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock2->GetProofOfStake().first.ToString().c_str(), pblock2->GetProofOfStake().second, hash.ToString().c_str());
2511 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2514 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2515 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2517 // Ask this guy to fill in what we're missing
2520 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2521 // ppcoin: getblocks may not obtain the ancestor block rejected
2522 // earlier by duplicate-stake check so we ask for it again directly
2523 if (!IsInitialBlockDownload())
2524 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2530 if (!pblock->AcceptBlock())
2531 return error("ProcessBlock() : AcceptBlock FAILED");
2533 // Recursively process any orphan blocks that depended on this one
2534 vector<uint256> vWorkQueue;
2535 vWorkQueue.push_back(hash);
2536 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2538 uint256 hashPrev = vWorkQueue[i];
2539 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2540 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2543 CBlock* pblockOrphan = (*mi).second;
2544 if (pblockOrphan->AcceptBlock())
2545 vWorkQueue.push_back(pblockOrphan->GetHash());
2546 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2547 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2548 delete pblockOrphan;
2550 mapOrphanBlocksByPrev.erase(hashPrev);
2553 printf("ProcessBlock: ACCEPTED\n");
2555 // ppcoin: if responsible for sync-checkpoint send it
2556 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2557 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2562 // attempt to generate suitable proof-of-stake
2563 bool CBlock::SignBlock(CWallet& wallet)
2565 // if we are trying to sign
2566 // something except proof-of-stake block template
2567 if (!vtx[0].vout[0].IsEmpty())
2570 // if we are trying to sign
2571 // a complete proof-of-stake block
2572 if (IsProofOfStake())
2575 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2578 CTransaction txCoinStake;
2579 int64 nSearchTime = txCoinStake.nTime; // search to current time
2581 if (nSearchTime > nLastCoinStakeSearchTime)
2583 if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2585 if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2587 // make sure coinstake would meet timestamp protocol
2588 // as it would be the same as the block timestamp
2589 vtx[0].nTime = nTime = txCoinStake.nTime;
2590 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2591 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2593 // we have to make sure that we have no future timestamps in
2594 // our transactions set
2595 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2596 if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2598 vtx.insert(vtx.begin() + 1, txCoinStake);
2599 hashMerkleRoot = BuildMerkleTree();
2601 // append a signature to our block
2602 return key.Sign(GetHash(), vchBlockSig);
2605 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2606 nLastCoinStakeSearchTime = nSearchTime;
2612 // get generation key
2613 bool CBlock::GetGenerator(CKey& GeneratorKey) const
2615 if(!IsProofOfStake())
2618 vector<valtype> vSolutions;
2619 txnouttype whichType;
2621 const CTxOut& txout = vtx[1].vout[1];
2623 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2625 if (whichType == TX_PUBKEY)
2627 valtype& vchPubKey = vSolutions[0];
2629 return GeneratorKey.SetPubKey(vchPubKey);
2635 // verify proof-of-stake signatures
2636 bool CBlock::CheckSignature(bool& fFatal, uint256& hashProofOfStake) const
2640 // no generator or invalid hash signature means fatal error
2641 fFatal = !GetGenerator(key) || !key.Verify(GetHash(), vchBlockSig);
2646 uint256 hashTarget = 0;
2647 if (!CheckProofOfStake(vtx[1], nBits, hashProofOfStake, hashTarget, fFatal))
2648 return false; // hash target mismatch or invalid coinstake signature
2653 // verify legacy proof-of-work signature
2654 bool CBlock::CheckLegacySignature() const
2656 if (IsProofOfStake())
2659 vector<valtype> vSolutions;
2660 txnouttype whichType;
2662 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2664 const CTxOut& txout = vtx[0].vout[i];
2666 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2669 if (whichType == TX_PUBKEY)
2672 valtype& vchPubKey = vSolutions[0];
2674 if (!key.SetPubKey(vchPubKey))
2676 if (vchBlockSig.empty())
2678 if(!key.Verify(GetHash(), vchBlockSig))
2687 bool CheckDiskSpace(uint64 nAdditionalBytes)
2689 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2691 // Check for nMinDiskSpace bytes (currently 50MB)
2692 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2695 string strMessage = _("Warning: Disk space is low!");
2696 strMiscWarning = strMessage;
2697 printf("*** %s\n", strMessage.c_str());
2698 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2706 CCriticalSection cs_LastBlockFile;
2707 CBlockFileInfo infoLastBlockFile;
2708 int nLastBlockFile = 0;
2710 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2714 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2715 boost::filesystem::create_directories(path.parent_path());
2716 FILE* file = fopen(path.string().c_str(), "rb+");
2717 if (!file && !fReadOnly)
2718 file = fopen(path.string().c_str(), "wb+");
2720 printf("Unable to open file %s\n", path.string().c_str());
2724 if (fseek(file, pos.nPos, SEEK_SET)) {
2725 printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2733 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2734 return OpenDiskFile(pos, "blk", fReadOnly);
2737 FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2738 return OpenDiskFile(pos, "rev", fReadOnly);
2741 bool LoadBlockIndex(bool fAllowNew)
2743 CBigNum bnTrustedModulus;
2747 pchMessageStart[0] = 0xcd;
2748 pchMessageStart[1] = 0xf2;
2749 pchMessageStart[2] = 0xc0;
2750 pchMessageStart[3] = 0xef;
2752 bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
2753 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2754 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2755 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2756 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2757 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2761 bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
2764 // Set up the Zerocoin Params object
2765 ZCParams = new libzerocoin::Params(bnTrustedModulus);
2770 CChainDB chaindb("cr");
2771 if (!LoadBlockIndex(chaindb))
2776 // Init with genesis block
2778 if (mapBlockIndex.empty())
2787 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2788 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2789 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2791 // vMerkleTree: 4cb33b3b6a
2795 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2796 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2797 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2799 // vMerkleTree: 4cb33b3b6a
2801 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2803 txNew.nTime = 1360105017;
2804 txNew.vin.resize(1);
2805 txNew.vout.resize(1);
2806 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2807 txNew.vout[0].SetEmpty();
2809 block.vtx.push_back(txNew);
2810 block.hashPrevBlock = 0;
2811 block.hashMerkleRoot = block.BuildMerkleTree();
2813 block.nTime = 1360105017;
2814 block.nBits = bnProofOfWorkLimit.GetCompact();
2815 block.nNonce = !fTestNet ? 1575379 : 46534;
2818 uint256 hash = block.GetHash();
2819 printf("%s\n", hash.ToString().c_str());
2820 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2822 assert(hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2823 assert(block.CheckBlock());
2825 // Start new block file
2826 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2827 CDiskBlockPos blockPos;
2830 if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, 0, block.nTime))
2831 return error("AcceptBlock() : FindBlockPos failed");
2833 if (!block.WriteToDisk(blockPos))
2834 return error("LoadBlockIndex() : writing genesis block to disk failed");
2835 if (!block.AddToBlockIndex(blockPos))
2836 return error("LoadBlockIndex() : genesis block not accepted");
2838 // initialize synchronized checkpoint
2839 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2840 return error("LoadBlockIndex() : failed to init sync checkpoint");
2843 string strPubKey = "";
2846 // if checkpoint master key changed must reset sync-checkpoint
2847 if (!chaindb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2849 // write checkpoint master key to db
2851 if (!chaindb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2852 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2853 if (!chaindb.TxnCommit())
2854 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2855 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2856 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2863 void PrintBlockTree()
2865 // pre-compute tree structure
2866 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2867 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2869 CBlockIndex* pindex = (*mi).second;
2870 mapNext[pindex->pprev].push_back(pindex);
2872 //while (rand() % 3 == 0)
2873 // mapNext[pindex->pprev].push_back(pindex);
2876 vector<pair<int, CBlockIndex*> > vStack;
2877 vStack.push_back(make_pair(0, pindexGenesisBlock));
2880 while (!vStack.empty())
2882 int nCol = vStack.back().first;
2883 CBlockIndex* pindex = vStack.back().second;
2886 // print split or gap
2887 if (nCol > nPrevCol)
2889 for (int i = 0; i < nCol-1; i++)
2893 else if (nCol < nPrevCol)
2895 for (int i = 0; i < nCol; i++)
2902 for (int i = 0; i < nCol; i++)
2907 block.ReadFromDisk(pindex);
2908 printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
2910 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2911 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2914 PrintWallets(block);
2916 // put the main time-chain first
2917 vector<CBlockIndex*>& vNext = mapNext[pindex];
2918 for (unsigned int i = 0; i < vNext.size(); i++)
2920 if (vNext[i]->pnext)
2922 swap(vNext[0], vNext[i]);
2928 for (unsigned int i = 0; i < vNext.size(); i++)
2929 vStack.push_back(make_pair(nCol+i, vNext[i]));
2933 bool LoadExternalBlockFile(FILE* fileIn)
2935 int64 nStart = GetTimeMillis();
2941 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2942 unsigned int nPos = 0;
2943 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2945 unsigned char pchData[65536];
2947 fseek(blkdat, nPos, SEEK_SET);
2948 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2951 nPos = (unsigned int)-1;
2954 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2957 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2959 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2962 nPos += ((unsigned char*)nFind - pchData) + 1;
2965 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2966 } while(!fRequestShutdown);
2967 if (nPos == (unsigned int)-1)
2969 fseek(blkdat, nPos, SEEK_SET);
2972 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2976 if (ProcessBlock(NULL,&block))
2984 catch (std::exception &e) {
2985 printf("%s() : Deserialize or I/O error caught during load\n",
2986 __PRETTY_FUNCTION__);
2989 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2993 //////////////////////////////////////////////////////////////////////////////
2998 extern map<uint256, CAlert> mapAlerts;
2999 extern CCriticalSection cs_mapAlerts;
3001 extern string strMintMessage;
3002 extern string strMintWarning;
3004 string GetWarnings(string strFor)
3007 string strStatusBar;
3010 if (GetBoolArg("-testsafemode"))
3013 // ppcoin: wallet lock warning for minting
3014 if (strMintWarning != "")
3017 strStatusBar = strMintWarning;
3020 // Misc warnings like out of disk space and clock is wrong
3021 if (strMiscWarning != "")
3024 strStatusBar = strMiscWarning;
3027 // * Should not enter safe mode for longer invalid chain
3028 // * If sync-checkpoint is too old do not enter safe mode
3029 // * Display warning only in the STRICT mode
3030 if (CheckpointsMode == Checkpoints::STRICT && Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) &&
3031 !fTestNet && !IsInitialBlockDownload())
3034 strStatusBar = _("WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.");
3037 // ppcoin: if detected invalid checkpoint enter safe mode
3038 if (Checkpoints::hashInvalidCheckpoint != 0)
3041 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3047 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3049 const CAlert& alert = item.second;
3050 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3052 nPriority = alert.nPriority;
3053 strStatusBar = alert.strStatusBar;
3054 if (nPriority > 1000)
3055 strRPC = strStatusBar;
3060 if (strFor == "statusbar")
3061 return strStatusBar;
3062 else if (strFor == "rpc")
3064 assert(!"GetWarnings() : invalid parameter");
3075 //////////////////////////////////////////////////////////////////////////////
3081 bool static AlreadyHave(const CInv& inv)
3087 bool txInMap = false;
3090 txInMap = mempool.exists(inv.hash);
3092 return txInMap || mapOrphanTransactions.count(inv.hash) ||
3093 pcoinsTip->HaveCoins(inv.hash);
3096 return mapBlockIndex.count(inv.hash) ||
3097 mapOrphanBlocks.count(inv.hash);
3099 // Don't know what it is, just say we already got one
3106 // The message start string is designed to be unlikely to occur in normal data.
3107 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3108 // a large 4-byte int at any alignment.
3109 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3111 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3113 static map<CService, CPubKey> mapReuseKey;
3114 RandAddSeedPerfmon();
3116 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3117 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3119 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3123 if (strCommand == "version")
3125 // Each connection can only send one version message
3126 if (pfrom->nVersion != 0)
3128 pfrom->Misbehaving(1);
3136 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3137 if (pfrom->nVersion < MIN_PROTO_VERSION)
3139 // Since February 20, 2012, the protocol is initiated at version 209,
3140 // and earlier versions are no longer supported
3141 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3142 pfrom->fDisconnect = true;
3146 if (pfrom->nVersion == 10300)
3147 pfrom->nVersion = 300;
3149 vRecv >> addrFrom >> nNonce;
3151 vRecv >> pfrom->strSubVer;
3153 vRecv >> pfrom->nStartingHeight;
3155 if (pfrom->fInbound && addrMe.IsRoutable())
3157 pfrom->addrLocal = addrMe;
3161 // Disconnect if we connected to ourself
3162 if (nNonce == nLocalHostNonce && nNonce > 1)
3164 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3165 pfrom->fDisconnect = true;
3169 // record my external IP reported by peer
3170 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3171 addrSeenByPeer = addrMe;
3173 // Be shy and don't send version until we hear
3174 if (pfrom->fInbound)
3175 pfrom->PushVersion();
3177 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3179 AddTimeData(pfrom->addr, nTime);
3182 pfrom->PushMessage("verack");
3183 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3185 if (!pfrom->fInbound)
3187 // Advertise our address
3188 if (!fNoListen && !IsInitialBlockDownload())
3190 CAddress addr = GetLocalAddress(&pfrom->addr);
3191 if (addr.IsRoutable())
3192 pfrom->PushAddress(addr);
3195 // Get recent addresses
3196 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3198 pfrom->PushMessage("getaddr");
3199 pfrom->fGetAddr = true;
3201 addrman.Good(pfrom->addr);
3203 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3205 addrman.Add(addrFrom, addrFrom);
3206 addrman.Good(addrFrom);
3210 // Ask the first connected node for block updates
3211 static int nAskedForBlocks = 0;
3212 if (!pfrom->fClient && !pfrom->fOneShot &&
3213 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3214 (pfrom->nVersion < NOBLKS_VERSION_START ||
3215 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3216 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3219 pfrom->PushGetBlocks(pindexBest, uint256(0));
3225 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3226 item.second.RelayTo(pfrom);
3229 // Relay sync-checkpoint
3231 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3232 if (!Checkpoints::checkpointMessage.IsNull())
3233 Checkpoints::checkpointMessage.RelayTo(pfrom);
3236 pfrom->fSuccessfullyConnected = true;
3238 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());
3240 cPeerBlockCounts.input(pfrom->nStartingHeight);
3242 // ppcoin: ask for pending sync-checkpoint if any
3243 if (!IsInitialBlockDownload())
3244 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3248 else if (pfrom->nVersion == 0)
3250 // Must have a version message before anything else
3251 pfrom->Misbehaving(1);
3256 else if (strCommand == "verack")
3258 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3262 else if (strCommand == "addr")
3264 vector<CAddress> vAddr;
3267 // Don't want addr from older versions unless seeding
3268 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3270 if (vAddr.size() > 1000)
3272 pfrom->Misbehaving(20);
3273 return error("message addr size() = %"PRIszu"", vAddr.size());
3276 // Store the new addresses
3277 vector<CAddress> vAddrOk;
3278 int64 nNow = GetAdjustedTime();
3279 int64 nSince = nNow - 10 * 60;
3280 BOOST_FOREACH(CAddress& addr, vAddr)
3284 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3285 addr.nTime = nNow - 5 * 24 * 60 * 60;
3286 pfrom->AddAddressKnown(addr);
3287 bool fReachable = IsReachable(addr);
3288 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3290 // Relay to a limited number of other nodes
3293 // Use deterministic randomness to send to the same nodes for 24 hours
3294 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3295 static uint256 hashSalt;
3297 hashSalt = GetRandHash();
3298 uint64 hashAddr = addr.GetHash();
3299 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3300 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3301 multimap<uint256, CNode*> mapMix;
3302 BOOST_FOREACH(CNode* pnode, vNodes)
3304 if (pnode->nVersion < CADDR_TIME_VERSION)
3306 unsigned int nPointer;
3307 memcpy(&nPointer, &pnode, sizeof(nPointer));
3308 uint256 hashKey = hashRand ^ nPointer;
3309 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3310 mapMix.insert(make_pair(hashKey, pnode));
3312 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3313 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3314 ((*mi).second)->PushAddress(addr);
3317 // Do not store addresses outside our network
3319 vAddrOk.push_back(addr);
3321 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3322 if (vAddr.size() < 1000)
3323 pfrom->fGetAddr = false;
3324 if (pfrom->fOneShot)
3325 pfrom->fDisconnect = true;
3328 else if (strCommand == "inv")
3332 if (vInv.size() > MAX_INV_SZ)
3334 pfrom->Misbehaving(20);
3335 return error("message inv size() = %"PRIszu"", vInv.size());
3338 // find last block in inv vector
3339 unsigned int nLastBlock = (unsigned int)(-1);
3340 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3341 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3342 nLastBlock = vInv.size() - 1 - nInv;
3346 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3348 const CInv &inv = vInv[nInv];
3352 pfrom->AddInventoryKnown(inv);
3354 bool fAlreadyHave = AlreadyHave(inv);
3356 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3360 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3361 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3362 } else if (nInv == nLastBlock) {
3363 // In case we are on a very long side-chain, it is possible that we already have
3364 // the last block in an inv bundle sent in response to getblocks. Try to detect
3365 // this situation and push another getblocks to continue.
3366 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3368 printf("force request: %s\n", inv.ToString().c_str());
3371 // Track requests for our stuff
3372 Inventory(inv.hash);
3377 else if (strCommand == "getdata")
3381 if (vInv.size() > MAX_INV_SZ)
3383 pfrom->Misbehaving(20);
3384 return error("message getdata size() = %"PRIszu"", vInv.size());
3387 if (fDebugNet || (vInv.size() != 1))
3388 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3390 BOOST_FOREACH(const CInv& inv, vInv)
3394 if (fDebugNet || (vInv.size() == 1))
3395 printf("received getdata for: %s\n", inv.ToString().c_str());
3397 if (inv.type == MSG_BLOCK)
3399 // Send block from disk
3400 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3401 if (mi != mapBlockIndex.end())
3404 block.ReadFromDisk((*mi).second);
3405 pfrom->PushMessage("block", block);
3407 // Trigger them to send a getblocks request for the next batch of inventory
3408 if (inv.hash == pfrom->hashContinue)
3410 // ppcoin: send latest proof-of-work block to allow the
3411 // download node to accept as orphan (proof-of-stake
3412 // block might be rejected by stake connection check)
3414 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3415 pfrom->PushMessage("inv", vInv);
3416 pfrom->hashContinue = 0;
3420 else if (inv.IsKnownType())
3422 // Send stream from relay memory
3423 bool pushed = false;
3426 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3427 if (mi != mapRelay.end()) {
3428 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3432 if (!pushed && inv.type == MSG_TX) {
3434 if (mempool.exists(inv.hash)) {
3435 CTransaction tx = mempool.lookup(inv.hash);
3436 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3439 pfrom->PushMessage("tx", ss);
3444 // Track requests for our stuff
3445 Inventory(inv.hash);
3450 else if (strCommand == "getblocks")
3452 CBlockLocator locator;
3454 vRecv >> locator >> hashStop;
3456 // Find the last block the caller has in the main chain
3457 CBlockIndex* pindex = locator.GetBlockIndex();
3459 // Send the rest of the chain
3461 pindex = pindex->pnext;
3463 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3464 for (; pindex; pindex = pindex->pnext)
3466 if (pindex->GetBlockHash() == hashStop)
3468 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3469 // ppcoin: tell downloading node about the latest block if it's
3470 // without risk being rejected due to stake connection check
3471 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3472 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3475 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3478 // When this block is requested, we'll send an inv that'll make them
3479 // getblocks the next batch of inventory.
3480 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3481 pfrom->hashContinue = pindex->GetBlockHash();
3486 else if (strCommand == "checkpoint")
3488 CSyncCheckpoint checkpoint;
3489 vRecv >> checkpoint;
3491 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3494 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3496 BOOST_FOREACH(CNode* pnode, vNodes)
3497 checkpoint.RelayTo(pnode);
3501 else if (strCommand == "getheaders")
3503 CBlockLocator locator;
3505 vRecv >> locator >> hashStop;
3507 CBlockIndex* pindex = NULL;
3508 if (locator.IsNull())
3510 // If locator is null, return the hashStop block
3511 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3512 if (mi == mapBlockIndex.end())
3514 pindex = (*mi).second;
3518 // Find the last block the caller has in the main chain
3519 pindex = locator.GetBlockIndex();
3521 pindex = pindex->pnext;
3524 vector<CBlock> vHeaders;
3526 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3527 for (; pindex; pindex = pindex->pnext)
3529 vHeaders.push_back(pindex->GetBlockHeader());
3530 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3533 pfrom->PushMessage("headers", vHeaders);
3537 else if (strCommand == "tx")
3539 vector<uint256> vWorkQueue;
3540 vector<uint256> vEraseQueue;
3541 CDataStream vMsg(vRecv);
3545 CInv inv(MSG_TX, tx.GetHash());
3546 pfrom->AddInventoryKnown(inv);
3548 bool fMissingInputs = false;
3549 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
3551 SyncWithWallets(inv.hash, tx, NULL, true);
3552 RelayTransaction(tx, inv.hash);
3553 mapAlreadyAskedFor.erase(inv);
3554 vWorkQueue.push_back(inv.hash);
3555 vEraseQueue.push_back(inv.hash);
3557 // Recursively process any orphan transactions that depended on this one
3558 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3560 uint256 hashPrev = vWorkQueue[i];
3561 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3562 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3565 const uint256& orphanTxHash = *mi;
3566 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3567 bool fMissingInputs2 = false;
3569 if (orphanTx.AcceptToMemoryPool(true, &fMissingInputs2))
3571 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3572 SyncWithWallets(inv.hash, tx, NULL, true);
3573 RelayTransaction(orphanTx, orphanTxHash);
3574 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3575 vWorkQueue.push_back(orphanTxHash);
3576 vEraseQueue.push_back(orphanTxHash);
3578 else if (!fMissingInputs2)
3581 vEraseQueue.push_back(orphanTxHash);
3582 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3587 BOOST_FOREACH(uint256 hash, vEraseQueue)
3588 EraseOrphanTx(hash);
3590 else if (fMissingInputs)
3594 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3595 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3597 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3599 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3603 else if (strCommand == "block")
3607 uint256 hashBlock = block.GetHash();
3609 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3612 CInv inv(MSG_BLOCK, hashBlock);
3613 pfrom->AddInventoryKnown(inv);
3615 if (ProcessBlock(pfrom, &block))
3616 mapAlreadyAskedFor.erase(inv);
3617 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3621 else if (strCommand == "getaddr")
3623 // Don't return addresses older than nCutOff timestamp
3624 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3625 pfrom->vAddrToSend.clear();
3626 vector<CAddress> vAddr = addrman.GetAddr();
3627 BOOST_FOREACH(const CAddress &addr, vAddr)
3628 if(addr.nTime > nCutOff)
3629 pfrom->PushAddress(addr);
3633 else if (strCommand == "mempool")
3635 std::vector<uint256> vtxid;
3636 mempool.queryHashes(vtxid);
3638 for (unsigned int i = 0; i < vtxid.size(); i++) {
3639 CInv inv(MSG_TX, vtxid[i]);
3640 vInv.push_back(inv);
3641 if (i == (MAX_INV_SZ - 1))
3644 if (vInv.size() > 0)
3645 pfrom->PushMessage("inv", vInv);
3649 else if (strCommand == "checkorder")
3654 if (!GetBoolArg("-allowreceivebyip"))
3656 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3663 /// we have a chance to check the order here
3665 // Keep giving the same key to the same ip until they use it
3666 if (!mapReuseKey.count(pfrom->addr))
3667 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3669 // Send back approval of order and pubkey to use
3670 CScript scriptPubKey;
3671 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3672 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3676 else if (strCommand == "reply")
3681 CRequestTracker tracker;
3683 LOCK(pfrom->cs_mapRequests);
3684 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3685 if (mi != pfrom->mapRequests.end())
3687 tracker = (*mi).second;
3688 pfrom->mapRequests.erase(mi);
3691 if (!tracker.IsNull())
3692 tracker.fn(tracker.param1, vRecv);
3696 else if (strCommand == "ping")
3698 if (pfrom->nVersion > BIP0031_VERSION)
3702 // Echo the message back with the nonce. This allows for two useful features:
3704 // 1) A remote node can quickly check if the connection is operational
3705 // 2) Remote nodes can measure the latency of the network thread. If this node
3706 // is overloaded it won't respond to pings quickly and the remote node can
3707 // avoid sending us more work, like chain download requests.
3709 // The nonce stops the remote getting confused between different pings: without
3710 // it, if the remote node sends a ping once per second and this node takes 5
3711 // seconds to respond to each, the 5th ping the remote sends would appear to
3712 // return very quickly.
3713 pfrom->PushMessage("pong", nonce);
3718 else if (strCommand == "alert")
3723 uint256 alertHash = alert.GetHash();
3724 if (pfrom->setKnown.count(alertHash) == 0)
3726 if (alert.ProcessAlert())
3729 pfrom->setKnown.insert(alertHash);
3732 BOOST_FOREACH(CNode* pnode, vNodes)
3733 alert.RelayTo(pnode);
3737 // Small DoS penalty so peers that send us lots of
3738 // duplicate/expired/invalid-signature/whatever alerts
3739 // eventually get banned.
3740 // This isn't a Misbehaving(100) (immediate ban) because the
3741 // peer might be an older or different implementation with
3742 // a different signature key, etc.
3743 pfrom->Misbehaving(10);
3751 // Ignore unknown commands for extensibility
3755 // Update the last seen time for this node's address
3756 if (pfrom->fNetworkNode)
3757 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3758 AddressCurrentlyConnected(pfrom->addr);
3764 bool ProcessMessages(CNode* pfrom)
3766 CDataStream& vRecv = pfrom->vRecv;
3770 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3774 // (4) message start
3783 // Don't bother if send buffer is too full to respond anyway
3784 if (pfrom->vSend.size() >= SendBufferSize())
3787 // Scan for message start
3788 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3789 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3790 if (vRecv.end() - pstart < nHeaderSize)
3792 if ((int)vRecv.size() > nHeaderSize)
3794 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3795 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3799 if (pstart - vRecv.begin() > 0)
3800 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3801 vRecv.erase(vRecv.begin(), pstart);
3804 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3809 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3812 string strCommand = hdr.GetCommand();
3815 unsigned int nMessageSize = hdr.nMessageSize;
3816 if (nMessageSize > MAX_SIZE)
3818 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3821 if (nMessageSize > vRecv.size())
3823 // Rewind and wait for rest of message
3824 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3829 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3830 unsigned int nChecksum = 0;
3831 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3832 if (nChecksum != hdr.nChecksum)
3834 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3835 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3839 // Copy message to its own buffer
3840 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3841 vRecv.ignore(nMessageSize);
3849 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3854 catch (std::ios_base::failure& e)
3856 if (strstr(e.what(), "end of data"))
3858 // Allow exceptions from under-length message on vRecv
3859 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());
3861 else if (strstr(e.what(), "size too large"))
3863 // Allow exceptions from over-long size
3864 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3868 PrintExceptionContinue(&e, "ProcessMessages()");
3871 catch (std::exception& e) {
3872 PrintExceptionContinue(&e, "ProcessMessages()");
3874 PrintExceptionContinue(NULL, "ProcessMessages()");
3878 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3886 bool SendMessages(CNode* pto, bool fSendTrickle)
3888 TRY_LOCK(cs_main, lockMain);
3890 // Don't send anything until we get their version message
3891 if (pto->nVersion == 0)
3894 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3896 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3898 if (pto->nVersion > BIP0031_VERSION)
3899 pto->PushMessage("ping", nonce);
3901 pto->PushMessage("ping");
3904 // Resend wallet transactions that haven't gotten in a block yet
3905 ResendWalletTransactions();
3907 // Address refresh broadcast
3908 static int64 nLastRebroadcast;
3909 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3913 BOOST_FOREACH(CNode* pnode, vNodes)
3915 // Periodically clear setAddrKnown to allow refresh broadcasts
3916 if (nLastRebroadcast)
3917 pnode->setAddrKnown.clear();
3919 // Rebroadcast our address
3922 CAddress addr = GetLocalAddress(&pnode->addr);
3923 if (addr.IsRoutable())
3924 pnode->PushAddress(addr);
3928 nLastRebroadcast = GetTime();
3936 vector<CAddress> vAddr;
3937 vAddr.reserve(pto->vAddrToSend.size());
3938 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3940 // returns true if wasn't already contained in the set
3941 if (pto->setAddrKnown.insert(addr).second)
3943 vAddr.push_back(addr);
3944 // receiver rejects addr messages larger than 1000
3945 if (vAddr.size() >= 1000)
3947 pto->PushMessage("addr", vAddr);
3952 pto->vAddrToSend.clear();
3954 pto->PushMessage("addr", vAddr);
3959 // Message: inventory
3962 vector<CInv> vInvWait;
3964 LOCK(pto->cs_inventory);
3965 vInv.reserve(pto->vInventoryToSend.size());
3966 vInvWait.reserve(pto->vInventoryToSend.size());
3967 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3969 if (pto->setInventoryKnown.count(inv))
3972 // trickle out tx inv to protect privacy
3973 if (inv.type == MSG_TX && !fSendTrickle)
3975 // 1/4 of tx invs blast to all immediately
3976 static uint256 hashSalt;
3978 hashSalt = GetRandHash();
3979 uint256 hashRand = inv.hash ^ hashSalt;
3980 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3981 bool fTrickleWait = ((hashRand & 3) != 0);
3983 // always trickle our own transactions
3987 if (GetTransaction(inv.hash, wtx))
3989 fTrickleWait = true;
3994 vInvWait.push_back(inv);
3999 // returns true if wasn't already contained in the set
4000 if (pto->setInventoryKnown.insert(inv).second)
4002 vInv.push_back(inv);
4003 if (vInv.size() >= 1000)
4005 pto->PushMessage("inv", vInv);
4010 pto->vInventoryToSend = vInvWait;
4013 pto->PushMessage("inv", vInv);
4019 vector<CInv> vGetData;
4020 int64 nNow = GetTime() * 1000000;
4021 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4023 const CInv& inv = (*pto->mapAskFor.begin()).second;
4024 if (!AlreadyHave(inv))
4027 printf("sending getdata: %s\n", inv.ToString().c_str());
4028 vGetData.push_back(inv);
4029 if (vGetData.size() >= 1000)
4031 pto->PushMessage("getdata", vGetData);
4034 mapAlreadyAskedFor[inv] = nNow;
4036 pto->mapAskFor.erase(pto->mapAskFor.begin());
4038 if (!vGetData.empty())
4039 pto->PushMessage("getdata", vGetData);
4045 // Amount compression:
4046 // * If the amount is 0, output 0
4047 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
4048 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
4049 // * call the result n
4050 // * output 1 + 10*(9*n + d - 1) + e
4051 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
4052 // (this is decodable, as d is in [1-9] and e is in [0-9])
4054 uint64 CTxOutCompressor::CompressAmount(uint64 n)
4059 while (((n % 10) == 0) && e < 9) {
4065 assert(d >= 1 && d <= 9);
4067 return 1 + (n*9 + d - 1)*10 + e;
4069 return 1 + (n - 1)*10 + 9;
4073 uint64 CTxOutCompressor::DecompressAmount(uint64 x)
4075 // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
4079 // x = 10*(9*n + d - 1) + e
4085 int d = (x % 9) + 1;