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 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(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 bool CCoinsViewCache::SetCoins(uint256 txid, const CCoins &coins) {
241 cacheCoins[txid] = coins;
245 bool CCoinsViewCache::HaveCoins(uint256 txid) {
246 return cacheCoins.count(txid) || base->HaveCoins(txid);
249 CBlockIndex *CCoinsViewCache::GetBestBlock() {
250 if (pindexTip == NULL)
251 pindexTip = base->GetBestBlock();
255 bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
260 bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
261 for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
262 cacheCoins[it->first] = it->second;
267 bool CCoinsViewCache::Flush() {
268 cacheCoinsReadOnly.clear(); // purge read-only cache
270 bool fOk = base->BatchWrite(cacheCoins, pindexTip);
276 unsigned int CCoinsViewCache::GetCacheSize() {
277 return cacheCoins.size();
280 /** CCoinsView that brings transactions from a memorypool into view.
281 It does not check for spendings by memory pool transactions. */
282 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
284 bool CCoinsViewMemPool::GetCoins(uint256 txid, CCoins &coins) {
285 if (base->GetCoins(txid, coins))
287 if (mempool.exists(txid)) {
288 const CTransaction &tx = mempool.lookup(txid);
289 coins = CCoins(tx, MEMPOOL_HEIGHT, -1);
295 bool CCoinsViewMemPool::HaveCoins(uint256 txid) {
296 return mempool.exists(txid) || base->HaveCoins(txid);
299 CCoinsViewCache *pcoinsTip = NULL;
301 //////////////////////////////////////////////////////////////////////////////
303 // mapOrphanTransactions
306 bool AddOrphanTx(const CTransaction& tx)
308 uint256 hash = tx.GetHash();
309 if (mapOrphanTransactions.count(hash))
312 // Ignore big transactions, to avoid a
313 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
314 // large transaction with a missing parent then we assume
315 // it will rebroadcast it later, after the parent transaction(s)
316 // have been mined or received.
317 // 10,000 orphans, each of which is at most 5,000 bytes big is
318 // at most 500 megabytes of orphans:
320 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
324 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
328 mapOrphanTransactions[hash] = tx;
329 BOOST_FOREACH(const CTxIn& txin, tx.vin)
330 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
332 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
333 mapOrphanTransactions.size());
337 void static EraseOrphanTx(uint256 hash)
339 if (!mapOrphanTransactions.count(hash))
341 const CTransaction& tx = mapOrphanTransactions[hash];
342 BOOST_FOREACH(const CTxIn& txin, tx.vin)
344 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
345 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
346 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
348 mapOrphanTransactions.erase(hash);
351 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
353 unsigned int nEvicted = 0;
354 while (mapOrphanTransactions.size() > nMaxOrphans)
356 // Evict a random orphan:
357 uint256 randomhash = GetRandHash();
358 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
359 if (it == mapOrphanTransactions.end())
360 it = mapOrphanTransactions.begin();
361 EraseOrphanTx(it->first);
373 //////////////////////////////////////////////////////////////////////////////
378 bool CTransaction::IsStandard() const
380 if (nVersion > CTransaction::CURRENT_VERSION)
383 BOOST_FOREACH(const CTxIn& txin, vin)
385 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
386 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
387 // ~65-byte public keys, plus a few script ops.
388 if (txin.scriptSig.size() > 500)
390 if (!txin.scriptSig.IsPushOnly())
393 BOOST_FOREACH(const CTxOut& txout, vout) {
394 if (!::IsStandard(txout.scriptPubKey))
396 if (txout.nValue == 0)
403 // Check transaction inputs, and make sure any
404 // pay-to-script-hash transactions are evaluating IsStandard scripts
406 // Why bother? To avoid denial-of-service attacks; an attacker
407 // can submit a standard HASH... OP_EQUAL transaction,
408 // which will get accepted into blocks. The redemption
409 // script can be anything; an attacker could use a very
410 // expensive-to-check-upon-redemption script like:
411 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
413 bool CTransaction::AreInputsStandard(CCoinsView& mapInputs) const
416 return true; // Coinbases don't use vin normally
418 for (unsigned int i = 0; i < vin.size(); i++)
420 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
422 vector<vector<unsigned char> > vSolutions;
423 txnouttype whichType;
424 // get the scriptPubKey corresponding to this input:
425 const CScript& prevScript = prev.scriptPubKey;
426 if (!Solver(prevScript, whichType, vSolutions))
428 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
429 if (nArgsExpected < 0)
432 // Transactions with extra stuff in their scriptSigs are
433 // non-standard. Note that this EvalScript() call will
434 // be quick, because if there are any operations
435 // beside "push data" in the scriptSig the
436 // IsStandard() call returns false
437 vector<vector<unsigned char> > stack;
438 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
441 if (whichType == TX_SCRIPTHASH)
445 CScript subscript(stack.back().begin(), stack.back().end());
446 vector<vector<unsigned char> > vSolutions2;
447 txnouttype whichType2;
448 if (!Solver(subscript, whichType2, vSolutions2))
450 if (whichType2 == TX_SCRIPTHASH)
454 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
457 nArgsExpected += tmpExpected;
460 if (stack.size() != (unsigned int)nArgsExpected)
468 CTransaction::GetLegacySigOpCount() const
470 unsigned int nSigOps = 0;
471 BOOST_FOREACH(const CTxIn& txin, vin)
473 nSigOps += txin.scriptSig.GetSigOpCount(false);
475 BOOST_FOREACH(const CTxOut& txout, vout)
477 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
483 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
493 if (pblock == NULL) {
495 if (pcoinsTip->GetCoins(GetHash(), coins)) {
496 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
498 if (!blockTmp.ReadFromDisk(pindex))
506 // Update the tx's hashBlock
507 hashBlock = pblock->GetHash();
509 // Locate the transaction
510 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
511 if (pblock->vtx[nIndex] == *(CTransaction*)this)
513 if (nIndex == (int)pblock->vtx.size())
515 vMerkleBranch.clear();
517 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
521 // Fill in merkle branch
522 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
526 // Is the tx in a block that's in the main chain
527 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
528 if (mi == mapBlockIndex.end())
530 CBlockIndex* pindex = (*mi).second;
531 if (!pindex || !pindex->IsInMainChain())
534 return pindexBest->nHeight - pindex->nHeight + 1;
537 bool CTransaction::CheckTransaction() const
539 // Basic checks that don't depend on any context
541 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
543 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
545 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
546 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
548 // Check for negative or overflow output values
550 for (unsigned int i = 0; i < vout.size(); i++)
552 const CTxOut& txout = vout[i];
553 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
554 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
556 // Enforce minimum output amount for user transactions until 1 May 2014 04:00:00 GMT
557 if (!fTestNet && !IsCoinBase() && !txout.IsEmpty() && nTime < OUTPUT_SWITCH_TIME && txout.nValue < MIN_TXOUT_AMOUNT)
558 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
560 if (txout.nValue > MAX_MONEY)
561 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
562 nValueOut += txout.nValue;
563 if (!MoneyRange(nValueOut))
564 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
567 // Check for duplicate inputs
568 set<COutPoint> vInOutPoints;
569 BOOST_FOREACH(const CTxIn& txin, vin)
571 if (vInOutPoints.count(txin.prevout))
573 vInOutPoints.insert(txin.prevout);
578 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
579 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
583 BOOST_FOREACH(const CTxIn& txin, vin)
584 if (txin.prevout.IsNull())
585 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
591 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
592 enum GetMinFee_mode mode, unsigned int nBytes) const
594 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
595 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
597 unsigned int nNewBlockSize = nBlockSize + nBytes;
598 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
600 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
601 if (nMinFee < nBaseFee)
603 BOOST_FOREACH(const CTxOut& txout, vout)
604 if (txout.nValue < CENT)
608 // Raise the price as the block approaches full
609 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
611 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
613 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
616 if (!MoneyRange(nMinFee))
621 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
625 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
627 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
628 while (it != mapNextTx.end() && it->first.hash == hashTx) {
629 coins.Spend(it->first.n); // and remove those outputs from coins
634 bool CTxMemPool::accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs)
637 *pfMissingInputs = false;
639 if (!tx.CheckTransaction())
640 return error("CTxMemPool::accept() : CheckTransaction failed");
642 // Coinbase is only valid in a block, not as a loose transaction
644 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
646 // Coinstake is also only valid in a block, not as a loose transaction
647 if (tx.IsCoinStake())
648 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
650 // To help v0.1.5 clients who would see it as a negative number
651 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
652 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
654 // Rather not work on nonstandard transactions (unless -testnet)
655 if (!fTestNet && !tx.IsStandard())
656 return error("CTxMemPool::accept() : nonstandard transaction type");
658 // is it already in the memory pool?
659 uint256 hash = tx.GetHash();
662 if (mapTx.count(hash))
666 // Check for conflicts with in-memory transactions
667 CTransaction* ptxOld = NULL;
668 for (unsigned int i = 0; i < tx.vin.size(); i++)
670 COutPoint outpoint = tx.vin[i].prevout;
671 if (mapNextTx.count(outpoint))
673 // Disable replacement feature for now
676 // Allow replacing with a newer version of the same transaction
679 ptxOld = mapNextTx[outpoint].ptx;
680 if (ptxOld->IsFinal())
682 if (!tx.IsNewerThan(*ptxOld))
684 for (unsigned int i = 0; i < tx.vin.size(); i++)
686 COutPoint outpoint = tx.vin[i].prevout;
687 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
696 CCoinsViewCache &view = *pcoinsTip;
698 // do we already have it?
699 if (view.HaveCoins(hash))
702 // do all inputs exist?
703 BOOST_FOREACH(const CTxIn txin, tx.vin) {
704 if (!view.HaveCoins(txin.prevout.hash)) {
706 *pfMissingInputs = true;
711 // Check for non-standard pay-to-script-hash in inputs
712 if (!tx.AreInputsStandard(view) && !fTestNet)
713 return error("CTxMemPool::accept() : nonstandard transaction input");
715 // Note: if you modify this code to accept non-standard transactions, then
716 // you should add code here to check that the transaction does a
717 // reasonable number of ECDSA signature verifications.
719 int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
720 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
722 // Don't accept it if it can't get into a block
723 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY, nSize);
724 if (nFees < txMinFee)
725 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
726 hash.ToString().c_str(),
730 // Continuously rate-limit free transactions
731 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
732 // be annoying or make others' transactions take longer to confirm.
733 if (nFees < MIN_RELAY_TX_FEE)
735 static CCriticalSection cs;
736 static double dFreeCount;
737 static int64 nLastTime;
738 int64 nNow = GetTime();
742 // Use an exponentially decaying ~10-minute window:
743 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
745 // -limitfreerelay unit is thousand-bytes-per-minute
746 // At default rate it would take over a month to fill 1GB
747 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
748 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
750 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
755 // Check against previous transactions
756 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
757 if (!tx.CheckInputs(view, CS_ALWAYS, true, false))
759 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
763 // Store transaction in memory
768 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
771 addUnchecked(hash, tx);
774 ///// are we sure this is ok when loading transactions or restoring block txes
775 // If updated, erase old tx from wallet
777 EraseFromWallets(ptxOld->GetHash());
779 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
780 hash.ToString().substr(0,10).c_str(),
785 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
787 return mempool.accept(*this, fCheckInputs, pfMissingInputs);
790 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
792 // Add to memory pool without checking anything. Don't call this directly,
793 // call CTxMemPool::accept to properly check the transaction first.
796 for (unsigned int i = 0; i < tx.vin.size(); i++)
797 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
798 nTransactionsUpdated++;
804 bool CTxMemPool::remove(CTransaction &tx)
806 // Remove transaction from memory pool
809 uint256 hash = tx.GetHash();
810 if (mapTx.count(hash))
812 BOOST_FOREACH(const CTxIn& txin, tx.vin)
813 mapNextTx.erase(txin.prevout);
815 nTransactionsUpdated++;
821 void CTxMemPool::clear()
826 ++nTransactionsUpdated;
829 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
834 vtxid.reserve(mapTx.size());
835 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
836 vtxid.push_back((*mi).first);
842 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
844 if (hashBlock == 0 || nIndex == -1)
847 // Find the block it claims to be in
848 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
849 if (mi == mapBlockIndex.end())
851 CBlockIndex* pindex = (*mi).second;
852 if (!pindex || !pindex->IsInMainChain())
855 // Make sure the merkle branch connects to this block
856 if (!fMerkleVerified)
858 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
860 fMerkleVerified = true;
864 return pindexBest->nHeight - pindex->nHeight + 1;
867 int CMerkleTx::GetBlocksToMaturity() const
869 if (!(IsCoinBase() || IsCoinStake()))
871 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
875 bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs)
879 if (!IsInMainChain() && !ClientCheckInputs())
881 return CTransaction::AcceptToMemoryPool(false);
885 return CTransaction::AcceptToMemoryPool(fCheckInputs);
889 bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
894 // Add previous supporting transactions first
895 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
897 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
899 uint256 hash = tx.GetHash();
900 if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
901 tx.AcceptToMemoryPool(fCheckInputs);
904 return AcceptToMemoryPool(fCheckInputs);
909 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
910 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
912 CBlockIndex *pindexSlow = NULL;
917 if (mempool.exists(hash))
919 txOut = mempool.lookup(hash);
924 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
927 CCoinsViewCache &view = *pcoinsTip;
929 if (view.GetCoins(hash, coins))
930 nHeight = coins.nHeight;
933 pindexSlow = FindBlockByHeight(nHeight);
939 if (block.ReadFromDisk(pindexSlow)) {
940 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
941 if (tx.GetHash() == hash) {
943 hashBlock = pindexSlow->GetBlockHash();
954 //////////////////////////////////////////////////////////////////////////////
956 // CBlock and CBlockIndex
959 static CBlockIndex* pblockindexFBBHLast;
960 CBlockIndex* FindBlockByHeight(int nHeight)
962 CBlockIndex *pblockindex;
963 if (nHeight < nBestHeight / 2)
964 pblockindex = pindexGenesisBlock;
966 pblockindex = pindexBest;
967 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
968 pblockindex = pblockindexFBBHLast;
969 while (pblockindex->nHeight > nHeight)
970 pblockindex = pblockindex->pprev;
971 while (pblockindex->nHeight < nHeight)
972 pblockindex = pblockindex->pnext;
973 pblockindexFBBHLast = pblockindex;
977 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
979 if (!fReadTransactions)
981 *this = pindex->GetBlockHeader();
984 if (!ReadFromDisk(pindex->GetBlockPos(), fReadTransactions))
986 if (GetHash() != pindex->GetBlockHash())
987 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
991 uint256 static GetOrphanRoot(const CBlock* pblock)
993 // Work back to the first block in the orphan chain
994 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
995 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
996 return pblock->GetHash();
999 // ppcoin: find block wanted by given orphan block
1000 uint256 WantedByOrphan(const CBlock* pblockOrphan)
1002 // Work back to the first block in the orphan chain
1003 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
1004 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
1005 return pblockOrphan->hashPrevBlock;
1008 // select stake target limit according to hard-coded conditions
1009 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1011 if(fTestNet) // separate proof of stake target limit for testnet
1012 return bnProofOfStakeLimit;
1013 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1014 return bnProofOfStakeLimit;
1015 if(nHeight + 1 > 15000) // 24 bits since block 15000
1016 return bnProofOfStakeLegacyLimit;
1017 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1018 return bnProofOfStakeHardLimit;
1020 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1023 // miner's coin base reward based on nBits
1024 int64 GetProofOfWorkReward(unsigned int nBits)
1026 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1029 bnTarget.SetCompact(nBits);
1030 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1031 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1033 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1034 // A reasonably continuous curve is used to avoid shock to market
1035 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1037 // Human readable form:
1039 // nSubsidy = 100 / (diff ^ 1/6)
1040 CBigNum bnLowerBound = CENT;
1041 CBigNum bnUpperBound = bnSubsidyLimit;
1042 while (bnLowerBound + CENT <= bnUpperBound)
1044 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1045 if (fDebug && GetBoolArg("-printcreation"))
1046 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1047 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1048 bnUpperBound = bnMidValue;
1050 bnLowerBound = bnMidValue;
1053 int64 nSubsidy = bnUpperBound.getuint64();
1055 nSubsidy = (nSubsidy / CENT) * CENT;
1056 if (fDebug && GetBoolArg("-printcreation"))
1057 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1059 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
1062 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1063 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
1065 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1067 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1069 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1071 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1073 bnTarget.SetCompact(nBits);
1074 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1075 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1077 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1079 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1080 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1081 bnMidPart, bnRewardPart;
1083 while (bnLowerBound + CENT <= bnUpperBound)
1085 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1086 if (fDebug && GetBoolArg("-printcreation"))
1087 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1089 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1092 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1094 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1096 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1099 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1100 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1105 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1107 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1109 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1112 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1113 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1116 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1117 bnUpperBound = bnMidValue;
1119 bnLowerBound = bnMidValue;
1122 nRewardCoinYear = bnUpperBound.getuint64();
1123 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1127 // Old creation amount per coin-year, 5% fixed stake mint rate
1128 nRewardCoinYear = 5 * CENT;
1132 return nRewardCoinYear;
1134 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1136 // Set reasonable reward limit for large inputs since 20 Oct 2013
1138 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1139 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1141 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1142 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1144 nSubsidy = min(nSubsidy, nSubsidyLimit);
1147 if (fDebug && GetBoolArg("-printcreation"))
1148 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1152 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1154 // get proof of work blocks max spacing according to hard-coded conditions
1155 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1157 if(nTime > TARGETS_SWITCH_TIME)
1158 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1161 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1163 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1167 // maximum nBits value could possible be required nTime after
1169 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1172 bnResult.SetCompact(nBase);
1174 while (nTime > 0 && bnResult < bnTargetLimit)
1176 // Maximum 200% adjustment per day...
1178 nTime -= 24 * 60 * 60;
1180 if (bnResult > bnTargetLimit)
1181 bnResult = bnTargetLimit;
1182 return bnResult.GetCompact();
1186 // minimum amount of work that could possibly be required nTime after
1187 // minimum proof-of-work required was nBase
1189 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1191 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1195 // minimum amount of stake that could possibly be required nTime after
1196 // minimum proof-of-stake required was nBase
1198 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1200 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1204 // ppcoin: find last block index up to pindex
1205 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1207 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1208 pindex = pindex->pprev;
1212 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1214 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1216 if (pindexLast == NULL)
1217 return bnTargetLimit.GetCompact(); // genesis block
1219 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1220 if (pindexPrev->pprev == NULL)
1221 return bnTargetLimit.GetCompact(); // first block
1222 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1223 if (pindexPrevPrev->pprev == NULL)
1224 return bnTargetLimit.GetCompact(); // second block
1226 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1228 // ppcoin: target change every block
1229 // ppcoin: retarget with exponential moving toward target spacing
1231 bnNew.SetCompact(pindexPrev->nBits);
1232 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1233 int64 nInterval = nTargetTimespan / nTargetSpacing;
1234 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1235 bnNew /= ((nInterval + 1) * nTargetSpacing);
1237 if (bnNew > bnTargetLimit)
1238 bnNew = bnTargetLimit;
1240 return bnNew.GetCompact();
1243 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1246 bnTarget.SetCompact(nBits);
1249 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1250 return error("CheckProofOfWork() : nBits below minimum work");
1252 // Check proof of work matches claimed amount
1253 if (hash > bnTarget.getuint256())
1254 return error("CheckProofOfWork() : hash doesn't match nBits");
1259 // Return maximum amount of blocks that other nodes claim to have
1260 int GetNumBlocksOfPeers()
1262 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1265 bool IsInitialBlockDownload()
1267 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1269 static int64 nLastUpdate;
1270 static CBlockIndex* pindexLastBest;
1271 if (pindexBest != pindexLastBest)
1273 pindexLastBest = pindexBest;
1274 nLastUpdate = GetTime();
1276 return (GetTime() - nLastUpdate < 10 &&
1277 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1280 void static InvalidChainFound(CBlockIndex* pindexNew)
1282 if (pindexNew->nChainTrust > nBestInvalidTrust)
1284 nBestInvalidTrust = pindexNew->nChainTrust;
1285 CChainDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1286 uiInterface.NotifyBlocksChanged();
1289 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1290 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1292 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1293 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1294 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1295 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1296 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1297 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1298 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1299 nBestBlockTrust.Get64(),
1300 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1304 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1306 nTime = max(GetBlockTime(), GetAdjustedTime());
1310 CTxOut CTransaction::GetOutputFor(const CTxIn& input, CCoinsView& view)
1313 if (!view.GetCoins(input.prevout.hash, coins))
1314 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1316 if (input.prevout.n >= coins.vout.size())
1317 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range or already spent");
1319 const CTxOut &out = coins.vout[input.prevout.n];
1321 throw std::runtime_error("CTransaction::GetOutputFor() : already spent");
1326 int64 CTransaction::GetValueIn(CCoinsView& inputs) const
1332 for (unsigned int i = 0; i < vin.size(); i++)
1334 nResult += GetOutputFor(vin[i], inputs).nValue;
1339 unsigned int CTransaction::GetP2SHSigOpCount(CCoinsView& inputs) const
1344 unsigned int nSigOps = 0;
1345 for (unsigned int i = 0; i < vin.size(); i++)
1347 CTxOut prevout = GetOutputFor(vin[i], inputs);
1348 if (prevout.scriptPubKey.IsPayToScriptHash())
1349 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1354 bool CTransaction::UpdateCoins(CCoinsView &inputs, CTxUndo &txundo, int nHeight, unsigned int nTimeStamp) const
1356 uint256 hash = GetHash();
1358 // mark inputs spent
1359 if (!IsCoinBase()) {
1360 BOOST_FOREACH(const CTxIn &txin, vin) {
1362 if (!inputs.GetCoins(txin.prevout.hash, coins))
1363 return error("UpdateCoins() : cannot find prevtx");
1364 if (coins.nTime > nTimeStamp)
1365 return error("UpdateCoins() : timestamp violation");
1367 if (!coins.Spend(txin.prevout, undo))
1368 return error("UpdateCoins() : cannot spend input");
1369 txundo.vprevout.push_back(undo);
1370 if (!inputs.SetCoins(txin.prevout.hash, coins))
1371 return error("UpdateCoins() : cannot update input");
1376 if (!inputs.SetCoins(hash, CCoins(*this, nHeight, nTimeStamp)))
1377 return error("UpdateCoins() : cannot update output");
1382 bool CTransaction::HaveInputs(CCoinsView &inputs) const
1384 if (!IsCoinBase()) {
1385 // first check whether information about the prevout hash is available
1386 for (unsigned int i = 0; i < vin.size(); i++) {
1387 const COutPoint &prevout = vin[i].prevout;
1388 if (!inputs.HaveCoins(prevout.hash))
1392 // then check whether the actual outputs are available
1393 for (unsigned int i = 0; i < vin.size(); i++) {
1394 const COutPoint &prevout = vin[i].prevout;
1396 inputs.GetCoins(prevout.hash, coins);
1397 if (!coins.IsAvailable(prevout.n))
1404 bool CTransaction::CheckInputs(CCoinsView &inputs, enum CheckSig_mode csmode, bool fStrictPayToScriptHash, bool fStrictEncodings, CBlock *pblock) const
1410 for (unsigned int i = 0; i < vin.size(); i++)
1412 const COutPoint &prevout = vin[i].prevout;
1414 if (!inputs.GetCoins(prevout.hash, coins))
1415 return error("CheckInputs() : cannot find prevout tx");
1417 // Check for conflicts (double-spend)
1418 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1419 // for an attacker to attempt to split the network.
1420 if (!coins.IsAvailable(prevout.n))
1421 return error("CheckInputs() : %s prev tx already used", GetHash().ToString().substr(0,10).c_str());
1423 // If prev is coinbase or coinstake, check that it's matured
1424 if (coins.IsCoinBase() || coins.IsCoinStake()) {
1425 CBlockIndex *pindexBlock = inputs.GetBestBlock();
1426 if (pindexBlock->nHeight - coins.nHeight < nCoinbaseMaturity)
1427 return error("CheckInputs() : tried to spend %s at depth %d", coins.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - coins.nHeight);
1430 // Check transaction timestamp
1431 if (coins.nTime > nTime)
1432 return DoS(100, error("CheckInputs() : transaction timestamp earlier than input transaction"));
1434 // Check for negative or overflow input values
1435 nValueIn += coins.vout[prevout.n].nValue;
1436 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1437 return DoS(100, error("CheckInputs() : txin values out of range"));
1443 return error("CheckInputs() : %s is a coinstake, but no block specified", GetHash().ToString().substr(0,10).c_str());
1445 // Coin stake tx earns reward instead of paying fee
1447 if (!GetCoinAge(nCoinAge))
1448 return error("CheckInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1450 int64 nStakeReward = GetValueOut() - nValueIn;
1451 int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pblock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1453 if (nStakeReward > nCalculatedStakeReward)
1454 return DoS(100, error("CheckInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1458 if (nValueIn < GetValueOut())
1459 return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1461 // Tally transaction fees
1462 int64 nTxFee = nValueIn - GetValueOut();
1464 return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1466 if (!MoneyRange(nFees))
1467 return DoS(100, error("CheckInputs() : nFees out of range"));
1469 // enforce transaction fees for every block until 1 May 2014 04:00:00 GMT
1470 if (!fTestNet && nTxFee < GetMinFee() && nTime < OUTPUT_SWITCH_TIME)
1471 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;
1474 // The first loop above does all the inexpensive checks.
1475 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1476 // Helps prevent CPU exhaustion attacks.
1478 // Skip ECDSA signature verification when connecting blocks
1479 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1480 // still computed and checked, and any change will be caught at the next checkpoint.
1481 if (csmode == CS_ALWAYS ||
1482 (csmode == CS_AFTER_CHECKPOINT && inputs.GetBestBlock()->nHeight >= Checkpoints::GetTotalBlocksEstimate())) {
1483 for (unsigned int i = 0; i < vin.size(); i++) {
1484 const COutPoint &prevout = vin[i].prevout;
1486 inputs.GetCoins(prevout.hash, coins);
1489 if (!VerifySignature(coins, *this, i, fStrictPayToScriptHash, fStrictEncodings, 0)) {
1490 // only during transition phase for P2SH: do not invoke anti-DoS code for
1491 // potentially old clients relaying bad P2SH transactions
1492 if (fStrictPayToScriptHash && VerifySignature(coins, *this, i, false, fStrictEncodings, 0))
1493 return error("CheckInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1495 return DoS(100,error("CheckInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1505 bool CTransaction::ClientCheckInputs() const
1510 // Take over previous transactions' spent pointers
1514 for (unsigned int i = 0; i < vin.size(); i++)
1516 // Get prev tx from single transactions in memory
1517 COutPoint prevout = vin[i].prevout;
1518 if (!mempool.exists(prevout.hash))
1520 CTransaction& txPrev = mempool.lookup(prevout.hash);
1522 if (prevout.n >= txPrev.vout.size())
1526 if (!VerifySignature(CCoins(txPrev, -1, -1), *this, i, true, false, 0))
1527 return error("ConnectInputs() : VerifySignature failed");
1529 ///// this is redundant with the mempool.mapNextTx stuff,
1530 ///// not sure which I want to get rid of
1531 ///// this has to go away now that posNext is gone
1532 // // Check for conflicts
1533 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1534 // return error("ConnectInputs() : prev tx already used");
1536 // // Flag outpoints as used
1537 // txPrev.vout[prevout.n].posNext = posThisTx;
1539 nValueIn += txPrev.vout[prevout.n].nValue;
1541 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1542 return error("ClientConnectInputs() : txin values out of range");
1544 if (GetValueOut() > nValueIn)
1551 bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsView &view)
1553 assert(pindex == view.GetBestBlock());
1555 CBlockUndo blockUndo;
1557 CDiskBlockPos pos = pindex->GetUndoPos();
1559 return error("DisconnectBlock() : no undo data available");
1560 FILE *file = OpenUndoFile(pos, true);
1562 return error("DisconnectBlock() : undo file not available");
1563 CAutoFile fileUndo(file, SER_DISK, CLIENT_VERSION);
1564 fileUndo >> blockUndo;
1567 assert(blockUndo.vtxundo.size() + 1 == vtx.size());
1569 // undo transactions in reverse order
1570 for (int i = vtx.size() - 1; i >= 0; i--) {
1571 const CTransaction &tx = vtx[i];
1572 uint256 hash = tx.GetHash();
1574 // don't check coinbase coins for proof-of-stake block
1575 if(IsProofOfStake() && tx.IsCoinBase())
1578 // check that all outputs are available
1580 if (!view.GetCoins(hash, outs))
1581 return error("DisconnectBlock() : outputs still spent? database corrupted");
1583 CCoins outsBlock = CCoins(tx, pindex->nHeight, pindex->nTime);
1584 if (outs != outsBlock)
1585 return error("DisconnectBlock() : added transaction mismatch? database corrupted");
1588 if (!view.SetCoins(hash, CCoins()))
1589 return error("DisconnectBlock() : cannot delete coin outputs");
1592 if (i > 0) { // not coinbases
1593 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1594 assert(txundo.vprevout.size() == tx.vin.size());
1595 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1596 const COutPoint &out = tx.vin[j].prevout;
1597 const CTxInUndo &undo = txundo.vprevout[j];
1599 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1600 if (coins.IsPruned()) {
1601 if (undo.nHeight == 0)
1602 return error("DisconnectBlock() : undo data doesn't contain tx metadata? database corrupted");
1603 coins.fCoinBase = undo.fCoinBase;
1604 coins.fCoinStake = undo.fCoinStake;
1605 coins.nHeight = undo.nHeight;
1606 coins.nTime = undo.nTime;
1607 coins.nBlockTime = undo.nBlockTime;
1608 coins.nVersion = undo.nVersion;
1610 if (undo.nHeight != 0)
1611 return error("DisconnectBlock() : undo data contains unneeded tx metadata? database corrupted");
1613 if (coins.IsAvailable(out.n))
1614 return error("DisconnectBlock() : prevout output not spent? database corrupted");
1615 if (coins.vout.size() < out.n+1)
1616 coins.vout.resize(out.n+1);
1617 coins.vout[out.n] = undo.txout;
1618 if (!view.SetCoins(out.hash, coins))
1619 return error("DisconnectBlock() : cannot restore coin inputs");
1624 // move best block pointer to prevout block
1625 view.SetBestBlock(pindex->pprev);
1630 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1632 bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsView &view, bool fJustCheck)
1634 // Check it again in case a previous version let a bad block in
1635 if (!CheckBlock(!fJustCheck, !fJustCheck))
1638 // verify that the view's current state corresponds to the previous block
1639 assert(pindex->pprev == view.GetBestBlock());
1641 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1642 // unless those are already completely spent.
1643 // If such overwrites are allowed, coinbases and transactions depending upon those
1644 // can be duplicated to remove the ability to spend the first instance -- even after
1645 // being sent to another address.
1646 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1647 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1648 // already refuses previously-known transaction ids entirely.
1649 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1650 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1651 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1652 // initial block download.
1653 bool fEnforceBIP30 = true;
1655 if (fEnforceBIP30) {
1656 BOOST_FOREACH(CTransaction& tx, vtx) {
1657 uint256 hash = tx.GetHash();
1659 if (view.GetCoins(hash, coins) && !coins.IsPruned())
1660 return error("ConnectBlock() : tried to overwrite transaction");
1664 // BIP16 always active
1665 bool fStrictPayToScriptHash = true;
1667 CBlockUndo blockundo;
1669 int64 nFees = 0, nValueIn = 0, nValueOut = 0;
1670 unsigned int nSigOps = 0;
1671 BOOST_FOREACH(CTransaction& tx, vtx)
1673 nSigOps += tx.GetLegacySigOpCount();
1674 if (nSigOps > MAX_BLOCK_SIGOPS)
1675 return DoS(100, error("ConnectBlock() : too many sigops"));
1677 if (!tx.IsCoinBase())
1679 if (!tx.HaveInputs(view))
1680 return DoS(100, error("ConnectBlock() : inputs missing/spent"));
1682 if (fStrictPayToScriptHash)
1684 // Add in sigops done by pay-to-script-hash inputs;
1685 // this is to prevent a "rogue miner" from creating
1686 // an incredibly-expensive-to-validate block.
1687 nSigOps += tx.GetP2SHSigOpCount(view);
1688 if (nSigOps > MAX_BLOCK_SIGOPS)
1689 return DoS(100, error("ConnectBlock() : too many sigops"));
1692 int64 nTxValueOut = tx.GetValueOut();
1693 int64 nTxValueIn = tx.GetValueIn(view);
1695 nValueIn += nTxValueIn;
1696 nValueOut += nTxValueOut;
1698 if (!tx.IsCoinStake())
1699 nFees += nTxValueIn - nTxValueOut;
1701 if (!tx.CheckInputs(view, CS_AFTER_CHECKPOINT, fStrictPayToScriptHash, false, this))
1706 nValueOut += tx.GetValueOut();
1709 // don't create coinbase coins for proof-of-stake block
1710 if(IsProofOfStake() && tx.IsCoinBase())
1714 if (!tx.UpdateCoins(view, txundo, pindex->nHeight, pindex->nTime))
1715 return error("ConnectBlock() : UpdateInputs failed");
1716 if (!tx.IsCoinBase())
1717 blockundo.vtxundo.push_back(txundo);
1720 pindex->nMint = nValueOut - nValueIn + nFees;
1721 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1729 // Write undo information to disk
1730 if (pindex->GetUndoPos().IsNull())
1732 if (!FindUndoPos(chaindb, pindex->pos.nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 8))
1733 return error("ConnectBlock() : FindUndoPos failed");
1734 if (!blockundo.WriteToDisk(pos))
1735 return error("ConnectBlock() : CBlockUndo::WriteToDisk failed");
1737 // update nUndoPos in block index
1738 pindex->nUndoPos = pos.nPos + 1;
1741 CDiskBlockIndex blockindex(pindex);
1742 if (!chaindb.WriteBlockIndex(blockindex))
1743 return error("ConnectBlock() : WriteBlockIndex failed");
1745 // add this block to the view's blockchain
1746 if (!view.SetBestBlock(pindex))
1749 // fees are destroyed to compensate the entire network
1750 if (fDebug && GetBoolArg("-printcreation"))
1751 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1753 // Watch for transactions paying to me
1754 BOOST_FOREACH(CTransaction& tx, vtx)
1755 SyncWithWallets(tx, this, true);
1760 bool CBlock::SetBestChain(CBlockIndex* pindexNew)
1762 CCoinsViewCache &view = *pcoinsTip;
1764 // special case for attaching the genesis block
1765 // note that no ConnectBlock is called, so its coinbase output is non-spendable
1766 if (pindexGenesisBlock == NULL && pindexNew->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1768 view.SetBestBlock(pindexNew);
1771 pindexGenesisBlock = pindexNew;
1772 pindexBest = pindexNew;
1773 hashBestChain = pindexNew->GetBlockHash();
1774 nBestHeight = pindexBest->nHeight;
1775 nBestChainTrust = pindexNew->nChainTrust;
1779 // Find the fork (typically, there is none)
1780 CBlockIndex* pfork = view.GetBestBlock();
1781 CBlockIndex* plonger = pindexNew;
1782 while (pfork != plonger)
1784 while (plonger->nHeight > pfork->nHeight)
1785 if (!(plonger = plonger->pprev))
1786 return error("SetBestChain() : plonger->pprev is null");
1787 if (pfork == plonger)
1789 if (!(pfork = pfork->pprev))
1790 return error("SetBestChain() : pfork->pprev is null");
1793 // List of what to disconnect (typically nothing)
1794 vector<CBlockIndex*> vDisconnect;
1795 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1796 vDisconnect.push_back(pindex);
1798 // List of what to connect (typically only pindexNew)
1799 vector<CBlockIndex*> vConnect;
1800 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1801 vConnect.push_back(pindex);
1802 reverse(vConnect.begin(), vConnect.end());
1804 if (vDisconnect.size() > 0) {
1805 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());
1806 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());
1809 // Disconnect shorter branch
1810 vector<CTransaction> vResurrect;
1811 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
1813 if (!block.ReadFromDisk(pindex))
1814 return error("SetBestBlock() : ReadFromDisk for disconnect failed");
1815 CCoinsViewCache viewTemp(view, true);
1816 if (!block.DisconnectBlock(pindex, viewTemp))
1817 return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1818 if (!viewTemp.Flush())
1819 return error("SetBestBlock() : Cache flush failed after disconnect");
1821 // Queue memory transactions to resurrect
1822 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1823 if (!tx.IsCoinBase() && !tx.IsCoinStake())
1824 vResurrect.push_back(tx);
1827 // Connect longer branch
1828 vector<CTransaction> vDelete;
1829 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
1832 if (pindex == pindexNew) // connecting *this block
1834 else { // other block; read it from disk
1835 if (!block.ReadFromDisk(pindex))
1836 return error("SetBestBlock() : ReadFromDisk for connect failed");
1839 CCoinsViewCache viewTemp(view, true);
1840 if (!pblock->ConnectBlock(pindex, viewTemp)) {
1841 InvalidChainFound(pindexNew);
1842 return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1844 if (!viewTemp.Flush())
1845 return error("SetBestBlock() : Cache flush failed after connect");
1847 // Queue memory transactions to delete
1848 BOOST_FOREACH(const CTransaction& tx, pblock->vtx)
1849 vDelete.push_back(tx);
1852 // Make sure it's successfully written to disk before changing memory structure
1853 bool fIsInitialDownload = IsInitialBlockDownload();
1854 if (!fIsInitialDownload || view.GetCacheSize()>5000)
1858 // At this point, all changes have been done to the database.
1859 // Proceed by updating the memory structures.
1861 // Disconnect shorter branch
1862 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1864 pindex->pprev->pnext = NULL;
1866 // Connect longer branch
1867 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1869 pindex->pprev->pnext = pindex;
1871 // Resurrect memory transactions that were in the disconnected branch
1872 BOOST_FOREACH(CTransaction& tx, vResurrect)
1873 tx.AcceptToMemoryPool(false);
1875 // Delete redundant memory transactions that are in the connected branch
1876 BOOST_FOREACH(CTransaction& tx, vDelete)
1879 // Update best block in wallet (so we can detect restored wallets)
1880 if (!fIsInitialDownload)
1882 const CBlockLocator locator(pindexNew);
1883 ::SetBestChain(locator);
1887 hashBestChain = pindexNew->GetBlockHash();
1888 pindexBest = pindexNew;
1889 pblockindexFBBHLast = NULL;
1890 nBestHeight = pindexBest->nHeight;
1891 nBestChainTrust = pindexNew->nChainTrust;
1892 nTimeBestReceived = GetTime();
1893 nTransactionsUpdated++;
1895 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1897 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1898 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1899 CBigNum(nBestChainTrust).ToString().c_str(),
1900 nBestBlockTrust.Get64(),
1901 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1903 // Check the version of the last 100 blocks to see if we need to upgrade:
1904 if (!fIsInitialDownload)
1907 const CBlockIndex* pindex = pindexBest;
1908 for (int i = 0; i < 100 && pindex != NULL; i++)
1910 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1912 pindex = pindex->pprev;
1915 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1916 if (nUpgraded > 100/2)
1917 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1918 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1921 std::string strCmd = GetArg("-blocknotify", "");
1923 if (!fIsInitialDownload && !strCmd.empty())
1925 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1926 boost::thread t(runCommand, strCmd); // thread runs free
1932 // Total coin age spent in transaction, in the unit of coin-days.
1933 // Only those coins meeting minimum age requirement counts. As those
1934 // transactions not in main chain are not currently indexed so we
1935 // might not find out about their coin age. Older transactions are
1936 // guaranteed to be in main chain by sync-checkpoint. This rule is
1937 // introduced to help nodes establish a consistent view of the coin
1938 // age (trust score) of competing branches.
1939 bool CTransaction::GetCoinAge(uint64& nCoinAge) const
1941 CCoinsViewCache &inputs = *pcoinsTip;
1943 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1949 for (unsigned int i = 0; i < vin.size(); i++)
1951 const COutPoint &prevout = vin[i].prevout;
1953 if (!inputs.GetCoins(prevout.hash, coins))
1956 if (nTime < coins.nTime)
1957 return false; // Transaction timestamp violation
1959 // only count coins meeting min age requirement
1960 if (coins.nBlockTime + nStakeMinAge > nTime)
1963 int64 nValueIn = coins.vout[vin[i].prevout.n].nValue;
1964 bnCentSecond += CBigNum(nValueIn) * (nTime-coins.nTime) / CENT;
1967 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1968 if (fDebug && GetBoolArg("-printcoinage"))
1969 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1970 nCoinAge = bnCoinDay.getuint64();
1974 // Total coin age spent in block, in the unit of coin-days.
1975 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1979 BOOST_FOREACH(const CTransaction& tx, vtx)
1982 if (tx.GetCoinAge(nTxCoinAge))
1983 nCoinAge += nTxCoinAge;
1988 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1990 if (fDebug && GetBoolArg("-printcoinage"))
1991 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1995 bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
1997 // Check for duplicate
1998 uint256 hash = GetHash();
1999 if (mapBlockIndex.count(hash))
2000 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2002 // Construct new block index object
2003 CBlockIndex* pindexNew = new CBlockIndex(*this);
2005 return error("AddToBlockIndex() : new CBlockIndex failed");
2006 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2007 pindexNew->phashBlock = &((*mi).first);
2008 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2009 if (miPrev != mapBlockIndex.end())
2011 pindexNew->pprev = (*miPrev).second;
2012 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2014 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2015 pindexNew->pos = pos;
2016 pindexNew->nUndoPos = 0;
2018 // Compute stake entropy bit for stake modifier
2019 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2020 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2022 // Record proof-of-stake hash value
2023 if (pindexNew->IsProofOfStake())
2025 if (!mapProofOfStake.count(hash))
2026 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2027 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2030 // Compute stake modifier
2031 uint64 nStakeModifier = 0;
2032 bool fGeneratedStakeModifier = false;
2033 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2034 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2035 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2036 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2037 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2038 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2041 if (!chaindb.TxnBegin())
2043 chaindb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2044 if (!chaindb.TxnCommit())
2048 if (!SetBestChain(pindexNew))
2051 if (pindexNew == pindexBest)
2053 // Notify UI to display prev block's coinbase if it was ours
2054 static uint256 hashPrevBestCoinBase;
2055 UpdatedTransaction(hashPrevBestCoinBase);
2056 hashPrevBestCoinBase = vtx[0].GetHash();
2059 uiInterface.NotifyBlocksChanged();
2063 bool FindBlockPos(CChainDB &chaindb, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime)
2065 bool fUpdatedLast = false;
2067 LOCK(cs_LastBlockFile);
2069 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2070 printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
2071 FILE *file = OpenBlockFile(pos);
2074 file = OpenUndoFile(pos);
2078 infoLastBlockFile.SetNull();
2079 chaindb.ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
2080 fUpdatedLast = true;
2083 pos.nFile = nLastBlockFile;
2084 pos.nPos = infoLastBlockFile.nSize;
2085 infoLastBlockFile.nSize += nAddSize;
2086 infoLastBlockFile.AddBlock(nHeight, nTime);
2088 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2089 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2090 if (nNewChunks > nOldChunks) {
2091 FILE *file = OpenBlockFile(pos);
2093 printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2094 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2099 if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2100 return error("FindBlockPos() : cannot write updated block info");
2102 chaindb.WriteLastBlockFile(nLastBlockFile);
2107 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2111 LOCK(cs_LastBlockFile);
2113 unsigned int nNewSize;
2114 if (nFile == nLastBlockFile) {
2115 pos.nPos = infoLastBlockFile.nUndoSize;
2116 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2117 if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2118 return error("FindUndoPos() : cannot write updated block info");
2120 CBlockFileInfo info;
2121 if (!chaindb.ReadBlockFileInfo(nFile, info))
2122 return error("FindUndoPos() : cannot read block info");
2123 pos.nPos = info.nUndoSize;
2124 nNewSize = (info.nUndoSize += nAddSize);
2125 if (!chaindb.WriteBlockFileInfo(nFile, info))
2126 return error("FindUndoPos() : cannot write updated block info");
2129 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2130 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2131 if (nNewChunks > nOldChunks) {
2132 FILE *file = OpenUndoFile(pos);
2134 printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2135 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2143 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2145 // These are checks that are independent of context
2146 // that can be verified before saving an orphan block.
2149 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2150 return DoS(100, error("CheckBlock() : size limits failed"));
2152 // Check proof of work matches claimed amount
2153 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2154 return DoS(50, error("CheckBlock() : proof of work failed"));
2157 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2158 return error("CheckBlock() : block timestamp too far in the future");
2160 // First transaction must be coinbase, the rest must not be
2161 if (vtx.empty() || !vtx[0].IsCoinBase())
2162 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2163 for (unsigned int i = 1; i < vtx.size(); i++)
2164 if (vtx[i].IsCoinBase())
2165 return DoS(100, error("CheckBlock() : more than one coinbase"));
2167 // Check coinbase timestamp
2168 if (GetBlockTime() > FutureDrift((int64)vtx[0].nTime))
2169 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2171 if (IsProofOfStake())
2173 // Coinbase output should be empty if proof-of-stake block
2174 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2175 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2177 // Second transaction must be coinstake, the rest must not be
2178 if (vtx.empty() || !vtx[1].IsCoinStake())
2179 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2180 for (unsigned int i = 2; i < vtx.size(); i++)
2181 if (vtx[i].IsCoinStake())
2182 return DoS(100, error("CheckBlock() : more than one coinstake"));
2184 // Check coinstake timestamp
2185 if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2186 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2190 int64 nReward = GetProofOfWorkReward(nBits);
2191 // Check coinbase reward
2192 if (vtx[0].GetValueOut() > nReward)
2193 return DoS(50, error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
2194 vtx[0].GetValueOut(),
2197 // Should we check proof-of-work block signature or not?
2199 // * Always skip on TestNet
2200 // * Perform checking for the first 9689 blocks
2201 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2203 if(!fTestNet && fCheckSig)
2205 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2207 // check legacy proof-of-work block signature
2208 if (checkEntropySig && !CheckLegacySignature())
2209 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2214 // Check transactions
2215 BOOST_FOREACH(const CTransaction& tx, vtx)
2217 if (!tx.CheckTransaction())
2218 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2220 // check transaction timestamp
2221 if (GetBlockTime() < (int64)tx.nTime)
2222 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2225 // Check for duplicate txids. This is caught by ConnectInputs(),
2226 // but catching it earlier avoids a potential DoS attack:
2227 set<uint256> uniqueTx;
2228 BOOST_FOREACH(const CTransaction& tx, vtx)
2230 uniqueTx.insert(tx.GetHash());
2232 if (uniqueTx.size() != vtx.size())
2233 return DoS(100, error("CheckBlock() : duplicate transaction"));
2235 unsigned int nSigOps = 0;
2236 BOOST_FOREACH(const CTransaction& tx, vtx)
2238 nSigOps += tx.GetLegacySigOpCount();
2240 if (nSigOps > MAX_BLOCK_SIGOPS)
2241 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2243 // Check merkle root
2244 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2245 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2251 bool CBlock::AcceptBlock()
2253 // Check for duplicate
2254 uint256 hash = GetHash();
2255 if (mapBlockIndex.count(hash))
2256 return error("AcceptBlock() : block already in mapBlockIndex");
2258 // Get prev block index
2259 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2260 if (mi == mapBlockIndex.end())
2261 return DoS(10, error("AcceptBlock() : prev block not found"));
2262 CBlockIndex* pindexPrev = (*mi).second;
2263 int nHeight = pindexPrev->nHeight+1;
2265 // Check proof-of-work or proof-of-stake
2266 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2267 return DoS(100, error("AcceptBlock() : incorrect proof-of-%s amount", IsProofOfWork() ? "work" : "stake"));
2269 // Check timestamp against prev
2270 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2271 return error("AcceptBlock() : block's timestamp is too early");
2273 // Check that all transactions are finalized
2274 BOOST_FOREACH(const CTransaction& tx, vtx)
2275 if (!tx.IsFinal(nHeight, GetBlockTime()))
2276 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2278 // Check that the block chain matches the known block chain up to a checkpoint
2279 if (!Checkpoints::CheckHardened(nHeight, hash))
2280 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2282 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2284 // Check that the block satisfies synchronized checkpoint
2285 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2286 return error("AcceptBlock() : rejected by synchronized checkpoint");
2288 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2289 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2291 // Enforce rule that the coinbase starts with serialized block height
2292 CScript expect = CScript() << nHeight;
2293 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2294 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2295 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2297 // Write block to history file
2298 unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
2299 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2300 return error("AcceptBlock() : out of disk space");
2301 CDiskBlockPos blockPos;
2304 if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, nHeight, nTime))
2305 return error("AcceptBlock() : FindBlockPos failed");
2307 if (!WriteToDisk(blockPos))
2308 return error("AcceptBlock() : WriteToDisk failed");
2309 if (!AddToBlockIndex(blockPos))
2310 return error("AcceptBlock() : AddToBlockIndex failed");
2312 // Relay inventory, but don't relay old inventory during initial block download
2313 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2314 if (hashBestChain == hash)
2317 BOOST_FOREACH(CNode* pnode, vNodes)
2318 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2319 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2322 // Check pending sync-checkpoint
2323 Checkpoints::AcceptPendingSyncCheckpoint();
2328 uint256 CBlockIndex::GetBlockTrust() const
2331 bnTarget.SetCompact(nBits);
2337 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2338 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2342 // Calculate work amount for block
2343 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2345 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2346 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2348 // Return nPoWTrust for the first 12 blocks
2349 if (pprev == NULL || pprev->nHeight < 12)
2352 const CBlockIndex* currentIndex = pprev;
2354 if(IsProofOfStake())
2356 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2358 // Return 1/3 of score if parent block is not the PoW block
2359 if (!pprev->IsProofOfWork())
2360 return (bnNewTrust / 3).getuint256();
2364 // Check last 12 blocks type
2365 while (pprev->nHeight - currentIndex->nHeight < 12)
2367 if (currentIndex->IsProofOfWork())
2369 currentIndex = currentIndex->pprev;
2372 // Return 1/3 of score if less than 3 PoW blocks found
2374 return (bnNewTrust / 3).getuint256();
2376 return bnNewTrust.getuint256();
2380 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2382 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2383 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2384 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2388 // Check last 12 blocks type
2389 while (pprev->nHeight - currentIndex->nHeight < 12)
2391 if (currentIndex->IsProofOfStake())
2393 currentIndex = currentIndex->pprev;
2396 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2398 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2400 bnTarget.SetCompact(pprev->nBits);
2405 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2407 // Return nPoWTrust + full trust score for previous block nBits
2408 return nPoWTrust + bnNewTrust.getuint256();
2412 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2414 unsigned int nFound = 0;
2415 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2417 if (pstart->nVersion >= minVersion)
2419 pstart = pstart->pprev;
2421 return (nFound >= nRequired);
2424 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2426 // Check for duplicate
2427 uint256 hash = pblock->GetHash();
2428 if (mapBlockIndex.count(hash))
2429 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2430 if (mapOrphanBlocks.count(hash))
2431 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2433 // Preliminary checks
2434 if (!pblock->CheckBlock())
2435 return error("ProcessBlock() : CheckBlock FAILED");
2437 if (pblock->IsProofOfStake())
2439 // Limited duplicity on stake: prevents block flood attack
2440 // Duplicate stake allowed only when there is orphan child block
2441 if (setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2442 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());
2444 bool fFatal = false;
2445 uint256 hashProofOfStake;
2447 // Verify proof-of-stake hash target and signatures
2448 if (!pblock->CheckSignature(fFatal, hashProofOfStake))
2452 // Invalid blockhash/coinstake signature or no generator defined, nothing to do here
2453 // This also may occur when supplied proof-of-stake doesn't satisfy required target
2455 pfrom->Misbehaving(100);
2456 return error("ProcessBlock() : invalid signature in proof-of-stake block %s", hash.ToString().c_str());
2460 // Blockhash and coinstake signatures are OK but target checkings failed
2461 // This may occur during initial block download
2464 pfrom->Misbehaving(1); // Small DoS penalty
2466 printf("WARNING: ProcessBlock(): proof-of-stake target checkings failed for block %s, we'll try again later\n", hash.ToString().c_str());
2471 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2472 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2475 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2476 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2478 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2479 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2481 bnNewBlock.SetCompact(pblock->nBits);
2484 if (pblock->IsProofOfStake())
2485 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2487 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2489 if (bnNewBlock > bnRequired)
2492 pfrom->Misbehaving(100);
2493 return error("ProcessBlock() : block with too little proof-of-%s", pblock->IsProofOfStake() ? "stake" : "work");
2497 // Ask for pending sync-checkpoint if any
2498 if (!IsInitialBlockDownload())
2499 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2501 // If don't already have its previous block, shunt it off to holding area until we get it
2502 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2504 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2505 CBlock* pblock2 = new CBlock(*pblock);
2507 if (pblock2->IsProofOfStake())
2509 // Limited duplicity on stake: prevents block flood attack
2510 // Duplicate stake allowed only when there is orphan child block
2511 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2512 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());
2514 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2517 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2518 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2520 // Ask this guy to fill in what we're missing
2523 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2524 // ppcoin: getblocks may not obtain the ancestor block rejected
2525 // earlier by duplicate-stake check so we ask for it again directly
2526 if (!IsInitialBlockDownload())
2527 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2533 if (!pblock->AcceptBlock())
2534 return error("ProcessBlock() : AcceptBlock FAILED");
2536 // Recursively process any orphan blocks that depended on this one
2537 vector<uint256> vWorkQueue;
2538 vWorkQueue.push_back(hash);
2539 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2541 uint256 hashPrev = vWorkQueue[i];
2542 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2543 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2546 CBlock* pblockOrphan = (*mi).second;
2547 if (pblockOrphan->AcceptBlock())
2548 vWorkQueue.push_back(pblockOrphan->GetHash());
2549 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2550 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2551 delete pblockOrphan;
2553 mapOrphanBlocksByPrev.erase(hashPrev);
2556 printf("ProcessBlock: ACCEPTED\n");
2558 // ppcoin: if responsible for sync-checkpoint send it
2559 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2560 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2565 // attempt to generate suitable proof-of-stake
2566 bool CBlock::SignBlock(CWallet& wallet)
2568 // if we are trying to sign
2569 // something except proof-of-stake block template
2570 if (!vtx[0].vout[0].IsEmpty())
2573 // if we are trying to sign
2574 // a complete proof-of-stake block
2575 if (IsProofOfStake())
2578 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2581 CTransaction txCoinStake;
2582 int64 nSearchTime = txCoinStake.nTime; // search to current time
2584 if (nSearchTime > nLastCoinStakeSearchTime)
2586 if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2588 if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2590 // make sure coinstake would meet timestamp protocol
2591 // as it would be the same as the block timestamp
2592 vtx[0].nTime = nTime = txCoinStake.nTime;
2593 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2594 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2596 // we have to make sure that we have no future timestamps in
2597 // our transactions set
2598 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2599 if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2601 vtx.insert(vtx.begin() + 1, txCoinStake);
2602 hashMerkleRoot = BuildMerkleTree();
2604 // append a signature to our block
2605 return key.Sign(GetHash(), vchBlockSig);
2608 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2609 nLastCoinStakeSearchTime = nSearchTime;
2615 // get generation key
2616 bool CBlock::GetGenerator(CKey& GeneratorKey) const
2618 if(!IsProofOfStake())
2621 vector<valtype> vSolutions;
2622 txnouttype whichType;
2624 const CTxOut& txout = vtx[1].vout[1];
2626 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2628 if (whichType == TX_PUBKEY)
2630 valtype& vchPubKey = vSolutions[0];
2632 return GeneratorKey.SetPubKey(vchPubKey);
2638 // verify proof-of-stake signatures
2639 bool CBlock::CheckSignature(bool& fFatal, uint256& hashProofOfStake) const
2643 // no generator or invalid hash signature means fatal error
2644 fFatal = !GetGenerator(key) || !key.Verify(GetHash(), vchBlockSig);
2649 uint256 hashTarget = 0;
2650 if (!CheckProofOfStake(vtx[1], nBits, hashProofOfStake, hashTarget, fFatal))
2651 return false; // hash target mismatch or invalid coinstake signature
2656 // verify legacy proof-of-work signature
2657 bool CBlock::CheckLegacySignature() const
2659 if (IsProofOfStake())
2662 vector<valtype> vSolutions;
2663 txnouttype whichType;
2665 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2667 const CTxOut& txout = vtx[0].vout[i];
2669 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2672 if (whichType == TX_PUBKEY)
2675 valtype& vchPubKey = vSolutions[0];
2677 if (!key.SetPubKey(vchPubKey))
2679 if (vchBlockSig.empty())
2681 if(!key.Verify(GetHash(), vchBlockSig))
2690 bool CheckDiskSpace(uint64 nAdditionalBytes)
2692 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2694 // Check for nMinDiskSpace bytes (currently 50MB)
2695 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2698 string strMessage = _("Warning: Disk space is low!");
2699 strMiscWarning = strMessage;
2700 printf("*** %s\n", strMessage.c_str());
2701 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2709 CCriticalSection cs_LastBlockFile;
2710 CBlockFileInfo infoLastBlockFile;
2711 int nLastBlockFile = 0;
2713 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2717 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2718 boost::filesystem::create_directories(path.parent_path());
2719 FILE* file = fopen(path.string().c_str(), "rb+");
2720 if (!file && !fReadOnly)
2721 file = fopen(path.string().c_str(), "wb+");
2723 printf("Unable to open file %s\n", path.string().c_str());
2727 if (fseek(file, pos.nPos, SEEK_SET)) {
2728 printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2736 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2737 return OpenDiskFile(pos, "blk", fReadOnly);
2740 FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2741 return OpenDiskFile(pos, "rev", fReadOnly);
2744 bool LoadBlockIndex(bool fAllowNew)
2746 CBigNum bnTrustedModulus;
2750 pchMessageStart[0] = 0xcd;
2751 pchMessageStart[1] = 0xf2;
2752 pchMessageStart[2] = 0xc0;
2753 pchMessageStart[3] = 0xef;
2755 bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
2756 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2757 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2758 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2759 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2760 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2764 bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
2767 // Set up the Zerocoin Params object
2768 ZCParams = new libzerocoin::Params(bnTrustedModulus);
2773 CChainDB chaindb("cr");
2774 if (!LoadBlockIndex(chaindb))
2779 // Init with genesis block
2781 if (mapBlockIndex.empty())
2790 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2791 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2792 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2794 // vMerkleTree: 4cb33b3b6a
2798 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2799 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2800 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2802 // vMerkleTree: 4cb33b3b6a
2804 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2806 txNew.nTime = 1360105017;
2807 txNew.vin.resize(1);
2808 txNew.vout.resize(1);
2809 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2810 txNew.vout[0].SetEmpty();
2812 block.vtx.push_back(txNew);
2813 block.hashPrevBlock = 0;
2814 block.hashMerkleRoot = block.BuildMerkleTree();
2816 block.nTime = 1360105017;
2817 block.nBits = bnProofOfWorkLimit.GetCompact();
2818 block.nNonce = !fTestNet ? 1575379 : 46534;
2821 uint256 hash = block.GetHash();
2822 printf("%s\n", hash.ToString().c_str());
2823 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2825 assert(hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2826 assert(block.CheckBlock());
2828 // Start new block file
2829 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2830 CDiskBlockPos blockPos;
2833 if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, 0, block.nTime))
2834 return error("AcceptBlock() : FindBlockPos failed");
2836 if (!block.WriteToDisk(blockPos))
2837 return error("LoadBlockIndex() : writing genesis block to disk failed");
2838 if (!block.AddToBlockIndex(blockPos))
2839 return error("LoadBlockIndex() : genesis block not accepted");
2841 // initialize synchronized checkpoint
2842 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2843 return error("LoadBlockIndex() : failed to init sync checkpoint");
2846 string strPubKey = "";
2849 // if checkpoint master key changed must reset sync-checkpoint
2850 if (!chaindb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2852 // write checkpoint master key to db
2854 if (!chaindb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2855 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2856 if (!chaindb.TxnCommit())
2857 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2858 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2859 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2866 void PrintBlockTree()
2868 // pre-compute tree structure
2869 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2870 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2872 CBlockIndex* pindex = (*mi).second;
2873 mapNext[pindex->pprev].push_back(pindex);
2875 //while (rand() % 3 == 0)
2876 // mapNext[pindex->pprev].push_back(pindex);
2879 vector<pair<int, CBlockIndex*> > vStack;
2880 vStack.push_back(make_pair(0, pindexGenesisBlock));
2883 while (!vStack.empty())
2885 int nCol = vStack.back().first;
2886 CBlockIndex* pindex = vStack.back().second;
2889 // print split or gap
2890 if (nCol > nPrevCol)
2892 for (int i = 0; i < nCol-1; i++)
2896 else if (nCol < nPrevCol)
2898 for (int i = 0; i < nCol; i++)
2905 for (int i = 0; i < nCol; i++)
2910 block.ReadFromDisk(pindex);
2911 printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
2913 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2914 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2917 PrintWallets(block);
2919 // put the main time-chain first
2920 vector<CBlockIndex*>& vNext = mapNext[pindex];
2921 for (unsigned int i = 0; i < vNext.size(); i++)
2923 if (vNext[i]->pnext)
2925 swap(vNext[0], vNext[i]);
2931 for (unsigned int i = 0; i < vNext.size(); i++)
2932 vStack.push_back(make_pair(nCol+i, vNext[i]));
2936 bool LoadExternalBlockFile(FILE* fileIn)
2938 int64 nStart = GetTimeMillis();
2944 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2945 unsigned int nPos = 0;
2946 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2948 unsigned char pchData[65536];
2950 fseek(blkdat, nPos, SEEK_SET);
2951 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2954 nPos = (unsigned int)-1;
2957 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2960 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2962 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2965 nPos += ((unsigned char*)nFind - pchData) + 1;
2968 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2969 } while(!fRequestShutdown);
2970 if (nPos == (unsigned int)-1)
2972 fseek(blkdat, nPos, SEEK_SET);
2975 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2979 if (ProcessBlock(NULL,&block))
2987 catch (std::exception &e) {
2988 printf("%s() : Deserialize or I/O error caught during load\n",
2989 __PRETTY_FUNCTION__);
2992 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2996 //////////////////////////////////////////////////////////////////////////////
3001 extern map<uint256, CAlert> mapAlerts;
3002 extern CCriticalSection cs_mapAlerts;
3004 extern string strMintMessage;
3005 extern string strMintWarning;
3007 string GetWarnings(string strFor)
3010 string strStatusBar;
3013 if (GetBoolArg("-testsafemode"))
3016 // ppcoin: wallet lock warning for minting
3017 if (strMintWarning != "")
3020 strStatusBar = strMintWarning;
3023 // Misc warnings like out of disk space and clock is wrong
3024 if (strMiscWarning != "")
3027 strStatusBar = strMiscWarning;
3030 // * Should not enter safe mode for longer invalid chain
3031 // * If sync-checkpoint is too old do not enter safe mode
3032 // * Display warning only in the STRICT mode
3033 if (CheckpointsMode == Checkpoints::STRICT && Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) &&
3034 !fTestNet && !IsInitialBlockDownload())
3037 strStatusBar = _("WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.");
3040 // ppcoin: if detected invalid checkpoint enter safe mode
3041 if (Checkpoints::hashInvalidCheckpoint != 0)
3044 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3050 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3052 const CAlert& alert = item.second;
3053 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3055 nPriority = alert.nPriority;
3056 strStatusBar = alert.strStatusBar;
3057 if (nPriority > 1000)
3058 strRPC = strStatusBar;
3063 if (strFor == "statusbar")
3064 return strStatusBar;
3065 else if (strFor == "rpc")
3067 assert(!"GetWarnings() : invalid parameter");
3078 //////////////////////////////////////////////////////////////////////////////
3084 bool static AlreadyHave(const CInv& inv)
3090 bool txInMap = false;
3093 txInMap = mempool.exists(inv.hash);
3095 return txInMap || mapOrphanTransactions.count(inv.hash) ||
3096 pcoinsTip->HaveCoins(inv.hash);
3099 return mapBlockIndex.count(inv.hash) ||
3100 mapOrphanBlocks.count(inv.hash);
3102 // Don't know what it is, just say we already got one
3109 // The message start string is designed to be unlikely to occur in normal data.
3110 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3111 // a large 4-byte int at any alignment.
3112 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3114 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3116 static map<CService, CPubKey> mapReuseKey;
3117 RandAddSeedPerfmon();
3119 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3120 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3122 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3126 if (strCommand == "version")
3128 // Each connection can only send one version message
3129 if (pfrom->nVersion != 0)
3131 pfrom->Misbehaving(1);
3139 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3140 if (pfrom->nVersion < MIN_PROTO_VERSION)
3142 // Since February 20, 2012, the protocol is initiated at version 209,
3143 // and earlier versions are no longer supported
3144 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3145 pfrom->fDisconnect = true;
3149 if (pfrom->nVersion == 10300)
3150 pfrom->nVersion = 300;
3152 vRecv >> addrFrom >> nNonce;
3154 vRecv >> pfrom->strSubVer;
3156 vRecv >> pfrom->nStartingHeight;
3158 if (pfrom->fInbound && addrMe.IsRoutable())
3160 pfrom->addrLocal = addrMe;
3164 // Disconnect if we connected to ourself
3165 if (nNonce == nLocalHostNonce && nNonce > 1)
3167 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3168 pfrom->fDisconnect = true;
3172 // record my external IP reported by peer
3173 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3174 addrSeenByPeer = addrMe;
3176 // Be shy and don't send version until we hear
3177 if (pfrom->fInbound)
3178 pfrom->PushVersion();
3180 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3182 AddTimeData(pfrom->addr, nTime);
3185 pfrom->PushMessage("verack");
3186 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3188 if (!pfrom->fInbound)
3190 // Advertise our address
3191 if (!fNoListen && !IsInitialBlockDownload())
3193 CAddress addr = GetLocalAddress(&pfrom->addr);
3194 if (addr.IsRoutable())
3195 pfrom->PushAddress(addr);
3198 // Get recent addresses
3199 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3201 pfrom->PushMessage("getaddr");
3202 pfrom->fGetAddr = true;
3204 addrman.Good(pfrom->addr);
3206 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3208 addrman.Add(addrFrom, addrFrom);
3209 addrman.Good(addrFrom);
3213 // Ask the first connected node for block updates
3214 static int nAskedForBlocks = 0;
3215 if (!pfrom->fClient && !pfrom->fOneShot &&
3216 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3217 (pfrom->nVersion < NOBLKS_VERSION_START ||
3218 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3219 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3222 pfrom->PushGetBlocks(pindexBest, uint256(0));
3228 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3229 item.second.RelayTo(pfrom);
3232 // Relay sync-checkpoint
3234 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3235 if (!Checkpoints::checkpointMessage.IsNull())
3236 Checkpoints::checkpointMessage.RelayTo(pfrom);
3239 pfrom->fSuccessfullyConnected = true;
3241 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());
3243 cPeerBlockCounts.input(pfrom->nStartingHeight);
3245 // ppcoin: ask for pending sync-checkpoint if any
3246 if (!IsInitialBlockDownload())
3247 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3251 else if (pfrom->nVersion == 0)
3253 // Must have a version message before anything else
3254 pfrom->Misbehaving(1);
3259 else if (strCommand == "verack")
3261 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3265 else if (strCommand == "addr")
3267 vector<CAddress> vAddr;
3270 // Don't want addr from older versions unless seeding
3271 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3273 if (vAddr.size() > 1000)
3275 pfrom->Misbehaving(20);
3276 return error("message addr size() = %"PRIszu"", vAddr.size());
3279 // Store the new addresses
3280 vector<CAddress> vAddrOk;
3281 int64 nNow = GetAdjustedTime();
3282 int64 nSince = nNow - 10 * 60;
3283 BOOST_FOREACH(CAddress& addr, vAddr)
3287 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3288 addr.nTime = nNow - 5 * 24 * 60 * 60;
3289 pfrom->AddAddressKnown(addr);
3290 bool fReachable = IsReachable(addr);
3291 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3293 // Relay to a limited number of other nodes
3296 // Use deterministic randomness to send to the same nodes for 24 hours
3297 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3298 static uint256 hashSalt;
3300 hashSalt = GetRandHash();
3301 uint64 hashAddr = addr.GetHash();
3302 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3303 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3304 multimap<uint256, CNode*> mapMix;
3305 BOOST_FOREACH(CNode* pnode, vNodes)
3307 if (pnode->nVersion < CADDR_TIME_VERSION)
3309 unsigned int nPointer;
3310 memcpy(&nPointer, &pnode, sizeof(nPointer));
3311 uint256 hashKey = hashRand ^ nPointer;
3312 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3313 mapMix.insert(make_pair(hashKey, pnode));
3315 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3316 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3317 ((*mi).second)->PushAddress(addr);
3320 // Do not store addresses outside our network
3322 vAddrOk.push_back(addr);
3324 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3325 if (vAddr.size() < 1000)
3326 pfrom->fGetAddr = false;
3327 if (pfrom->fOneShot)
3328 pfrom->fDisconnect = true;
3331 else if (strCommand == "inv")
3335 if (vInv.size() > MAX_INV_SZ)
3337 pfrom->Misbehaving(20);
3338 return error("message inv size() = %"PRIszu"", vInv.size());
3341 // find last block in inv vector
3342 unsigned int nLastBlock = (unsigned int)(-1);
3343 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3344 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3345 nLastBlock = vInv.size() - 1 - nInv;
3349 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3351 const CInv &inv = vInv[nInv];
3355 pfrom->AddInventoryKnown(inv);
3357 bool fAlreadyHave = AlreadyHave(inv);
3359 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3363 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3364 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3365 } else if (nInv == nLastBlock) {
3366 // In case we are on a very long side-chain, it is possible that we already have
3367 // the last block in an inv bundle sent in response to getblocks. Try to detect
3368 // this situation and push another getblocks to continue.
3369 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3371 printf("force request: %s\n", inv.ToString().c_str());
3374 // Track requests for our stuff
3375 Inventory(inv.hash);
3380 else if (strCommand == "getdata")
3384 if (vInv.size() > MAX_INV_SZ)
3386 pfrom->Misbehaving(20);
3387 return error("message getdata size() = %"PRIszu"", vInv.size());
3390 if (fDebugNet || (vInv.size() != 1))
3391 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3393 BOOST_FOREACH(const CInv& inv, vInv)
3397 if (fDebugNet || (vInv.size() == 1))
3398 printf("received getdata for: %s\n", inv.ToString().c_str());
3400 if (inv.type == MSG_BLOCK)
3402 // Send block from disk
3403 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3404 if (mi != mapBlockIndex.end())
3407 block.ReadFromDisk((*mi).second);
3408 pfrom->PushMessage("block", block);
3410 // Trigger them to send a getblocks request for the next batch of inventory
3411 if (inv.hash == pfrom->hashContinue)
3413 // ppcoin: send latest proof-of-work block to allow the
3414 // download node to accept as orphan (proof-of-stake
3415 // block might be rejected by stake connection check)
3417 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3418 pfrom->PushMessage("inv", vInv);
3419 pfrom->hashContinue = 0;
3423 else if (inv.IsKnownType())
3425 // Send stream from relay memory
3426 bool pushed = false;
3429 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3430 if (mi != mapRelay.end()) {
3431 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3435 if (!pushed && inv.type == MSG_TX) {
3437 if (mempool.exists(inv.hash)) {
3438 CTransaction tx = mempool.lookup(inv.hash);
3439 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3442 pfrom->PushMessage("tx", ss);
3447 // Track requests for our stuff
3448 Inventory(inv.hash);
3453 else if (strCommand == "getblocks")
3455 CBlockLocator locator;
3457 vRecv >> locator >> hashStop;
3459 // Find the last block the caller has in the main chain
3460 CBlockIndex* pindex = locator.GetBlockIndex();
3462 // Send the rest of the chain
3464 pindex = pindex->pnext;
3466 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3467 for (; pindex; pindex = pindex->pnext)
3469 if (pindex->GetBlockHash() == hashStop)
3471 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3472 // ppcoin: tell downloading node about the latest block if it's
3473 // without risk being rejected due to stake connection check
3474 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3475 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3478 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3481 // When this block is requested, we'll send an inv that'll make them
3482 // getblocks the next batch of inventory.
3483 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3484 pfrom->hashContinue = pindex->GetBlockHash();
3489 else if (strCommand == "checkpoint")
3491 CSyncCheckpoint checkpoint;
3492 vRecv >> checkpoint;
3494 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3497 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3499 BOOST_FOREACH(CNode* pnode, vNodes)
3500 checkpoint.RelayTo(pnode);
3504 else if (strCommand == "getheaders")
3506 CBlockLocator locator;
3508 vRecv >> locator >> hashStop;
3510 CBlockIndex* pindex = NULL;
3511 if (locator.IsNull())
3513 // If locator is null, return the hashStop block
3514 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3515 if (mi == mapBlockIndex.end())
3517 pindex = (*mi).second;
3521 // Find the last block the caller has in the main chain
3522 pindex = locator.GetBlockIndex();
3524 pindex = pindex->pnext;
3527 vector<CBlock> vHeaders;
3529 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3530 for (; pindex; pindex = pindex->pnext)
3532 vHeaders.push_back(pindex->GetBlockHeader());
3533 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3536 pfrom->PushMessage("headers", vHeaders);
3540 else if (strCommand == "tx")
3542 vector<uint256> vWorkQueue;
3543 vector<uint256> vEraseQueue;
3544 CDataStream vMsg(vRecv);
3548 CInv inv(MSG_TX, tx.GetHash());
3549 pfrom->AddInventoryKnown(inv);
3551 bool fMissingInputs = false;
3552 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
3554 SyncWithWallets(tx, NULL, true);
3555 RelayTransaction(tx, inv.hash);
3556 mapAlreadyAskedFor.erase(inv);
3557 vWorkQueue.push_back(inv.hash);
3558 vEraseQueue.push_back(inv.hash);
3560 // Recursively process any orphan transactions that depended on this one
3561 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3563 uint256 hashPrev = vWorkQueue[i];
3564 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3565 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3568 const uint256& orphanTxHash = *mi;
3569 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3570 bool fMissingInputs2 = false;
3572 if (orphanTx.AcceptToMemoryPool(true, &fMissingInputs2))
3574 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3575 SyncWithWallets(tx, NULL, true);
3576 RelayTransaction(orphanTx, orphanTxHash);
3577 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3578 vWorkQueue.push_back(orphanTxHash);
3579 vEraseQueue.push_back(orphanTxHash);
3581 else if (!fMissingInputs2)
3584 vEraseQueue.push_back(orphanTxHash);
3585 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3590 BOOST_FOREACH(uint256 hash, vEraseQueue)
3591 EraseOrphanTx(hash);
3593 else if (fMissingInputs)
3597 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3598 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3600 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3602 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3606 else if (strCommand == "block")
3610 uint256 hashBlock = block.GetHash();
3612 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3615 CInv inv(MSG_BLOCK, hashBlock);
3616 pfrom->AddInventoryKnown(inv);
3618 if (ProcessBlock(pfrom, &block))
3619 mapAlreadyAskedFor.erase(inv);
3620 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3624 else if (strCommand == "getaddr")
3626 // Don't return addresses older than nCutOff timestamp
3627 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3628 pfrom->vAddrToSend.clear();
3629 vector<CAddress> vAddr = addrman.GetAddr();
3630 BOOST_FOREACH(const CAddress &addr, vAddr)
3631 if(addr.nTime > nCutOff)
3632 pfrom->PushAddress(addr);
3636 else if (strCommand == "mempool")
3638 std::vector<uint256> vtxid;
3639 mempool.queryHashes(vtxid);
3641 for (unsigned int i = 0; i < vtxid.size(); i++) {
3642 CInv inv(MSG_TX, vtxid[i]);
3643 vInv.push_back(inv);
3644 if (i == (MAX_INV_SZ - 1))
3647 if (vInv.size() > 0)
3648 pfrom->PushMessage("inv", vInv);
3652 else if (strCommand == "checkorder")
3657 if (!GetBoolArg("-allowreceivebyip"))
3659 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3666 /// we have a chance to check the order here
3668 // Keep giving the same key to the same ip until they use it
3669 if (!mapReuseKey.count(pfrom->addr))
3670 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3672 // Send back approval of order and pubkey to use
3673 CScript scriptPubKey;
3674 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3675 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3679 else if (strCommand == "reply")
3684 CRequestTracker tracker;
3686 LOCK(pfrom->cs_mapRequests);
3687 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3688 if (mi != pfrom->mapRequests.end())
3690 tracker = (*mi).second;
3691 pfrom->mapRequests.erase(mi);
3694 if (!tracker.IsNull())
3695 tracker.fn(tracker.param1, vRecv);
3699 else if (strCommand == "ping")
3701 if (pfrom->nVersion > BIP0031_VERSION)
3705 // Echo the message back with the nonce. This allows for two useful features:
3707 // 1) A remote node can quickly check if the connection is operational
3708 // 2) Remote nodes can measure the latency of the network thread. If this node
3709 // is overloaded it won't respond to pings quickly and the remote node can
3710 // avoid sending us more work, like chain download requests.
3712 // The nonce stops the remote getting confused between different pings: without
3713 // it, if the remote node sends a ping once per second and this node takes 5
3714 // seconds to respond to each, the 5th ping the remote sends would appear to
3715 // return very quickly.
3716 pfrom->PushMessage("pong", nonce);
3721 else if (strCommand == "alert")
3726 uint256 alertHash = alert.GetHash();
3727 if (pfrom->setKnown.count(alertHash) == 0)
3729 if (alert.ProcessAlert())
3732 pfrom->setKnown.insert(alertHash);
3735 BOOST_FOREACH(CNode* pnode, vNodes)
3736 alert.RelayTo(pnode);
3740 // Small DoS penalty so peers that send us lots of
3741 // duplicate/expired/invalid-signature/whatever alerts
3742 // eventually get banned.
3743 // This isn't a Misbehaving(100) (immediate ban) because the
3744 // peer might be an older or different implementation with
3745 // a different signature key, etc.
3746 pfrom->Misbehaving(10);
3754 // Ignore unknown commands for extensibility
3758 // Update the last seen time for this node's address
3759 if (pfrom->fNetworkNode)
3760 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3761 AddressCurrentlyConnected(pfrom->addr);
3767 bool ProcessMessages(CNode* pfrom)
3769 CDataStream& vRecv = pfrom->vRecv;
3773 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3777 // (4) message start
3786 // Don't bother if send buffer is too full to respond anyway
3787 if (pfrom->vSend.size() >= SendBufferSize())
3790 // Scan for message start
3791 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3792 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3793 if (vRecv.end() - pstart < nHeaderSize)
3795 if ((int)vRecv.size() > nHeaderSize)
3797 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3798 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3802 if (pstart - vRecv.begin() > 0)
3803 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3804 vRecv.erase(vRecv.begin(), pstart);
3807 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3812 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3815 string strCommand = hdr.GetCommand();
3818 unsigned int nMessageSize = hdr.nMessageSize;
3819 if (nMessageSize > MAX_SIZE)
3821 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3824 if (nMessageSize > vRecv.size())
3826 // Rewind and wait for rest of message
3827 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3832 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3833 unsigned int nChecksum = 0;
3834 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3835 if (nChecksum != hdr.nChecksum)
3837 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3838 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3842 // Copy message to its own buffer
3843 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3844 vRecv.ignore(nMessageSize);
3852 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3857 catch (std::ios_base::failure& e)
3859 if (strstr(e.what(), "end of data"))
3861 // Allow exceptions from under-length message on vRecv
3862 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());
3864 else if (strstr(e.what(), "size too large"))
3866 // Allow exceptions from over-long size
3867 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3871 PrintExceptionContinue(&e, "ProcessMessages()");
3874 catch (std::exception& e) {
3875 PrintExceptionContinue(&e, "ProcessMessages()");
3877 PrintExceptionContinue(NULL, "ProcessMessages()");
3881 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3889 bool SendMessages(CNode* pto, bool fSendTrickle)
3891 TRY_LOCK(cs_main, lockMain);
3893 // Don't send anything until we get their version message
3894 if (pto->nVersion == 0)
3897 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3899 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3901 if (pto->nVersion > BIP0031_VERSION)
3902 pto->PushMessage("ping", nonce);
3904 pto->PushMessage("ping");
3907 // Resend wallet transactions that haven't gotten in a block yet
3908 ResendWalletTransactions();
3910 // Address refresh broadcast
3911 static int64 nLastRebroadcast;
3912 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3916 BOOST_FOREACH(CNode* pnode, vNodes)
3918 // Periodically clear setAddrKnown to allow refresh broadcasts
3919 if (nLastRebroadcast)
3920 pnode->setAddrKnown.clear();
3922 // Rebroadcast our address
3925 CAddress addr = GetLocalAddress(&pnode->addr);
3926 if (addr.IsRoutable())
3927 pnode->PushAddress(addr);
3931 nLastRebroadcast = GetTime();
3939 vector<CAddress> vAddr;
3940 vAddr.reserve(pto->vAddrToSend.size());
3941 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3943 // returns true if wasn't already contained in the set
3944 if (pto->setAddrKnown.insert(addr).second)
3946 vAddr.push_back(addr);
3947 // receiver rejects addr messages larger than 1000
3948 if (vAddr.size() >= 1000)
3950 pto->PushMessage("addr", vAddr);
3955 pto->vAddrToSend.clear();
3957 pto->PushMessage("addr", vAddr);
3962 // Message: inventory
3965 vector<CInv> vInvWait;
3967 LOCK(pto->cs_inventory);
3968 vInv.reserve(pto->vInventoryToSend.size());
3969 vInvWait.reserve(pto->vInventoryToSend.size());
3970 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3972 if (pto->setInventoryKnown.count(inv))
3975 // trickle out tx inv to protect privacy
3976 if (inv.type == MSG_TX && !fSendTrickle)
3978 // 1/4 of tx invs blast to all immediately
3979 static uint256 hashSalt;
3981 hashSalt = GetRandHash();
3982 uint256 hashRand = inv.hash ^ hashSalt;
3983 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3984 bool fTrickleWait = ((hashRand & 3) != 0);
3986 // always trickle our own transactions
3990 if (GetTransaction(inv.hash, wtx))
3992 fTrickleWait = true;
3997 vInvWait.push_back(inv);
4002 // returns true if wasn't already contained in the set
4003 if (pto->setInventoryKnown.insert(inv).second)
4005 vInv.push_back(inv);
4006 if (vInv.size() >= 1000)
4008 pto->PushMessage("inv", vInv);
4013 pto->vInventoryToSend = vInvWait;
4016 pto->PushMessage("inv", vInv);
4022 vector<CInv> vGetData;
4023 int64 nNow = GetTime() * 1000000;
4024 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4026 const CInv& inv = (*pto->mapAskFor.begin()).second;
4027 if (!AlreadyHave(inv))
4030 printf("sending getdata: %s\n", inv.ToString().c_str());
4031 vGetData.push_back(inv);
4032 if (vGetData.size() >= 1000)
4034 pto->PushMessage("getdata", vGetData);
4037 mapAlreadyAskedFor[inv] = nNow;
4039 pto->mapAskFor.erase(pto->mapAskFor.begin());
4041 if (!vGetData.empty())
4042 pto->PushMessage("getdata", vGetData);
4048 // Amount compression:
4049 // * If the amount is 0, output 0
4050 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
4051 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
4052 // * call the result n
4053 // * output 1 + 10*(9*n + d - 1) + e
4054 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
4055 // (this is decodable, as d is in [1-9] and e is in [0-9])
4057 uint64 CTxOutCompressor::CompressAmount(uint64 n)
4062 while (((n % 10) == 0) && e < 9) {
4068 assert(d >= 1 && d <= 9);
4070 return 1 + (n*9 + d - 1)*10 + e;
4072 return 1 + (n - 1)*10 + 9;
4076 uint64 CTxOutCompressor::DecompressAmount(uint64 x)
4078 // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
4082 // x = 10*(9*n + d - 1) + e
4088 int d = (x % 9) + 1;