1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
11 #include "ui_interface.h"
13 #include "zerocoin/Zerocoin.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
20 using namespace boost;
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
29 CCriticalSection cs_main;
32 unsigned int nTransactionsUpdated = 0;
34 map<uint256, CBlockIndex*> mapBlockIndex;
35 set<pair<COutPoint, unsigned int> > setStakeSeen;
36 libzerocoin::Params* ZCParams;
38 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
39 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
40 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
41 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
42 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
44 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
46 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as zero time weight
47 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
48 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
49 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
51 int nCoinbaseMaturity = 500;
52 CBlockIndex* pindexGenesisBlock = NULL;
55 uint256 nBestChainTrust = 0;
56 uint256 nBestInvalidTrust = 0;
58 uint256 hashBestChain = 0;
59 CBlockIndex* pindexBest = NULL;
60 int64 nTimeBestReceived = 0;
62 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
64 map<uint256, CBlock*> mapOrphanBlocks;
65 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
66 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
67 map<uint256, uint256> mapProofOfStake;
69 map<uint256, CTransaction> mapOrphanTransactions;
70 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
72 // Constant stuff for coinbase transactions we create:
73 CScript COINBASE_FLAGS;
75 const string strMessageMagic = "NovaCoin Signed Message:\n";
78 int64 nTransactionFee = MIN_TX_FEE;
79 int64 nMinimumInputValue = MIN_TX_FEE;
81 extern enum Checkpoints::CPMode CheckpointsMode;
83 //////////////////////////////////////////////////////////////////////////////
85 // dispatching functions
88 // These functions dispatch to one or all registered wallets
91 void RegisterWallet(CWallet* pwalletIn)
94 LOCK(cs_setpwalletRegistered);
95 setpwalletRegistered.insert(pwalletIn);
99 void UnregisterWallet(CWallet* pwalletIn)
102 LOCK(cs_setpwalletRegistered);
103 setpwalletRegistered.erase(pwalletIn);
107 // check whether the passed transaction is from us
108 bool static IsFromMe(CTransaction& tx)
110 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
111 if (pwallet->IsFromMe(tx))
116 // get the wallet transaction with the given hash (if it exists)
117 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
119 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
120 if (pwallet->GetTransaction(hashTx,wtx))
125 // erases transaction with the given hash from all wallets
126 void static EraseFromWallets(uint256 hash)
128 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
129 pwallet->EraseFromWallet(hash);
132 // make sure all wallets know about the given transaction, in the given block
133 void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
137 // ppcoin: wallets need to refund inputs when disconnecting coinstake
138 if (tx.IsCoinStake())
140 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
141 if (pwallet->IsFromMe(tx))
142 pwallet->DisableTransaction(tx);
147 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
148 pwallet->AddToWalletIfInvolvingMe(hash, tx, pblock, fUpdate);
151 // notify wallets about a new best chain
152 void static SetBestChain(const CBlockLocator& loc)
154 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
155 pwallet->SetBestChain(loc);
158 // notify wallets about an updated transaction
159 void static UpdatedTransaction(const uint256& hashTx)
161 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
162 pwallet->UpdatedTransaction(hashTx);
166 void static PrintWallets(const CBlock& block)
168 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
169 pwallet->PrintWallet(block);
172 // notify wallets about an incoming inventory (for request counts)
173 void static Inventory(const uint256& hash)
175 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
176 pwallet->Inventory(hash);
179 // ask wallets to resend their transactions
180 void ResendWalletTransactions()
182 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
183 pwallet->ResendWalletTransactions();
187 //////////////////////////////////////////////////////////////////////////////
189 // CCoinsView implementations
192 bool CCoinsView::GetCoins(uint256 txid, CCoins &coins) { return false; }
193 bool CCoinsView::SetCoins(uint256 txid, const CCoins &coins) { return false; }
194 bool CCoinsView::HaveCoins(uint256 txid) { return false; }
195 CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
196 bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
197 bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
199 CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
200 bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); }
201 bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
202 bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); }
203 CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
204 bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
205 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
207 bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
209 CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
211 bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) {
212 if (cacheCoins.count(txid)) {
213 coins = cacheCoins[txid];
216 if (base->GetCoins(txid, coins)) {
217 cacheCoins[txid] = coins;
223 // Select coins from read-only cache or database
224 bool CCoinsViewCache::GetCoinsReadOnly(uint256 txid, CCoins &coins) {
225 if (cacheCoins.count(txid)) {
226 coins = cacheCoins[txid]; // get from cache
229 if (cacheCoinsReadOnly.count(txid)) {
230 coins = cacheCoinsReadOnly[txid]; // get from read-only cache
233 if (base->GetCoins(txid, coins)) {
234 cacheCoinsReadOnly[txid] = coins; // save to read-only cache
240 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 uint256 &txhash) const
1356 // mark inputs spent
1357 if (!IsCoinBase()) {
1358 BOOST_FOREACH(const CTxIn &txin, vin) {
1360 if (!inputs.GetCoins(txin.prevout.hash, coins))
1361 return error("UpdateCoins() : cannot find prevtx");
1362 if (coins.nTime > nTimeStamp)
1363 return error("UpdateCoins() : timestamp violation");
1365 if (!coins.Spend(txin.prevout, undo))
1366 return error("UpdateCoins() : cannot spend input");
1367 txundo.vprevout.push_back(undo);
1368 if (!inputs.SetCoins(txin.prevout.hash, coins))
1369 return error("UpdateCoins() : cannot update input");
1374 if (!inputs.SetCoins(txhash, CCoins(*this, nHeight, nTimeStamp)))
1375 return error("UpdateCoins() : cannot update output");
1380 bool CTransaction::HaveInputs(CCoinsView &inputs) const
1382 if (!IsCoinBase()) {
1383 // first check whether information about the prevout hash is available
1384 for (unsigned int i = 0; i < vin.size(); i++) {
1385 const COutPoint &prevout = vin[i].prevout;
1386 if (!inputs.HaveCoins(prevout.hash))
1390 // then check whether the actual outputs are available
1391 for (unsigned int i = 0; i < vin.size(); i++) {
1392 const COutPoint &prevout = vin[i].prevout;
1394 inputs.GetCoins(prevout.hash, coins);
1395 if (!coins.IsAvailable(prevout.n))
1402 bool CTransaction::CheckInputs(CCoinsView &inputs, enum CheckSig_mode csmode, bool fStrictPayToScriptHash, bool fStrictEncodings, CBlock *pblock) const
1408 for (unsigned int i = 0; i < vin.size(); i++)
1410 const COutPoint &prevout = vin[i].prevout;
1412 if (!inputs.GetCoins(prevout.hash, coins))
1413 return error("CheckInputs() : cannot find prevout tx");
1415 // Check for conflicts (double-spend)
1416 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1417 // for an attacker to attempt to split the network.
1418 if (!coins.IsAvailable(prevout.n))
1419 return error("CheckInputs() : %s prev tx already used", GetHash().ToString().substr(0,10).c_str());
1421 // If prev is coinbase or coinstake, check that it's matured
1422 if (coins.IsCoinBase() || coins.IsCoinStake()) {
1423 CBlockIndex *pindexBlock = inputs.GetBestBlock();
1424 if (pindexBlock->nHeight - coins.nHeight < nCoinbaseMaturity)
1425 return error("CheckInputs() : tried to spend %s at depth %d", coins.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - coins.nHeight);
1428 // Check transaction timestamp
1429 if (coins.nTime > nTime)
1430 return DoS(100, error("CheckInputs() : transaction timestamp earlier than input transaction"));
1432 // Check for negative or overflow input values
1433 nValueIn += coins.vout[prevout.n].nValue;
1434 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1435 return DoS(100, error("CheckInputs() : txin values out of range"));
1441 return error("CheckInputs() : %s is a coinstake, but no block specified", GetHash().ToString().substr(0,10).c_str());
1443 // Coin stake tx earns reward instead of paying fee
1445 if (!GetCoinAge(nCoinAge))
1446 return error("CheckInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1448 int64 nStakeReward = GetValueOut() - nValueIn;
1449 int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pblock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1451 if (nStakeReward > nCalculatedStakeReward)
1452 return DoS(100, error("CheckInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1456 if (nValueIn < GetValueOut())
1457 return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1459 // Tally transaction fees
1460 int64 nTxFee = nValueIn - GetValueOut();
1462 return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1464 if (!MoneyRange(nFees))
1465 return DoS(100, error("CheckInputs() : nFees out of range"));
1467 // enforce transaction fees for every block until 1 May 2014 04:00:00 GMT
1468 if (!fTestNet && nTxFee < GetMinFee() && nTime < OUTPUT_SWITCH_TIME)
1469 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;
1472 // The first loop above does all the inexpensive checks.
1473 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1474 // Helps prevent CPU exhaustion attacks.
1476 // Skip ECDSA signature verification when connecting blocks
1477 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1478 // still computed and checked, and any change will be caught at the next checkpoint.
1479 if (csmode == CS_ALWAYS ||
1480 (csmode == CS_AFTER_CHECKPOINT && inputs.GetBestBlock()->nHeight >= Checkpoints::GetTotalBlocksEstimate())) {
1481 for (unsigned int i = 0; i < vin.size(); i++) {
1482 const COutPoint &prevout = vin[i].prevout;
1484 inputs.GetCoins(prevout.hash, coins);
1487 if (!VerifySignature(coins, *this, i, fStrictPayToScriptHash, fStrictEncodings, 0)) {
1488 // only during transition phase for P2SH: do not invoke anti-DoS code for
1489 // potentially old clients relaying bad P2SH transactions
1490 if (fStrictPayToScriptHash && VerifySignature(coins, *this, i, false, fStrictEncodings, 0))
1491 return error("CheckInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1493 return DoS(100,error("CheckInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1503 bool CTransaction::ClientCheckInputs() const
1508 // Take over previous transactions' spent pointers
1512 for (unsigned int i = 0; i < vin.size(); i++)
1514 // Get prev tx from single transactions in memory
1515 COutPoint prevout = vin[i].prevout;
1516 if (!mempool.exists(prevout.hash))
1518 CTransaction& txPrev = mempool.lookup(prevout.hash);
1520 if (prevout.n >= txPrev.vout.size())
1524 if (!VerifySignature(CCoins(txPrev, -1, -1), *this, i, true, false, 0))
1525 return error("ConnectInputs() : VerifySignature failed");
1527 ///// this is redundant with the mempool.mapNextTx stuff,
1528 ///// not sure which I want to get rid of
1529 ///// this has to go away now that posNext is gone
1530 // // Check for conflicts
1531 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1532 // return error("ConnectInputs() : prev tx already used");
1534 // // Flag outpoints as used
1535 // txPrev.vout[prevout.n].posNext = posThisTx;
1537 nValueIn += txPrev.vout[prevout.n].nValue;
1539 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1540 return error("ClientConnectInputs() : txin values out of range");
1542 if (GetValueOut() > nValueIn)
1549 bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsView &view)
1551 assert(pindex == view.GetBestBlock());
1553 CBlockUndo blockUndo;
1555 CDiskBlockPos pos = pindex->GetUndoPos();
1557 return error("DisconnectBlock() : no undo data available");
1558 FILE *file = OpenUndoFile(pos, true);
1560 return error("DisconnectBlock() : undo file not available");
1561 CAutoFile fileUndo(file, SER_DISK, CLIENT_VERSION);
1562 fileUndo >> blockUndo;
1565 assert(blockUndo.vtxundo.size() + 1 == vtx.size());
1567 // undo transactions in reverse order
1568 for (int i = vtx.size() - 1; i >= 0; i--) {
1569 const CTransaction &tx = vtx[i];
1570 uint256 hash = tx.GetHash();
1572 // don't check coinbase coins for proof-of-stake block
1573 if(IsProofOfStake() && tx.IsCoinBase())
1576 // check that all outputs are available
1578 if (!view.GetCoins(hash, outs))
1579 return error("DisconnectBlock() : outputs still spent? database corrupted");
1581 CCoins outsBlock = CCoins(tx, pindex->nHeight, pindex->nTime);
1582 if (outs != outsBlock)
1583 return error("DisconnectBlock() : added transaction mismatch? database corrupted");
1586 if (!view.SetCoins(hash, CCoins()))
1587 return error("DisconnectBlock() : cannot delete coin outputs");
1590 if (i > 0) { // not coinbases
1591 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1592 assert(txundo.vprevout.size() == tx.vin.size());
1593 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1594 const COutPoint &out = tx.vin[j].prevout;
1595 const CTxInUndo &undo = txundo.vprevout[j];
1597 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1598 if (coins.IsPruned()) {
1599 if (undo.nHeight == 0)
1600 return error("DisconnectBlock() : undo data doesn't contain tx metadata? database corrupted");
1601 coins.fCoinBase = undo.fCoinBase;
1602 coins.fCoinStake = undo.fCoinStake;
1603 coins.nHeight = undo.nHeight;
1604 coins.nTime = undo.nTime;
1605 coins.nBlockTime = undo.nBlockTime;
1606 coins.nVersion = undo.nVersion;
1608 if (undo.nHeight != 0)
1609 return error("DisconnectBlock() : undo data contains unneeded tx metadata? database corrupted");
1611 if (coins.IsAvailable(out.n))
1612 return error("DisconnectBlock() : prevout output not spent? database corrupted");
1613 if (coins.vout.size() < out.n+1)
1614 coins.vout.resize(out.n+1);
1615 coins.vout[out.n] = undo.txout;
1616 if (!view.SetCoins(out.hash, coins))
1617 return error("DisconnectBlock() : cannot restore coin inputs");
1622 // move best block pointer to prevout block
1623 view.SetBestBlock(pindex->pprev);
1628 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1630 bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsView &view, bool fJustCheck)
1632 // Check it again in case a previous version let a bad block in
1633 if (!CheckBlock(!fJustCheck, !fJustCheck))
1636 // verify that the view's current state corresponds to the previous block
1637 assert(pindex->pprev == view.GetBestBlock());
1639 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1640 // unless those are already completely spent.
1641 // If such overwrites are allowed, coinbases and transactions depending upon those
1642 // can be duplicated to remove the ability to spend the first instance -- even after
1643 // being sent to another address.
1644 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1645 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1646 // already refuses previously-known transaction ids entirely.
1647 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1648 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1649 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1650 // initial block download.
1651 bool fEnforceBIP30 = true;
1653 if (fEnforceBIP30) {
1654 for (unsigned int i=0; i<vtx.size(); i++) {
1655 uint256 hash = GetTxHash(i);
1657 if (view.GetCoins(hash, coins) && !coins.IsPruned())
1658 return error("ConnectBlock() : tried to overwrite transaction");
1662 // BIP16 always active
1663 bool fStrictPayToScriptHash = true;
1665 CBlockUndo blockundo;
1667 int64 nFees = 0, nValueIn = 0, nValueOut = 0;
1668 unsigned int nSigOps = 0;
1669 for (unsigned int i=0; i<vtx.size(); i++)
1671 const CTransaction &tx = vtx[i];
1672 nSigOps += tx.GetLegacySigOpCount();
1673 if (nSigOps > MAX_BLOCK_SIGOPS)
1674 return DoS(100, error("ConnectBlock() : too many sigops"));
1676 if (!tx.IsCoinBase())
1678 if (!tx.HaveInputs(view))
1679 return DoS(100, error("ConnectBlock() : inputs missing/spent"));
1681 if (fStrictPayToScriptHash)
1683 // Add in sigops done by pay-to-script-hash inputs;
1684 // this is to prevent a "rogue miner" from creating
1685 // an incredibly-expensive-to-validate block.
1686 nSigOps += tx.GetP2SHSigOpCount(view);
1687 if (nSigOps > MAX_BLOCK_SIGOPS)
1688 return DoS(100, error("ConnectBlock() : too many sigops"));
1691 int64 nTxValueOut = tx.GetValueOut();
1692 int64 nTxValueIn = tx.GetValueIn(view);
1694 nValueIn += nTxValueIn;
1695 nValueOut += nTxValueOut;
1697 if (!tx.IsCoinStake())
1698 nFees += nTxValueIn - nTxValueOut;
1700 if (!tx.CheckInputs(view, CS_AFTER_CHECKPOINT, fStrictPayToScriptHash, false, this))
1705 nValueOut += tx.GetValueOut();
1708 // don't create coinbase coins for proof-of-stake block
1709 if(IsProofOfStake() && tx.IsCoinBase())
1713 if (!tx.UpdateCoins(view, txundo, pindex->nHeight, pindex->nTime, GetTxHash(i)))
1714 return error("ConnectBlock() : UpdateInputs failed");
1715 if (!tx.IsCoinBase())
1716 blockundo.vtxundo.push_back(txundo);
1719 pindex->nMint = nValueOut - nValueIn + nFees;
1720 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1728 // Write undo information to disk
1729 if (pindex->GetUndoPos().IsNull())
1731 if (!FindUndoPos(chaindb, pindex->pos.nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 8))
1732 return error("ConnectBlock() : FindUndoPos failed");
1733 if (!blockundo.WriteToDisk(pos))
1734 return error("ConnectBlock() : CBlockUndo::WriteToDisk failed");
1736 // update nUndoPos in block index
1737 pindex->nUndoPos = pos.nPos + 1;
1740 CDiskBlockIndex blockindex(pindex);
1741 if (!chaindb.WriteBlockIndex(blockindex))
1742 return error("ConnectBlock() : WriteBlockIndex failed");
1744 // add this block to the view's blockchain
1745 if (!view.SetBestBlock(pindex))
1748 // fees are destroyed to compensate the entire network
1749 if (fDebug && GetBoolArg("-printcreation"))
1750 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1752 // Watch for transactions paying to me
1753 for (unsigned int i=0; i<vtx.size(); i++)
1754 SyncWithWallets(GetTxHash(i), vtx[i], this, true);
1759 bool CBlock::SetBestChain(CBlockIndex* pindexNew)
1761 CCoinsViewCache &view = *pcoinsTip;
1763 // special case for attaching the genesis block
1764 // note that no ConnectBlock is called, so its coinbase output is non-spendable
1765 if (pindexGenesisBlock == NULL && pindexNew->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1767 view.SetBestBlock(pindexNew);
1770 pindexGenesisBlock = pindexNew;
1771 pindexBest = pindexNew;
1772 hashBestChain = pindexNew->GetBlockHash();
1773 nBestHeight = pindexBest->nHeight;
1774 nBestChainTrust = pindexNew->nChainTrust;
1778 // Find the fork (typically, there is none)
1779 CBlockIndex* pfork = view.GetBestBlock();
1780 CBlockIndex* plonger = pindexNew;
1781 while (pfork != plonger)
1783 while (plonger->nHeight > pfork->nHeight)
1784 if (!(plonger = plonger->pprev))
1785 return error("SetBestChain() : plonger->pprev is null");
1786 if (pfork == plonger)
1788 if (!(pfork = pfork->pprev))
1789 return error("SetBestChain() : pfork->pprev is null");
1792 // List of what to disconnect (typically nothing)
1793 vector<CBlockIndex*> vDisconnect;
1794 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1795 vDisconnect.push_back(pindex);
1797 // List of what to connect (typically only pindexNew)
1798 vector<CBlockIndex*> vConnect;
1799 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1800 vConnect.push_back(pindex);
1801 reverse(vConnect.begin(), vConnect.end());
1803 if (vDisconnect.size() > 0) {
1804 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());
1805 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());
1808 // Disconnect shorter branch
1809 vector<CTransaction> vResurrect;
1810 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
1812 if (!block.ReadFromDisk(pindex))
1813 return error("SetBestBlock() : ReadFromDisk for disconnect failed");
1814 CCoinsViewCache viewTemp(view, true);
1815 if (!block.DisconnectBlock(pindex, viewTemp))
1816 return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1817 if (!viewTemp.Flush())
1818 return error("SetBestBlock() : Cache flush failed after disconnect");
1820 // Queue memory transactions to resurrect
1821 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1822 if (!tx.IsCoinBase() && !tx.IsCoinStake())
1823 vResurrect.push_back(tx);
1826 // Connect longer branch
1827 vector<CTransaction> vDelete;
1828 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
1831 if (pindex == pindexNew) // connecting *this block
1833 else { // other block; read it from disk
1834 if (!block.ReadFromDisk(pindex))
1835 return error("SetBestBlock() : ReadFromDisk for connect failed");
1838 CCoinsViewCache viewTemp(view, true);
1839 if (!pblock->ConnectBlock(pindex, viewTemp)) {
1840 InvalidChainFound(pindexNew);
1841 return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1843 if (!viewTemp.Flush())
1844 return error("SetBestBlock() : Cache flush failed after connect");
1846 // Queue memory transactions to delete
1847 BOOST_FOREACH(const CTransaction& tx, pblock->vtx)
1848 vDelete.push_back(tx);
1851 // Make sure it's successfully written to disk before changing memory structure
1852 bool fIsInitialDownload = IsInitialBlockDownload();
1853 if (!fIsInitialDownload || view.GetCacheSize()>5000)
1857 // At this point, all changes have been done to the database.
1858 // Proceed by updating the memory structures.
1860 // Disconnect shorter branch
1861 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1863 pindex->pprev->pnext = NULL;
1865 // Connect longer branch
1866 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1868 pindex->pprev->pnext = pindex;
1870 // Resurrect memory transactions that were in the disconnected branch
1871 BOOST_FOREACH(CTransaction& tx, vResurrect)
1872 tx.AcceptToMemoryPool(false);
1874 // Delete redundant memory transactions that are in the connected branch
1875 BOOST_FOREACH(CTransaction& tx, vDelete)
1878 // Update best block in wallet (so we can detect restored wallets)
1879 if (!fIsInitialDownload)
1881 const CBlockLocator locator(pindexNew);
1882 ::SetBestChain(locator);
1886 hashBestChain = pindexNew->GetBlockHash();
1887 pindexBest = pindexNew;
1888 pblockindexFBBHLast = NULL;
1889 nBestHeight = pindexBest->nHeight;
1890 nBestChainTrust = pindexNew->nChainTrust;
1891 nTimeBestReceived = GetTime();
1892 nTransactionsUpdated++;
1894 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1896 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1897 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1898 CBigNum(nBestChainTrust).ToString().c_str(),
1899 nBestBlockTrust.Get64(),
1900 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1902 // Check the version of the last 100 blocks to see if we need to upgrade:
1903 if (!fIsInitialDownload)
1906 const CBlockIndex* pindex = pindexBest;
1907 for (int i = 0; i < 100 && pindex != NULL; i++)
1909 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1911 pindex = pindex->pprev;
1914 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1915 if (nUpgraded > 100/2)
1916 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1917 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1920 std::string strCmd = GetArg("-blocknotify", "");
1922 if (!fIsInitialDownload && !strCmd.empty())
1924 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1925 boost::thread t(runCommand, strCmd); // thread runs free
1931 // Total coin age spent in transaction, in the unit of coin-days.
1932 // Only those coins meeting minimum age requirement counts. As those
1933 // transactions not in main chain are not currently indexed so we
1934 // might not find out about their coin age. Older transactions are
1935 // guaranteed to be in main chain by sync-checkpoint. This rule is
1936 // introduced to help nodes establish a consistent view of the coin
1937 // age (trust score) of competing branches.
1938 bool CTransaction::GetCoinAge(uint64& nCoinAge) const
1940 CCoinsViewCache &inputs = *pcoinsTip;
1942 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1948 for (unsigned int i = 0; i < vin.size(); i++)
1950 const COutPoint &prevout = vin[i].prevout;
1952 if (!inputs.GetCoins(prevout.hash, coins))
1955 if (nTime < coins.nTime)
1956 return false; // Transaction timestamp violation
1958 // only count coins meeting min age requirement
1959 if (coins.nBlockTime + nStakeMinAge > nTime)
1962 int64 nValueIn = coins.vout[vin[i].prevout.n].nValue;
1963 bnCentSecond += CBigNum(nValueIn) * (nTime-coins.nTime) / CENT;
1966 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1967 if (fDebug && GetBoolArg("-printcoinage"))
1968 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1969 nCoinAge = bnCoinDay.getuint64();
1973 // Total coin age spent in block, in the unit of coin-days.
1974 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1978 BOOST_FOREACH(const CTransaction& tx, vtx)
1981 if (tx.GetCoinAge(nTxCoinAge))
1982 nCoinAge += nTxCoinAge;
1987 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1989 if (fDebug && GetBoolArg("-printcoinage"))
1990 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1994 bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
1996 // Check for duplicate
1997 uint256 hash = GetHash();
1998 if (mapBlockIndex.count(hash))
1999 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2001 // Construct new block index object
2002 CBlockIndex* pindexNew = new CBlockIndex(*this);
2004 return error("AddToBlockIndex() : new CBlockIndex failed");
2005 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2006 pindexNew->phashBlock = &((*mi).first);
2007 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2008 if (miPrev != mapBlockIndex.end())
2010 pindexNew->pprev = (*miPrev).second;
2011 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2013 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2014 pindexNew->pos = pos;
2015 pindexNew->nUndoPos = 0;
2017 // Compute stake entropy bit for stake modifier
2018 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2019 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2021 // Record proof-of-stake hash value
2022 if (pindexNew->IsProofOfStake())
2024 if (!mapProofOfStake.count(hash))
2025 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2026 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2029 // Compute stake modifier
2030 uint64 nStakeModifier = 0;
2031 bool fGeneratedStakeModifier = false;
2032 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2033 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2034 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2035 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2036 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2037 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2040 if (!chaindb.TxnBegin())
2042 chaindb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2043 if (!chaindb.TxnCommit())
2047 if (!SetBestChain(pindexNew))
2050 if (pindexNew == pindexBest)
2052 // Notify UI to display prev block's coinbase if it was ours
2053 static uint256 hashPrevBestCoinBase;
2054 UpdatedTransaction(hashPrevBestCoinBase);
2055 hashPrevBestCoinBase = GetTxHash(0);
2058 uiInterface.NotifyBlocksChanged();
2062 bool FindBlockPos(CChainDB &chaindb, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime)
2064 bool fUpdatedLast = false;
2066 LOCK(cs_LastBlockFile);
2068 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2069 printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
2070 FILE *file = OpenBlockFile(pos);
2073 file = OpenUndoFile(pos);
2077 infoLastBlockFile.SetNull();
2078 chaindb.ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
2079 fUpdatedLast = true;
2082 pos.nFile = nLastBlockFile;
2083 pos.nPos = infoLastBlockFile.nSize;
2084 infoLastBlockFile.nSize += nAddSize;
2085 infoLastBlockFile.AddBlock(nHeight, nTime);
2087 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2088 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2089 if (nNewChunks > nOldChunks) {
2090 FILE *file = OpenBlockFile(pos);
2092 printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2093 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2098 if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2099 return error("FindBlockPos() : cannot write updated block info");
2101 chaindb.WriteLastBlockFile(nLastBlockFile);
2106 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2110 LOCK(cs_LastBlockFile);
2112 unsigned int nNewSize;
2113 if (nFile == nLastBlockFile) {
2114 pos.nPos = infoLastBlockFile.nUndoSize;
2115 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2116 if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2117 return error("FindUndoPos() : cannot write updated block info");
2119 CBlockFileInfo info;
2120 if (!chaindb.ReadBlockFileInfo(nFile, info))
2121 return error("FindUndoPos() : cannot read block info");
2122 pos.nPos = info.nUndoSize;
2123 nNewSize = (info.nUndoSize += nAddSize);
2124 if (!chaindb.WriteBlockFileInfo(nFile, info))
2125 return error("FindUndoPos() : cannot write updated block info");
2128 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2129 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2130 if (nNewChunks > nOldChunks) {
2131 FILE *file = OpenUndoFile(pos);
2133 printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2134 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2142 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2144 // These are checks that are independent of context
2145 // that can be verified before saving an orphan block.
2148 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2149 return DoS(100, error("CheckBlock() : size limits failed"));
2151 // Check proof of work matches claimed amount
2152 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2153 return DoS(50, error("CheckBlock() : proof of work failed"));
2156 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2157 return error("CheckBlock() : block timestamp too far in the future");
2159 // First transaction must be coinbase, the rest must not be
2160 if (vtx.empty() || !vtx[0].IsCoinBase())
2161 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2162 for (unsigned int i = 1; i < vtx.size(); i++)
2163 if (vtx[i].IsCoinBase())
2164 return DoS(100, error("CheckBlock() : more than one coinbase"));
2166 // Check coinbase timestamp
2167 if (GetBlockTime() > FutureDrift((int64)vtx[0].nTime))
2168 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2170 if (IsProofOfStake())
2172 // Coinbase output should be empty if proof-of-stake block
2173 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2174 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2176 // Second transaction must be coinstake, the rest must not be
2177 if (vtx.empty() || !vtx[1].IsCoinStake())
2178 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2179 for (unsigned int i = 2; i < vtx.size(); i++)
2180 if (vtx[i].IsCoinStake())
2181 return DoS(100, error("CheckBlock() : more than one coinstake"));
2183 // Check coinstake timestamp
2184 if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2185 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2189 int64 nReward = GetProofOfWorkReward(nBits);
2190 // Check coinbase reward
2191 if (vtx[0].GetValueOut() > nReward)
2192 return DoS(50, error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
2193 vtx[0].GetValueOut(),
2196 // Should we check proof-of-work block signature or not?
2198 // * Always skip on TestNet
2199 // * Perform checking for the first 9689 blocks
2200 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2202 if(!fTestNet && fCheckSig)
2204 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2206 // check legacy proof-of-work block signature
2207 if (checkEntropySig && !CheckLegacySignature())
2208 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2213 // Check transactions
2214 BOOST_FOREACH(const CTransaction& tx, vtx)
2216 if (!tx.CheckTransaction())
2217 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2219 // check transaction timestamp
2220 if (GetBlockTime() < (int64)tx.nTime)
2221 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2224 // Check for duplicate txids. This is caught by ConnectInputs(),
2225 // but catching it earlier avoids a potential DoS attack:
2227 set<uint256> uniqueTx;
2228 for (unsigned int i=0; i<vtx.size(); i++) {
2229 uniqueTx.insert(GetTxHash(i));
2231 if (uniqueTx.size() != vtx.size())
2232 return DoS(100, error("CheckBlock() : duplicate transaction"));
2234 unsigned int nSigOps = 0;
2235 BOOST_FOREACH(const CTransaction& tx, vtx)
2237 nSigOps += tx.GetLegacySigOpCount();
2239 if (nSigOps > MAX_BLOCK_SIGOPS)
2240 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2242 // Check merkle root
2243 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2244 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2250 bool CBlock::AcceptBlock()
2252 // Check for duplicate
2253 uint256 hash = GetHash();
2254 if (mapBlockIndex.count(hash))
2255 return error("AcceptBlock() : block already in mapBlockIndex");
2257 // Get prev block index
2258 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2259 if (mi == mapBlockIndex.end())
2260 return DoS(10, error("AcceptBlock() : prev block not found"));
2261 CBlockIndex* pindexPrev = (*mi).second;
2262 int nHeight = pindexPrev->nHeight+1;
2264 // Check proof-of-work or proof-of-stake
2265 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2266 return DoS(100, error("AcceptBlock() : incorrect proof-of-%s amount", IsProofOfWork() ? "work" : "stake"));
2268 // Check timestamp against prev
2269 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2270 return error("AcceptBlock() : block's timestamp is too early");
2272 // Check that all transactions are finalized
2273 BOOST_FOREACH(const CTransaction& tx, vtx)
2274 if (!tx.IsFinal(nHeight, GetBlockTime()))
2275 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2277 // Check that the block chain matches the known block chain up to a checkpoint
2278 if (!Checkpoints::CheckHardened(nHeight, hash))
2279 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2281 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2283 // Check that the block satisfies synchronized checkpoint
2284 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2285 return error("AcceptBlock() : rejected by synchronized checkpoint");
2287 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2288 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2290 // Enforce rule that the coinbase starts with serialized block height
2291 CScript expect = CScript() << nHeight;
2292 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2293 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2294 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2296 // Write block to history file
2297 unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
2298 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2299 return error("AcceptBlock() : out of disk space");
2300 CDiskBlockPos blockPos;
2303 if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, nHeight, nTime))
2304 return error("AcceptBlock() : FindBlockPos failed");
2306 if (!WriteToDisk(blockPos))
2307 return error("AcceptBlock() : WriteToDisk failed");
2308 if (!AddToBlockIndex(blockPos))
2309 return error("AcceptBlock() : AddToBlockIndex failed");
2311 // Relay inventory, but don't relay old inventory during initial block download
2312 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2313 if (hashBestChain == hash)
2316 BOOST_FOREACH(CNode* pnode, vNodes)
2317 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2318 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2321 // Check pending sync-checkpoint
2322 Checkpoints::AcceptPendingSyncCheckpoint();
2327 uint256 CBlockIndex::GetBlockTrust() const
2330 bnTarget.SetCompact(nBits);
2336 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2337 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2341 // Calculate work amount for block
2342 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2344 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2345 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2347 // Return nPoWTrust for the first 12 blocks
2348 if (pprev == NULL || pprev->nHeight < 12)
2351 const CBlockIndex* currentIndex = pprev;
2353 if(IsProofOfStake())
2355 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2357 // Return 1/3 of score if parent block is not the PoW block
2358 if (!pprev->IsProofOfWork())
2359 return (bnNewTrust / 3).getuint256();
2363 // Check last 12 blocks type
2364 while (pprev->nHeight - currentIndex->nHeight < 12)
2366 if (currentIndex->IsProofOfWork())
2368 currentIndex = currentIndex->pprev;
2371 // Return 1/3 of score if less than 3 PoW blocks found
2373 return (bnNewTrust / 3).getuint256();
2375 return bnNewTrust.getuint256();
2379 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2381 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2382 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2383 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2387 // Check last 12 blocks type
2388 while (pprev->nHeight - currentIndex->nHeight < 12)
2390 if (currentIndex->IsProofOfStake())
2392 currentIndex = currentIndex->pprev;
2395 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2397 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2399 bnTarget.SetCompact(pprev->nBits);
2404 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2406 // Return nPoWTrust + full trust score for previous block nBits
2407 return nPoWTrust + bnNewTrust.getuint256();
2411 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2413 unsigned int nFound = 0;
2414 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2416 if (pstart->nVersion >= minVersion)
2418 pstart = pstart->pprev;
2420 return (nFound >= nRequired);
2423 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2425 // Check for duplicate
2426 uint256 hash = pblock->GetHash();
2427 if (mapBlockIndex.count(hash))
2428 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2429 if (mapOrphanBlocks.count(hash))
2430 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2432 // Preliminary checks
2433 if (!pblock->CheckBlock())
2434 return error("ProcessBlock() : CheckBlock FAILED");
2436 if (pblock->IsProofOfStake())
2438 // Limited duplicity on stake: prevents block flood attack
2439 // Duplicate stake allowed only when there is orphan child block
2440 if (setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2441 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());
2443 bool fFatal = false;
2444 uint256 hashProofOfStake;
2446 // Verify proof-of-stake hash target and signatures
2447 if (!pblock->CheckSignature(fFatal, hashProofOfStake))
2451 // Invalid blockhash/coinstake signature or no generator defined, nothing to do here
2452 // This also may occur when supplied proof-of-stake doesn't satisfy required target
2454 pfrom->Misbehaving(100);
2455 return error("ProcessBlock() : invalid signature in proof-of-stake block %s", hash.ToString().c_str());
2459 // Blockhash and coinstake signatures are OK but target checkings failed
2460 // This may occur during initial block download
2463 pfrom->Misbehaving(1); // Small DoS penalty
2465 printf("WARNING: ProcessBlock(): proof-of-stake target checkings failed for block %s, we'll try again later\n", hash.ToString().c_str());
2470 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2471 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2474 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2475 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2477 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2478 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2480 bnNewBlock.SetCompact(pblock->nBits);
2483 if (pblock->IsProofOfStake())
2484 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2486 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2488 if (bnNewBlock > bnRequired)
2491 pfrom->Misbehaving(100);
2492 return error("ProcessBlock() : block with too little proof-of-%s", pblock->IsProofOfStake() ? "stake" : "work");
2496 // Ask for pending sync-checkpoint if any
2497 if (!IsInitialBlockDownload())
2498 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2500 // If don't already have its previous block, shunt it off to holding area until we get it
2501 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2503 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2504 CBlock* pblock2 = new CBlock(*pblock);
2506 if (pblock2->IsProofOfStake())
2508 // Limited duplicity on stake: prevents block flood attack
2509 // Duplicate stake allowed only when there is orphan child block
2510 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2511 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());
2513 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2516 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2517 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2519 // Ask this guy to fill in what we're missing
2522 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2523 // ppcoin: getblocks may not obtain the ancestor block rejected
2524 // earlier by duplicate-stake check so we ask for it again directly
2525 if (!IsInitialBlockDownload())
2526 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2532 if (!pblock->AcceptBlock())
2533 return error("ProcessBlock() : AcceptBlock FAILED");
2535 // Recursively process any orphan blocks that depended on this one
2536 vector<uint256> vWorkQueue;
2537 vWorkQueue.push_back(hash);
2538 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2540 uint256 hashPrev = vWorkQueue[i];
2541 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2542 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2545 CBlock* pblockOrphan = (*mi).second;
2546 if (pblockOrphan->AcceptBlock())
2547 vWorkQueue.push_back(pblockOrphan->GetHash());
2548 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2549 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2550 delete pblockOrphan;
2552 mapOrphanBlocksByPrev.erase(hashPrev);
2555 printf("ProcessBlock: ACCEPTED\n");
2557 // ppcoin: if responsible for sync-checkpoint send it
2558 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2559 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2564 // attempt to generate suitable proof-of-stake
2565 bool CBlock::SignBlock(CWallet& wallet)
2567 // if we are trying to sign
2568 // something except proof-of-stake block template
2569 if (!vtx[0].vout[0].IsEmpty())
2572 // if we are trying to sign
2573 // a complete proof-of-stake block
2574 if (IsProofOfStake())
2577 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2580 CTransaction txCoinStake;
2581 int64 nSearchTime = txCoinStake.nTime; // search to current time
2583 if (nSearchTime > nLastCoinStakeSearchTime)
2585 if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2587 if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2589 // make sure coinstake would meet timestamp protocol
2590 // as it would be the same as the block timestamp
2591 vtx[0].nTime = nTime = txCoinStake.nTime;
2592 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2593 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2595 // we have to make sure that we have no future timestamps in
2596 // our transactions set
2597 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2598 if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2600 vtx.insert(vtx.begin() + 1, txCoinStake);
2601 hashMerkleRoot = BuildMerkleTree();
2603 // append a signature to our block
2604 return key.Sign(GetHash(), vchBlockSig);
2607 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2608 nLastCoinStakeSearchTime = nSearchTime;
2614 // get generation key
2615 bool CBlock::GetGenerator(CKey& GeneratorKey) const
2617 if(!IsProofOfStake())
2620 vector<valtype> vSolutions;
2621 txnouttype whichType;
2623 const CTxOut& txout = vtx[1].vout[1];
2625 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2627 if (whichType == TX_PUBKEY)
2629 valtype& vchPubKey = vSolutions[0];
2631 return GeneratorKey.SetPubKey(vchPubKey);
2637 // verify proof-of-stake signatures
2638 bool CBlock::CheckSignature(bool& fFatal, uint256& hashProofOfStake) const
2642 // no generator or invalid hash signature means fatal error
2643 fFatal = !GetGenerator(key) || !key.Verify(GetHash(), vchBlockSig);
2648 uint256 hashTarget = 0;
2649 if (!CheckProofOfStake(vtx[1], nBits, hashProofOfStake, hashTarget, fFatal))
2650 return false; // hash target mismatch or invalid coinstake signature
2655 // verify legacy proof-of-work signature
2656 bool CBlock::CheckLegacySignature() const
2658 if (IsProofOfStake())
2661 vector<valtype> vSolutions;
2662 txnouttype whichType;
2664 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2666 const CTxOut& txout = vtx[0].vout[i];
2668 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2671 if (whichType == TX_PUBKEY)
2674 valtype& vchPubKey = vSolutions[0];
2676 if (!key.SetPubKey(vchPubKey))
2678 if (vchBlockSig.empty())
2680 if(!key.Verify(GetHash(), vchBlockSig))
2689 bool CheckDiskSpace(uint64 nAdditionalBytes)
2691 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2693 // Check for nMinDiskSpace bytes (currently 50MB)
2694 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2697 string strMessage = _("Warning: Disk space is low!");
2698 strMiscWarning = strMessage;
2699 printf("*** %s\n", strMessage.c_str());
2700 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2708 CCriticalSection cs_LastBlockFile;
2709 CBlockFileInfo infoLastBlockFile;
2710 int nLastBlockFile = 0;
2712 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2716 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2717 boost::filesystem::create_directories(path.parent_path());
2718 FILE* file = fopen(path.string().c_str(), "rb+");
2719 if (!file && !fReadOnly)
2720 file = fopen(path.string().c_str(), "wb+");
2722 printf("Unable to open file %s\n", path.string().c_str());
2726 if (fseek(file, pos.nPos, SEEK_SET)) {
2727 printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2735 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2736 return OpenDiskFile(pos, "blk", fReadOnly);
2739 FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2740 return OpenDiskFile(pos, "rev", fReadOnly);
2743 bool LoadBlockIndex(bool fAllowNew)
2745 CBigNum bnTrustedModulus;
2749 pchMessageStart[0] = 0xcd;
2750 pchMessageStart[1] = 0xf2;
2751 pchMessageStart[2] = 0xc0;
2752 pchMessageStart[3] = 0xef;
2754 bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
2755 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2756 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2757 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2758 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2759 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2763 bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
2766 // Set up the Zerocoin Params object
2767 ZCParams = new libzerocoin::Params(bnTrustedModulus);
2772 CChainDB chaindb("cr");
2773 if (!LoadBlockIndex(chaindb))
2778 // Init with genesis block
2780 if (mapBlockIndex.empty())
2789 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2790 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2791 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2793 // vMerkleTree: 4cb33b3b6a
2797 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2798 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2799 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2801 // vMerkleTree: 4cb33b3b6a
2803 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2805 txNew.nTime = 1360105017;
2806 txNew.vin.resize(1);
2807 txNew.vout.resize(1);
2808 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2809 txNew.vout[0].SetEmpty();
2811 block.vtx.push_back(txNew);
2812 block.hashPrevBlock = 0;
2813 block.hashMerkleRoot = block.BuildMerkleTree();
2815 block.nTime = 1360105017;
2816 block.nBits = bnProofOfWorkLimit.GetCompact();
2817 block.nNonce = !fTestNet ? 1575379 : 46534;
2820 uint256 hash = block.GetHash();
2821 printf("%s\n", hash.ToString().c_str());
2822 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2824 assert(hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2825 assert(block.CheckBlock());
2827 // Start new block file
2828 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2829 CDiskBlockPos blockPos;
2832 if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, 0, block.nTime))
2833 return error("AcceptBlock() : FindBlockPos failed");
2835 if (!block.WriteToDisk(blockPos))
2836 return error("LoadBlockIndex() : writing genesis block to disk failed");
2837 if (!block.AddToBlockIndex(blockPos))
2838 return error("LoadBlockIndex() : genesis block not accepted");
2840 // initialize synchronized checkpoint
2841 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2842 return error("LoadBlockIndex() : failed to init sync checkpoint");
2845 string strPubKey = "";
2848 // if checkpoint master key changed must reset sync-checkpoint
2849 if (!chaindb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2851 // write checkpoint master key to db
2853 if (!chaindb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2854 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2855 if (!chaindb.TxnCommit())
2856 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2857 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2858 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2865 void PrintBlockTree()
2867 // pre-compute tree structure
2868 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2869 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2871 CBlockIndex* pindex = (*mi).second;
2872 mapNext[pindex->pprev].push_back(pindex);
2874 //while (rand() % 3 == 0)
2875 // mapNext[pindex->pprev].push_back(pindex);
2878 vector<pair<int, CBlockIndex*> > vStack;
2879 vStack.push_back(make_pair(0, pindexGenesisBlock));
2882 while (!vStack.empty())
2884 int nCol = vStack.back().first;
2885 CBlockIndex* pindex = vStack.back().second;
2888 // print split or gap
2889 if (nCol > nPrevCol)
2891 for (int i = 0; i < nCol-1; i++)
2895 else if (nCol < nPrevCol)
2897 for (int i = 0; i < nCol; i++)
2904 for (int i = 0; i < nCol; i++)
2909 block.ReadFromDisk(pindex);
2910 printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
2912 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2913 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2916 PrintWallets(block);
2918 // put the main time-chain first
2919 vector<CBlockIndex*>& vNext = mapNext[pindex];
2920 for (unsigned int i = 0; i < vNext.size(); i++)
2922 if (vNext[i]->pnext)
2924 swap(vNext[0], vNext[i]);
2930 for (unsigned int i = 0; i < vNext.size(); i++)
2931 vStack.push_back(make_pair(nCol+i, vNext[i]));
2935 bool LoadExternalBlockFile(FILE* fileIn)
2937 int64 nStart = GetTimeMillis();
2943 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2944 unsigned int nPos = 0;
2945 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2947 unsigned char pchData[65536];
2949 fseek(blkdat, nPos, SEEK_SET);
2950 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2953 nPos = (unsigned int)-1;
2956 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2959 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2961 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2964 nPos += ((unsigned char*)nFind - pchData) + 1;
2967 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2968 } while(!fRequestShutdown);
2969 if (nPos == (unsigned int)-1)
2971 fseek(blkdat, nPos, SEEK_SET);
2974 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2978 if (ProcessBlock(NULL,&block))
2986 catch (std::exception &e) {
2987 printf("%s() : Deserialize or I/O error caught during load\n",
2988 __PRETTY_FUNCTION__);
2991 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2995 //////////////////////////////////////////////////////////////////////////////
3000 extern map<uint256, CAlert> mapAlerts;
3001 extern CCriticalSection cs_mapAlerts;
3003 extern string strMintMessage;
3004 extern string strMintWarning;
3006 string GetWarnings(string strFor)
3009 string strStatusBar;
3012 if (GetBoolArg("-testsafemode"))
3015 // ppcoin: wallet lock warning for minting
3016 if (strMintWarning != "")
3019 strStatusBar = strMintWarning;
3022 // Misc warnings like out of disk space and clock is wrong
3023 if (strMiscWarning != "")
3026 strStatusBar = strMiscWarning;
3029 // * Should not enter safe mode for longer invalid chain
3030 // * If sync-checkpoint is too old do not enter safe mode
3031 // * Display warning only in the STRICT mode
3032 if (CheckpointsMode == Checkpoints::STRICT && Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) &&
3033 !fTestNet && !IsInitialBlockDownload())
3036 strStatusBar = _("WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.");
3039 // ppcoin: if detected invalid checkpoint enter safe mode
3040 if (Checkpoints::hashInvalidCheckpoint != 0)
3043 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3049 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3051 const CAlert& alert = item.second;
3052 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3054 nPriority = alert.nPriority;
3055 strStatusBar = alert.strStatusBar;
3056 if (nPriority > 1000)
3057 strRPC = strStatusBar;
3062 if (strFor == "statusbar")
3063 return strStatusBar;
3064 else if (strFor == "rpc")
3066 assert(!"GetWarnings() : invalid parameter");
3077 //////////////////////////////////////////////////////////////////////////////
3083 bool static AlreadyHave(const CInv& inv)
3089 bool txInMap = false;
3092 txInMap = mempool.exists(inv.hash);
3094 return txInMap || mapOrphanTransactions.count(inv.hash) ||
3095 pcoinsTip->HaveCoins(inv.hash);
3098 return mapBlockIndex.count(inv.hash) ||
3099 mapOrphanBlocks.count(inv.hash);
3101 // Don't know what it is, just say we already got one
3108 // The message start string is designed to be unlikely to occur in normal data.
3109 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3110 // a large 4-byte int at any alignment.
3111 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3113 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3115 static map<CService, CPubKey> mapReuseKey;
3116 RandAddSeedPerfmon();
3118 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3119 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3121 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3125 if (strCommand == "version")
3127 // Each connection can only send one version message
3128 if (pfrom->nVersion != 0)
3130 pfrom->Misbehaving(1);
3138 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3139 if (pfrom->nVersion < MIN_PROTO_VERSION)
3141 // Since February 20, 2012, the protocol is initiated at version 209,
3142 // and earlier versions are no longer supported
3143 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3144 pfrom->fDisconnect = true;
3148 if (pfrom->nVersion == 10300)
3149 pfrom->nVersion = 300;
3151 vRecv >> addrFrom >> nNonce;
3153 vRecv >> pfrom->strSubVer;
3155 vRecv >> pfrom->nStartingHeight;
3157 if (pfrom->fInbound && addrMe.IsRoutable())
3159 pfrom->addrLocal = addrMe;
3163 // Disconnect if we connected to ourself
3164 if (nNonce == nLocalHostNonce && nNonce > 1)
3166 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3167 pfrom->fDisconnect = true;
3171 // record my external IP reported by peer
3172 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3173 addrSeenByPeer = addrMe;
3175 // Be shy and don't send version until we hear
3176 if (pfrom->fInbound)
3177 pfrom->PushVersion();
3179 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3181 AddTimeData(pfrom->addr, nTime);
3184 pfrom->PushMessage("verack");
3185 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3187 if (!pfrom->fInbound)
3189 // Advertise our address
3190 if (!fNoListen && !IsInitialBlockDownload())
3192 CAddress addr = GetLocalAddress(&pfrom->addr);
3193 if (addr.IsRoutable())
3194 pfrom->PushAddress(addr);
3197 // Get recent addresses
3198 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3200 pfrom->PushMessage("getaddr");
3201 pfrom->fGetAddr = true;
3203 addrman.Good(pfrom->addr);
3205 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3207 addrman.Add(addrFrom, addrFrom);
3208 addrman.Good(addrFrom);
3212 // Ask the first connected node for block updates
3213 static int nAskedForBlocks = 0;
3214 if (!pfrom->fClient && !pfrom->fOneShot &&
3215 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3216 (pfrom->nVersion < NOBLKS_VERSION_START ||
3217 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3218 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3221 pfrom->PushGetBlocks(pindexBest, uint256(0));
3227 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3228 item.second.RelayTo(pfrom);
3231 // Relay sync-checkpoint
3233 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3234 if (!Checkpoints::checkpointMessage.IsNull())
3235 Checkpoints::checkpointMessage.RelayTo(pfrom);
3238 pfrom->fSuccessfullyConnected = true;
3240 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());
3242 cPeerBlockCounts.input(pfrom->nStartingHeight);
3244 // ppcoin: ask for pending sync-checkpoint if any
3245 if (!IsInitialBlockDownload())
3246 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3250 else if (pfrom->nVersion == 0)
3252 // Must have a version message before anything else
3253 pfrom->Misbehaving(1);
3258 else if (strCommand == "verack")
3260 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3264 else if (strCommand == "addr")
3266 vector<CAddress> vAddr;
3269 // Don't want addr from older versions unless seeding
3270 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3272 if (vAddr.size() > 1000)
3274 pfrom->Misbehaving(20);
3275 return error("message addr size() = %"PRIszu"", vAddr.size());
3278 // Store the new addresses
3279 vector<CAddress> vAddrOk;
3280 int64 nNow = GetAdjustedTime();
3281 int64 nSince = nNow - 10 * 60;
3282 BOOST_FOREACH(CAddress& addr, vAddr)
3286 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3287 addr.nTime = nNow - 5 * 24 * 60 * 60;
3288 pfrom->AddAddressKnown(addr);
3289 bool fReachable = IsReachable(addr);
3290 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3292 // Relay to a limited number of other nodes
3295 // Use deterministic randomness to send to the same nodes for 24 hours
3296 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3297 static uint256 hashSalt;
3299 hashSalt = GetRandHash();
3300 uint64 hashAddr = addr.GetHash();
3301 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3302 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3303 multimap<uint256, CNode*> mapMix;
3304 BOOST_FOREACH(CNode* pnode, vNodes)
3306 if (pnode->nVersion < CADDR_TIME_VERSION)
3308 unsigned int nPointer;
3309 memcpy(&nPointer, &pnode, sizeof(nPointer));
3310 uint256 hashKey = hashRand ^ nPointer;
3311 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3312 mapMix.insert(make_pair(hashKey, pnode));
3314 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3315 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3316 ((*mi).second)->PushAddress(addr);
3319 // Do not store addresses outside our network
3321 vAddrOk.push_back(addr);
3323 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3324 if (vAddr.size() < 1000)
3325 pfrom->fGetAddr = false;
3326 if (pfrom->fOneShot)
3327 pfrom->fDisconnect = true;
3330 else if (strCommand == "inv")
3334 if (vInv.size() > MAX_INV_SZ)
3336 pfrom->Misbehaving(20);
3337 return error("message inv size() = %"PRIszu"", vInv.size());
3340 // find last block in inv vector
3341 unsigned int nLastBlock = (unsigned int)(-1);
3342 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3343 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3344 nLastBlock = vInv.size() - 1 - nInv;
3348 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3350 const CInv &inv = vInv[nInv];
3354 pfrom->AddInventoryKnown(inv);
3356 bool fAlreadyHave = AlreadyHave(inv);
3358 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3362 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3363 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3364 } else if (nInv == nLastBlock) {
3365 // In case we are on a very long side-chain, it is possible that we already have
3366 // the last block in an inv bundle sent in response to getblocks. Try to detect
3367 // this situation and push another getblocks to continue.
3368 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3370 printf("force request: %s\n", inv.ToString().c_str());
3373 // Track requests for our stuff
3374 Inventory(inv.hash);
3379 else if (strCommand == "getdata")
3383 if (vInv.size() > MAX_INV_SZ)
3385 pfrom->Misbehaving(20);
3386 return error("message getdata size() = %"PRIszu"", vInv.size());
3389 if (fDebugNet || (vInv.size() != 1))
3390 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3392 BOOST_FOREACH(const CInv& inv, vInv)
3396 if (fDebugNet || (vInv.size() == 1))
3397 printf("received getdata for: %s\n", inv.ToString().c_str());
3399 if (inv.type == MSG_BLOCK)
3401 // Send block from disk
3402 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3403 if (mi != mapBlockIndex.end())
3406 block.ReadFromDisk((*mi).second);
3407 pfrom->PushMessage("block", block);
3409 // Trigger them to send a getblocks request for the next batch of inventory
3410 if (inv.hash == pfrom->hashContinue)
3412 // ppcoin: send latest proof-of-work block to allow the
3413 // download node to accept as orphan (proof-of-stake
3414 // block might be rejected by stake connection check)
3416 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3417 pfrom->PushMessage("inv", vInv);
3418 pfrom->hashContinue = 0;
3422 else if (inv.IsKnownType())
3424 // Send stream from relay memory
3425 bool pushed = false;
3428 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3429 if (mi != mapRelay.end()) {
3430 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3434 if (!pushed && inv.type == MSG_TX) {
3436 if (mempool.exists(inv.hash)) {
3437 CTransaction tx = mempool.lookup(inv.hash);
3438 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3441 pfrom->PushMessage("tx", ss);
3446 // Track requests for our stuff
3447 Inventory(inv.hash);
3452 else if (strCommand == "getblocks")
3454 CBlockLocator locator;
3456 vRecv >> locator >> hashStop;
3458 // Find the last block the caller has in the main chain
3459 CBlockIndex* pindex = locator.GetBlockIndex();
3461 // Send the rest of the chain
3463 pindex = pindex->pnext;
3465 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3466 for (; pindex; pindex = pindex->pnext)
3468 if (pindex->GetBlockHash() == hashStop)
3470 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3471 // ppcoin: tell downloading node about the latest block if it's
3472 // without risk being rejected due to stake connection check
3473 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3474 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3477 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3480 // When this block is requested, we'll send an inv that'll make them
3481 // getblocks the next batch of inventory.
3482 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3483 pfrom->hashContinue = pindex->GetBlockHash();
3488 else if (strCommand == "checkpoint")
3490 CSyncCheckpoint checkpoint;
3491 vRecv >> checkpoint;
3493 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3496 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3498 BOOST_FOREACH(CNode* pnode, vNodes)
3499 checkpoint.RelayTo(pnode);
3503 else if (strCommand == "getheaders")
3505 CBlockLocator locator;
3507 vRecv >> locator >> hashStop;
3509 CBlockIndex* pindex = NULL;
3510 if (locator.IsNull())
3512 // If locator is null, return the hashStop block
3513 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3514 if (mi == mapBlockIndex.end())
3516 pindex = (*mi).second;
3520 // Find the last block the caller has in the main chain
3521 pindex = locator.GetBlockIndex();
3523 pindex = pindex->pnext;
3526 vector<CBlock> vHeaders;
3528 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3529 for (; pindex; pindex = pindex->pnext)
3531 vHeaders.push_back(pindex->GetBlockHeader());
3532 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3535 pfrom->PushMessage("headers", vHeaders);
3539 else if (strCommand == "tx")
3541 vector<uint256> vWorkQueue;
3542 vector<uint256> vEraseQueue;
3543 CDataStream vMsg(vRecv);
3547 CInv inv(MSG_TX, tx.GetHash());
3548 pfrom->AddInventoryKnown(inv);
3550 bool fMissingInputs = false;
3551 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
3553 SyncWithWallets(inv.hash, tx, NULL, true);
3554 RelayTransaction(tx, inv.hash);
3555 mapAlreadyAskedFor.erase(inv);
3556 vWorkQueue.push_back(inv.hash);
3557 vEraseQueue.push_back(inv.hash);
3559 // Recursively process any orphan transactions that depended on this one
3560 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3562 uint256 hashPrev = vWorkQueue[i];
3563 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3564 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3567 const uint256& orphanTxHash = *mi;
3568 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3569 bool fMissingInputs2 = false;
3571 if (orphanTx.AcceptToMemoryPool(true, &fMissingInputs2))
3573 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3574 SyncWithWallets(inv.hash, tx, NULL, true);
3575 RelayTransaction(orphanTx, orphanTxHash);
3576 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3577 vWorkQueue.push_back(orphanTxHash);
3578 vEraseQueue.push_back(orphanTxHash);
3580 else if (!fMissingInputs2)
3583 vEraseQueue.push_back(orphanTxHash);
3584 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3589 BOOST_FOREACH(uint256 hash, vEraseQueue)
3590 EraseOrphanTx(hash);
3592 else if (fMissingInputs)
3596 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3597 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3599 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3601 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3605 else if (strCommand == "block")
3609 uint256 hashBlock = block.GetHash();
3611 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3614 CInv inv(MSG_BLOCK, hashBlock);
3615 pfrom->AddInventoryKnown(inv);
3617 if (ProcessBlock(pfrom, &block))
3618 mapAlreadyAskedFor.erase(inv);
3619 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3623 else if (strCommand == "getaddr")
3625 // Don't return addresses older than nCutOff timestamp
3626 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3627 pfrom->vAddrToSend.clear();
3628 vector<CAddress> vAddr = addrman.GetAddr();
3629 BOOST_FOREACH(const CAddress &addr, vAddr)
3630 if(addr.nTime > nCutOff)
3631 pfrom->PushAddress(addr);
3635 else if (strCommand == "mempool")
3637 std::vector<uint256> vtxid;
3638 mempool.queryHashes(vtxid);
3640 for (unsigned int i = 0; i < vtxid.size(); i++) {
3641 CInv inv(MSG_TX, vtxid[i]);
3642 vInv.push_back(inv);
3643 if (i == (MAX_INV_SZ - 1))
3646 if (vInv.size() > 0)
3647 pfrom->PushMessage("inv", vInv);
3651 else if (strCommand == "checkorder")
3656 if (!GetBoolArg("-allowreceivebyip"))
3658 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3665 /// we have a chance to check the order here
3667 // Keep giving the same key to the same ip until they use it
3668 if (!mapReuseKey.count(pfrom->addr))
3669 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3671 // Send back approval of order and pubkey to use
3672 CScript scriptPubKey;
3673 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3674 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3678 else if (strCommand == "reply")
3683 CRequestTracker tracker;
3685 LOCK(pfrom->cs_mapRequests);
3686 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3687 if (mi != pfrom->mapRequests.end())
3689 tracker = (*mi).second;
3690 pfrom->mapRequests.erase(mi);
3693 if (!tracker.IsNull())
3694 tracker.fn(tracker.param1, vRecv);
3698 else if (strCommand == "ping")
3700 if (pfrom->nVersion > BIP0031_VERSION)
3704 // Echo the message back with the nonce. This allows for two useful features:
3706 // 1) A remote node can quickly check if the connection is operational
3707 // 2) Remote nodes can measure the latency of the network thread. If this node
3708 // is overloaded it won't respond to pings quickly and the remote node can
3709 // avoid sending us more work, like chain download requests.
3711 // The nonce stops the remote getting confused between different pings: without
3712 // it, if the remote node sends a ping once per second and this node takes 5
3713 // seconds to respond to each, the 5th ping the remote sends would appear to
3714 // return very quickly.
3715 pfrom->PushMessage("pong", nonce);
3720 else if (strCommand == "alert")
3725 uint256 alertHash = alert.GetHash();
3726 if (pfrom->setKnown.count(alertHash) == 0)
3728 if (alert.ProcessAlert())
3731 pfrom->setKnown.insert(alertHash);
3734 BOOST_FOREACH(CNode* pnode, vNodes)
3735 alert.RelayTo(pnode);
3739 // Small DoS penalty so peers that send us lots of
3740 // duplicate/expired/invalid-signature/whatever alerts
3741 // eventually get banned.
3742 // This isn't a Misbehaving(100) (immediate ban) because the
3743 // peer might be an older or different implementation with
3744 // a different signature key, etc.
3745 pfrom->Misbehaving(10);
3753 // Ignore unknown commands for extensibility
3757 // Update the last seen time for this node's address
3758 if (pfrom->fNetworkNode)
3759 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3760 AddressCurrentlyConnected(pfrom->addr);
3766 bool ProcessMessages(CNode* pfrom)
3768 CDataStream& vRecv = pfrom->vRecv;
3772 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3776 // (4) message start
3785 // Don't bother if send buffer is too full to respond anyway
3786 if (pfrom->vSend.size() >= SendBufferSize())
3789 // Scan for message start
3790 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3791 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3792 if (vRecv.end() - pstart < nHeaderSize)
3794 if ((int)vRecv.size() > nHeaderSize)
3796 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3797 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3801 if (pstart - vRecv.begin() > 0)
3802 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3803 vRecv.erase(vRecv.begin(), pstart);
3806 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3811 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3814 string strCommand = hdr.GetCommand();
3817 unsigned int nMessageSize = hdr.nMessageSize;
3818 if (nMessageSize > MAX_SIZE)
3820 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3823 if (nMessageSize > vRecv.size())
3825 // Rewind and wait for rest of message
3826 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3831 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3832 unsigned int nChecksum = 0;
3833 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3834 if (nChecksum != hdr.nChecksum)
3836 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3837 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3841 // Copy message to its own buffer
3842 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3843 vRecv.ignore(nMessageSize);
3851 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3856 catch (std::ios_base::failure& e)
3858 if (strstr(e.what(), "end of data"))
3860 // Allow exceptions from under-length message on vRecv
3861 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());
3863 else if (strstr(e.what(), "size too large"))
3865 // Allow exceptions from over-long size
3866 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3870 PrintExceptionContinue(&e, "ProcessMessages()");
3873 catch (std::exception& e) {
3874 PrintExceptionContinue(&e, "ProcessMessages()");
3876 PrintExceptionContinue(NULL, "ProcessMessages()");
3880 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3888 bool SendMessages(CNode* pto, bool fSendTrickle)
3890 TRY_LOCK(cs_main, lockMain);
3892 // Don't send anything until we get their version message
3893 if (pto->nVersion == 0)
3896 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3898 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3900 if (pto->nVersion > BIP0031_VERSION)
3901 pto->PushMessage("ping", nonce);
3903 pto->PushMessage("ping");
3906 // Resend wallet transactions that haven't gotten in a block yet
3907 ResendWalletTransactions();
3909 // Address refresh broadcast
3910 static int64 nLastRebroadcast;
3911 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3915 BOOST_FOREACH(CNode* pnode, vNodes)
3917 // Periodically clear setAddrKnown to allow refresh broadcasts
3918 if (nLastRebroadcast)
3919 pnode->setAddrKnown.clear();
3921 // Rebroadcast our address
3924 CAddress addr = GetLocalAddress(&pnode->addr);
3925 if (addr.IsRoutable())
3926 pnode->PushAddress(addr);
3930 nLastRebroadcast = GetTime();
3938 vector<CAddress> vAddr;
3939 vAddr.reserve(pto->vAddrToSend.size());
3940 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3942 // returns true if wasn't already contained in the set
3943 if (pto->setAddrKnown.insert(addr).second)
3945 vAddr.push_back(addr);
3946 // receiver rejects addr messages larger than 1000
3947 if (vAddr.size() >= 1000)
3949 pto->PushMessage("addr", vAddr);
3954 pto->vAddrToSend.clear();
3956 pto->PushMessage("addr", vAddr);
3961 // Message: inventory
3964 vector<CInv> vInvWait;
3966 LOCK(pto->cs_inventory);
3967 vInv.reserve(pto->vInventoryToSend.size());
3968 vInvWait.reserve(pto->vInventoryToSend.size());
3969 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3971 if (pto->setInventoryKnown.count(inv))
3974 // trickle out tx inv to protect privacy
3975 if (inv.type == MSG_TX && !fSendTrickle)
3977 // 1/4 of tx invs blast to all immediately
3978 static uint256 hashSalt;
3980 hashSalt = GetRandHash();
3981 uint256 hashRand = inv.hash ^ hashSalt;
3982 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3983 bool fTrickleWait = ((hashRand & 3) != 0);
3985 // always trickle our own transactions
3989 if (GetTransaction(inv.hash, wtx))
3991 fTrickleWait = true;
3996 vInvWait.push_back(inv);
4001 // returns true if wasn't already contained in the set
4002 if (pto->setInventoryKnown.insert(inv).second)
4004 vInv.push_back(inv);
4005 if (vInv.size() >= 1000)
4007 pto->PushMessage("inv", vInv);
4012 pto->vInventoryToSend = vInvWait;
4015 pto->PushMessage("inv", vInv);
4021 vector<CInv> vGetData;
4022 int64 nNow = GetTime() * 1000000;
4023 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4025 const CInv& inv = (*pto->mapAskFor.begin()).second;
4026 if (!AlreadyHave(inv))
4029 printf("sending getdata: %s\n", inv.ToString().c_str());
4030 vGetData.push_back(inv);
4031 if (vGetData.size() >= 1000)
4033 pto->PushMessage("getdata", vGetData);
4036 mapAlreadyAskedFor[inv] = nNow;
4038 pto->mapAskFor.erase(pto->mapAskFor.begin());
4040 if (!vGetData.empty())
4041 pto->PushMessage("getdata", vGetData);
4047 // Amount compression:
4048 // * If the amount is 0, output 0
4049 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
4050 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
4051 // * call the result n
4052 // * output 1 + 10*(9*n + d - 1) + e
4053 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
4054 // (this is decodable, as d is in [1-9] and e is in [0-9])
4056 uint64 CTxOutCompressor::CompressAmount(uint64 n)
4061 while (((n % 10) == 0) && e < 9) {
4067 assert(d >= 1 && d <= 9);
4069 return 1 + (n*9 + d - 1)*10 + e;
4071 return 1 + (n - 1)*10 + 9;
4075 uint64 CTxOutCompressor::DecompressAmount(uint64 x)
4077 // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
4081 // x = 10*(9*n + d - 1) + e
4087 int d = (x % 9) + 1;