1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
11 #include "ui_interface.h"
13 #include "zerocoin/Zerocoin.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
20 using namespace boost;
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
29 CCriticalSection cs_main;
32 unsigned int nTransactionsUpdated = 0;
34 map<uint256, CBlockIndex*> mapBlockIndex;
35 set<pair<COutPoint, unsigned int> > setStakeSeen;
36 libzerocoin::Params* ZCParams;
38 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
39 CBigNum bnProofOfStakeLegacyLimit(~uint256(0) >> 24); // proof of stake target limit from block #15000 and until 20 June 2013, results with 0,00390625 proof of stake difficulty
40 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
41 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
42 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
44 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
46 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as zero time weight
47 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
48 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
49 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
51 int nCoinbaseMaturity = 500;
52 CBlockIndex* pindexGenesisBlock = NULL;
55 uint256 nBestChainTrust = 0;
56 uint256 nBestInvalidTrust = 0;
58 uint256 hashBestChain = 0;
59 CBlockIndex* pindexBest = NULL;
60 int64 nTimeBestReceived = 0;
62 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
64 map<uint256, CBlock*> mapOrphanBlocks;
65 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
66 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
67 map<uint256, uint256> mapProofOfStake;
69 map<uint256, CTransaction> mapOrphanTransactions;
70 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
72 // Constant stuff for coinbase transactions we create:
73 CScript COINBASE_FLAGS;
75 const string strMessageMagic = "NovaCoin Signed Message:\n";
78 int64 nTransactionFee = MIN_TX_FEE;
79 int64 nMinimumInputValue = MIN_TX_FEE;
81 extern enum Checkpoints::CPMode CheckpointsMode;
83 //////////////////////////////////////////////////////////////////////////////
85 // dispatching functions
88 // These functions dispatch to one or all registered wallets
91 void RegisterWallet(CWallet* pwalletIn)
94 LOCK(cs_setpwalletRegistered);
95 setpwalletRegistered.insert(pwalletIn);
99 void UnregisterWallet(CWallet* pwalletIn)
102 LOCK(cs_setpwalletRegistered);
103 setpwalletRegistered.erase(pwalletIn);
107 // check whether the passed transaction is from us
108 bool static IsFromMe(CTransaction& tx)
110 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
111 if (pwallet->IsFromMe(tx))
116 // get the wallet transaction with the given hash (if it exists)
117 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
119 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
120 if (pwallet->GetTransaction(hashTx,wtx))
125 // erases transaction with the given hash from all wallets
126 void static EraseFromWallets(uint256 hash)
128 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
129 pwallet->EraseFromWallet(hash);
132 // make sure all wallets know about the given transaction, in the given block
133 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
137 // ppcoin: wallets need to refund inputs when disconnecting coinstake
138 if (tx.IsCoinStake())
140 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
141 if (pwallet->IsFromMe(tx))
142 pwallet->DisableTransaction(tx);
147 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
148 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
151 // notify wallets about a new best chain
152 void static SetBestChain(const CBlockLocator& loc)
154 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
155 pwallet->SetBestChain(loc);
158 // notify wallets about an updated transaction
159 void static UpdatedTransaction(const uint256& hashTx)
161 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
162 pwallet->UpdatedTransaction(hashTx);
166 void static PrintWallets(const CBlock& block)
168 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
169 pwallet->PrintWallet(block);
172 // notify wallets about an incoming inventory (for request counts)
173 void static Inventory(const uint256& hash)
175 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
176 pwallet->Inventory(hash);
179 // ask wallets to resend their transactions
180 void ResendWalletTransactions()
182 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
183 pwallet->ResendWalletTransactions();
187 //////////////////////////////////////////////////////////////////////////////
189 // CCoinsView implementations
192 bool CCoinsView::GetCoins(uint256 txid, CCoins &coins) { return false; }
193 bool CCoinsView::SetCoins(uint256 txid, const CCoins &coins) { return false; }
194 bool CCoinsView::HaveCoins(uint256 txid) { return false; }
195 CBlockIndex *CCoinsView::GetBestBlock() { return NULL; }
196 bool CCoinsView::SetBestBlock(CBlockIndex *pindex) { return false; }
197 bool CCoinsView::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return false; }
199 CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
200 bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); }
201 bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
202 bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); }
203 CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
204 bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
205 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
207 bool CCoinsViewBacked::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) { return base->BatchWrite(mapCoins, pindex); }
209 CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
211 bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) {
212 if (cacheCoins.count(txid)) {
213 coins = cacheCoins[txid];
216 if (base->GetCoins(txid, coins)) {
217 cacheCoins[txid] = coins;
223 bool CCoinsViewCache::SetCoins(uint256 txid, const CCoins &coins) {
224 cacheCoins[txid] = coins;
228 bool CCoinsViewCache::HaveCoins(uint256 txid) {
229 return cacheCoins.count(txid) || base->HaveCoins(txid);
232 CBlockIndex *CCoinsViewCache::GetBestBlock() {
233 if (pindexTip == NULL)
234 pindexTip = base->GetBestBlock();
238 bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
243 bool CCoinsViewCache::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
244 for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
245 cacheCoins[it->first] = it->second;
250 bool CCoinsViewCache::Flush() {
251 bool fOk = base->BatchWrite(cacheCoins, pindexTip);
257 unsigned int CCoinsViewCache::GetCacheSize() {
258 return cacheCoins.size();
261 /** CCoinsView that brings transactions from a memorypool into view.
262 It does not check for spendings by memory pool transactions. */
263 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
265 bool CCoinsViewMemPool::GetCoins(uint256 txid, CCoins &coins) {
266 if (base->GetCoins(txid, coins))
268 if (mempool.exists(txid)) {
269 const CTransaction &tx = mempool.lookup(txid);
270 coins = CCoins(tx, MEMPOOL_HEIGHT, -1);
276 bool CCoinsViewMemPool::HaveCoins(uint256 txid) {
277 return mempool.exists(txid) || base->HaveCoins(txid);
280 CCoinsViewCache *pcoinsTip = NULL;
282 //////////////////////////////////////////////////////////////////////////////
284 // mapOrphanTransactions
287 bool AddOrphanTx(const CTransaction& tx)
289 uint256 hash = tx.GetHash();
290 if (mapOrphanTransactions.count(hash))
293 // Ignore big transactions, to avoid a
294 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
295 // large transaction with a missing parent then we assume
296 // it will rebroadcast it later, after the parent transaction(s)
297 // have been mined or received.
298 // 10,000 orphans, each of which is at most 5,000 bytes big is
299 // at most 500 megabytes of orphans:
301 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
305 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
309 mapOrphanTransactions[hash] = tx;
310 BOOST_FOREACH(const CTxIn& txin, tx.vin)
311 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
313 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
314 mapOrphanTransactions.size());
318 void static EraseOrphanTx(uint256 hash)
320 if (!mapOrphanTransactions.count(hash))
322 const CTransaction& tx = mapOrphanTransactions[hash];
323 BOOST_FOREACH(const CTxIn& txin, tx.vin)
325 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
326 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
327 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
329 mapOrphanTransactions.erase(hash);
332 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
334 unsigned int nEvicted = 0;
335 while (mapOrphanTransactions.size() > nMaxOrphans)
337 // Evict a random orphan:
338 uint256 randomhash = GetRandHash();
339 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
340 if (it == mapOrphanTransactions.end())
341 it = mapOrphanTransactions.begin();
342 EraseOrphanTx(it->first);
354 //////////////////////////////////////////////////////////////////////////////
359 bool CTransaction::IsStandard() const
361 if (nVersion > CTransaction::CURRENT_VERSION)
364 BOOST_FOREACH(const CTxIn& txin, vin)
366 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
367 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
368 // ~65-byte public keys, plus a few script ops.
369 if (txin.scriptSig.size() > 500)
371 if (!txin.scriptSig.IsPushOnly())
374 BOOST_FOREACH(const CTxOut& txout, vout) {
375 if (!::IsStandard(txout.scriptPubKey))
377 if (txout.nValue == 0)
384 // Check transaction inputs, and make sure any
385 // pay-to-script-hash transactions are evaluating IsStandard scripts
387 // Why bother? To avoid denial-of-service attacks; an attacker
388 // can submit a standard HASH... OP_EQUAL transaction,
389 // which will get accepted into blocks. The redemption
390 // script can be anything; an attacker could use a very
391 // expensive-to-check-upon-redemption script like:
392 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
394 bool CTransaction::AreInputsStandard(CCoinsView& mapInputs) const
397 return true; // Coinbases don't use vin normally
399 for (unsigned int i = 0; i < vin.size(); i++)
401 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
403 vector<vector<unsigned char> > vSolutions;
404 txnouttype whichType;
405 // get the scriptPubKey corresponding to this input:
406 const CScript& prevScript = prev.scriptPubKey;
407 if (!Solver(prevScript, whichType, vSolutions))
409 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
410 if (nArgsExpected < 0)
413 // Transactions with extra stuff in their scriptSigs are
414 // non-standard. Note that this EvalScript() call will
415 // be quick, because if there are any operations
416 // beside "push data" in the scriptSig the
417 // IsStandard() call returns false
418 vector<vector<unsigned char> > stack;
419 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
422 if (whichType == TX_SCRIPTHASH)
426 CScript subscript(stack.back().begin(), stack.back().end());
427 vector<vector<unsigned char> > vSolutions2;
428 txnouttype whichType2;
429 if (!Solver(subscript, whichType2, vSolutions2))
431 if (whichType2 == TX_SCRIPTHASH)
435 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
438 nArgsExpected += tmpExpected;
441 if (stack.size() != (unsigned int)nArgsExpected)
449 CTransaction::GetLegacySigOpCount() const
451 unsigned int nSigOps = 0;
452 BOOST_FOREACH(const CTxIn& txin, vin)
454 nSigOps += txin.scriptSig.GetSigOpCount(false);
456 BOOST_FOREACH(const CTxOut& txout, vout)
458 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
464 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
474 if (pblock == NULL) {
476 if (pcoinsTip->GetCoins(GetHash(), coins)) {
477 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
479 if (!blockTmp.ReadFromDisk(pindex))
487 // Update the tx's hashBlock
488 hashBlock = pblock->GetHash();
490 // Locate the transaction
491 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
492 if (pblock->vtx[nIndex] == *(CTransaction*)this)
494 if (nIndex == (int)pblock->vtx.size())
496 vMerkleBranch.clear();
498 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
502 // Fill in merkle branch
503 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
507 // Is the tx in a block that's in the main chain
508 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
509 if (mi == mapBlockIndex.end())
511 CBlockIndex* pindex = (*mi).second;
512 if (!pindex || !pindex->IsInMainChain())
515 return pindexBest->nHeight - pindex->nHeight + 1;
518 bool CTransaction::CheckTransaction() const
520 // Basic checks that don't depend on any context
522 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
524 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
526 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
527 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
529 // Check for negative or overflow output values
531 for (unsigned int i = 0; i < vout.size(); i++)
533 const CTxOut& txout = vout[i];
534 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
535 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
537 // Enforce minimum output amount for user transactions until 1 May 2014 04:00:00 GMT
538 if (!fTestNet && !IsCoinBase() && !txout.IsEmpty() && nTime < OUTPUT_SWITCH_TIME && txout.nValue < MIN_TXOUT_AMOUNT)
539 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
541 if (txout.nValue > MAX_MONEY)
542 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
543 nValueOut += txout.nValue;
544 if (!MoneyRange(nValueOut))
545 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
548 // Check for duplicate inputs
549 set<COutPoint> vInOutPoints;
550 BOOST_FOREACH(const CTxIn& txin, vin)
552 if (vInOutPoints.count(txin.prevout))
554 vInOutPoints.insert(txin.prevout);
559 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
560 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
564 BOOST_FOREACH(const CTxIn& txin, vin)
565 if (txin.prevout.IsNull())
566 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
572 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
573 enum GetMinFee_mode mode, unsigned int nBytes) const
575 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
576 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
578 unsigned int nNewBlockSize = nBlockSize + nBytes;
579 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
581 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
582 if (nMinFee < nBaseFee)
584 BOOST_FOREACH(const CTxOut& txout, vout)
585 if (txout.nValue < CENT)
589 // Raise the price as the block approaches full
590 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
592 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
594 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
597 if (!MoneyRange(nMinFee))
602 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
606 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
608 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
609 while (it != mapNextTx.end() && it->first.hash == hashTx) {
610 coins.Spend(it->first.n); // and remove those outputs from coins
615 bool CTxMemPool::accept(CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs)
618 *pfMissingInputs = false;
620 if (!tx.CheckTransaction())
621 return error("CTxMemPool::accept() : CheckTransaction failed");
623 // Coinbase is only valid in a block, not as a loose transaction
625 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
627 // Coinstake is also only valid in a block, not as a loose transaction
628 if (tx.IsCoinStake())
629 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
631 // To help v0.1.5 clients who would see it as a negative number
632 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
633 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
635 // Rather not work on nonstandard transactions (unless -testnet)
636 if (!fTestNet && !tx.IsStandard())
637 return error("CTxMemPool::accept() : nonstandard transaction type");
639 // is it already in the memory pool?
640 uint256 hash = tx.GetHash();
643 if (mapTx.count(hash))
647 // Check for conflicts with in-memory transactions
648 CTransaction* ptxOld = NULL;
649 for (unsigned int i = 0; i < tx.vin.size(); i++)
651 COutPoint outpoint = tx.vin[i].prevout;
652 if (mapNextTx.count(outpoint))
654 // Disable replacement feature for now
657 // Allow replacing with a newer version of the same transaction
660 ptxOld = mapNextTx[outpoint].ptx;
661 if (ptxOld->IsFinal())
663 if (!tx.IsNewerThan(*ptxOld))
665 for (unsigned int i = 0; i < tx.vin.size(); i++)
667 COutPoint outpoint = tx.vin[i].prevout;
668 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
677 CCoinsViewCache &view = *pcoinsTip;
679 // do we already have it?
680 if (view.HaveCoins(hash))
683 // do all inputs exist?
684 BOOST_FOREACH(const CTxIn txin, tx.vin) {
685 if (!view.HaveCoins(txin.prevout.hash)) {
687 *pfMissingInputs = true;
692 // Check for non-standard pay-to-script-hash in inputs
693 if (!tx.AreInputsStandard(view) && !fTestNet)
694 return error("CTxMemPool::accept() : nonstandard transaction input");
696 // Note: if you modify this code to accept non-standard transactions, then
697 // you should add code here to check that the transaction does a
698 // reasonable number of ECDSA signature verifications.
700 int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
701 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
703 // Don't accept it if it can't get into a block
704 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY, nSize);
705 if (nFees < txMinFee)
706 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
707 hash.ToString().c_str(),
711 // Continuously rate-limit free transactions
712 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
713 // be annoying or make others' transactions take longer to confirm.
714 if (nFees < MIN_RELAY_TX_FEE)
716 static CCriticalSection cs;
717 static double dFreeCount;
718 static int64 nLastTime;
719 int64 nNow = GetTime();
723 // Use an exponentially decaying ~10-minute window:
724 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
726 // -limitfreerelay unit is thousand-bytes-per-minute
727 // At default rate it would take over a month to fill 1GB
728 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
729 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
731 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
736 // Check against previous transactions
737 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
738 if (!tx.CheckInputs(view, CS_ALWAYS, true, false))
740 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
744 // Store transaction in memory
749 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
752 addUnchecked(hash, tx);
755 ///// are we sure this is ok when loading transactions or restoring block txes
756 // If updated, erase old tx from wallet
758 EraseFromWallets(ptxOld->GetHash());
760 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
761 hash.ToString().substr(0,10).c_str(),
766 bool CTransaction::AcceptToMemoryPool(bool fCheckInputs, bool* pfMissingInputs)
768 return mempool.accept(*this, fCheckInputs, pfMissingInputs);
771 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
773 // Add to memory pool without checking anything. Don't call this directly,
774 // call CTxMemPool::accept to properly check the transaction first.
777 for (unsigned int i = 0; i < tx.vin.size(); i++)
778 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
779 nTransactionsUpdated++;
785 bool CTxMemPool::remove(CTransaction &tx)
787 // Remove transaction from memory pool
790 uint256 hash = tx.GetHash();
791 if (mapTx.count(hash))
793 BOOST_FOREACH(const CTxIn& txin, tx.vin)
794 mapNextTx.erase(txin.prevout);
796 nTransactionsUpdated++;
802 void CTxMemPool::clear()
807 ++nTransactionsUpdated;
810 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
815 vtxid.reserve(mapTx.size());
816 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
817 vtxid.push_back((*mi).first);
823 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
825 if (hashBlock == 0 || nIndex == -1)
828 // Find the block it claims to be in
829 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
830 if (mi == mapBlockIndex.end())
832 CBlockIndex* pindex = (*mi).second;
833 if (!pindex || !pindex->IsInMainChain())
836 // Make sure the merkle branch connects to this block
837 if (!fMerkleVerified)
839 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
841 fMerkleVerified = true;
845 return pindexBest->nHeight - pindex->nHeight + 1;
848 int CMerkleTx::GetBlocksToMaturity() const
850 if (!(IsCoinBase() || IsCoinStake()))
852 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
856 bool CMerkleTx::AcceptToMemoryPool(bool fCheckInputs)
860 if (!IsInMainChain() && !ClientCheckInputs())
862 return CTransaction::AcceptToMemoryPool(false);
866 return CTransaction::AcceptToMemoryPool(fCheckInputs);
870 bool CWalletTx::AcceptWalletTransaction(bool fCheckInputs)
875 // Add previous supporting transactions first
876 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
878 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
880 uint256 hash = tx.GetHash();
881 if (!mempool.exists(hash) && pcoinsTip->HaveCoins(hash))
882 tx.AcceptToMemoryPool(fCheckInputs);
885 return AcceptToMemoryPool(fCheckInputs);
890 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
891 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
893 CBlockIndex *pindexSlow = NULL;
898 if (mempool.exists(hash))
900 txOut = mempool.lookup(hash);
905 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
908 CCoinsViewCache &view = *pcoinsTip;
910 if (view.GetCoins(hash, coins))
911 nHeight = coins.nHeight;
914 pindexSlow = FindBlockByHeight(nHeight);
920 if (block.ReadFromDisk(pindexSlow)) {
921 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
922 if (tx.GetHash() == hash) {
924 hashBlock = pindexSlow->GetBlockHash();
935 //////////////////////////////////////////////////////////////////////////////
937 // CBlock and CBlockIndex
940 static CBlockIndex* pblockindexFBBHLast;
941 CBlockIndex* FindBlockByHeight(int nHeight)
943 CBlockIndex *pblockindex;
944 if (nHeight < nBestHeight / 2)
945 pblockindex = pindexGenesisBlock;
947 pblockindex = pindexBest;
948 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
949 pblockindex = pblockindexFBBHLast;
950 while (pblockindex->nHeight > nHeight)
951 pblockindex = pblockindex->pprev;
952 while (pblockindex->nHeight < nHeight)
953 pblockindex = pblockindex->pnext;
954 pblockindexFBBHLast = pblockindex;
958 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
960 if (!fReadTransactions)
962 *this = pindex->GetBlockHeader();
965 if (!ReadFromDisk(pindex->GetBlockPos(), fReadTransactions))
967 if (GetHash() != pindex->GetBlockHash())
968 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
972 uint256 static GetOrphanRoot(const CBlock* pblock)
974 // Work back to the first block in the orphan chain
975 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
976 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
977 return pblock->GetHash();
980 // ppcoin: find block wanted by given orphan block
981 uint256 WantedByOrphan(const CBlock* pblockOrphan)
983 // Work back to the first block in the orphan chain
984 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
985 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
986 return pblockOrphan->hashPrevBlock;
989 // select stake target limit according to hard-coded conditions
990 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
992 if(fTestNet) // separate proof of stake target limit for testnet
993 return bnProofOfStakeLimit;
994 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
995 return bnProofOfStakeLimit;
996 if(nHeight + 1 > 15000) // 24 bits since block 15000
997 return bnProofOfStakeLegacyLimit;
998 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
999 return bnProofOfStakeHardLimit;
1001 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1004 // miner's coin base reward based on nBits
1005 int64 GetProofOfWorkReward(unsigned int nBits)
1007 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1010 bnTarget.SetCompact(nBits);
1011 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1012 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1014 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1015 // A reasonably continuous curve is used to avoid shock to market
1016 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1018 // Human readable form:
1020 // nSubsidy = 100 / (diff ^ 1/6)
1021 CBigNum bnLowerBound = CENT;
1022 CBigNum bnUpperBound = bnSubsidyLimit;
1023 while (bnLowerBound + CENT <= bnUpperBound)
1025 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1026 if (fDebug && GetBoolArg("-printcreation"))
1027 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1028 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1029 bnUpperBound = bnMidValue;
1031 bnLowerBound = bnMidValue;
1034 int64 nSubsidy = bnUpperBound.getuint64();
1036 nSubsidy = (nSubsidy / CENT) * CENT;
1037 if (fDebug && GetBoolArg("-printcreation"))
1038 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1040 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
1043 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1044 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
1046 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1048 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1050 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1052 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1054 bnTarget.SetCompact(nBits);
1055 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1056 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1058 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1060 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1061 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1062 bnMidPart, bnRewardPart;
1064 while (bnLowerBound + CENT <= bnUpperBound)
1066 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1067 if (fDebug && GetBoolArg("-printcreation"))
1068 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1070 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1073 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1075 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1077 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1080 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1081 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1086 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1088 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1090 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1093 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1094 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1097 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1098 bnUpperBound = bnMidValue;
1100 bnLowerBound = bnMidValue;
1103 nRewardCoinYear = bnUpperBound.getuint64();
1104 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1108 // Old creation amount per coin-year, 5% fixed stake mint rate
1109 nRewardCoinYear = 5 * CENT;
1113 return nRewardCoinYear;
1115 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1117 // Set reasonable reward limit for large inputs since 20 Oct 2013
1119 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1120 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1122 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1123 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1125 nSubsidy = min(nSubsidy, nSubsidyLimit);
1128 if (fDebug && GetBoolArg("-printcreation"))
1129 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1133 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1135 // get proof of work blocks max spacing according to hard-coded conditions
1136 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1138 if(nTime > TARGETS_SWITCH_TIME)
1139 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1142 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1144 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1148 // maximum nBits value could possible be required nTime after
1150 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1153 bnResult.SetCompact(nBase);
1155 while (nTime > 0 && bnResult < bnTargetLimit)
1157 // Maximum 200% adjustment per day...
1159 nTime -= 24 * 60 * 60;
1161 if (bnResult > bnTargetLimit)
1162 bnResult = bnTargetLimit;
1163 return bnResult.GetCompact();
1167 // minimum amount of work that could possibly be required nTime after
1168 // minimum proof-of-work required was nBase
1170 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1172 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1176 // minimum amount of stake that could possibly be required nTime after
1177 // minimum proof-of-stake required was nBase
1179 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1181 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1185 // ppcoin: find last block index up to pindex
1186 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1188 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1189 pindex = pindex->pprev;
1193 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1195 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1197 if (pindexLast == NULL)
1198 return bnTargetLimit.GetCompact(); // genesis block
1200 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1201 if (pindexPrev->pprev == NULL)
1202 return bnTargetLimit.GetCompact(); // first block
1203 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1204 if (pindexPrevPrev->pprev == NULL)
1205 return bnTargetLimit.GetCompact(); // second block
1207 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1209 // ppcoin: target change every block
1210 // ppcoin: retarget with exponential moving toward target spacing
1212 bnNew.SetCompact(pindexPrev->nBits);
1213 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1214 int64 nInterval = nTargetTimespan / nTargetSpacing;
1215 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1216 bnNew /= ((nInterval + 1) * nTargetSpacing);
1218 if (bnNew > bnTargetLimit)
1219 bnNew = bnTargetLimit;
1221 return bnNew.GetCompact();
1224 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1227 bnTarget.SetCompact(nBits);
1230 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1231 return error("CheckProofOfWork() : nBits below minimum work");
1233 // Check proof of work matches claimed amount
1234 if (hash > bnTarget.getuint256())
1235 return error("CheckProofOfWork() : hash doesn't match nBits");
1240 // Return maximum amount of blocks that other nodes claim to have
1241 int GetNumBlocksOfPeers()
1243 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1246 bool IsInitialBlockDownload()
1248 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1250 static int64 nLastUpdate;
1251 static CBlockIndex* pindexLastBest;
1252 if (pindexBest != pindexLastBest)
1254 pindexLastBest = pindexBest;
1255 nLastUpdate = GetTime();
1257 return (GetTime() - nLastUpdate < 10 &&
1258 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1261 void static InvalidChainFound(CBlockIndex* pindexNew)
1263 if (pindexNew->nChainTrust > nBestInvalidTrust)
1265 nBestInvalidTrust = pindexNew->nChainTrust;
1266 CChainDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1267 uiInterface.NotifyBlocksChanged();
1270 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1271 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1273 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1274 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1275 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1276 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1277 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1278 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1279 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1280 nBestBlockTrust.Get64(),
1281 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1285 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1287 nTime = max(GetBlockTime(), GetAdjustedTime());
1291 CTxOut CTransaction::GetOutputFor(const CTxIn& input, CCoinsView& view)
1294 if (!view.GetCoins(input.prevout.hash, coins))
1295 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1297 if (input.prevout.n >= coins.vout.size())
1298 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range or already spent");
1300 const CTxOut &out = coins.vout[input.prevout.n];
1302 throw std::runtime_error("CTransaction::GetOutputFor() : already spent");
1307 int64 CTransaction::GetValueIn(CCoinsView& inputs) const
1313 for (unsigned int i = 0; i < vin.size(); i++)
1315 nResult += GetOutputFor(vin[i], inputs).nValue;
1320 unsigned int CTransaction::GetP2SHSigOpCount(CCoinsView& inputs) const
1325 unsigned int nSigOps = 0;
1326 for (unsigned int i = 0; i < vin.size(); i++)
1328 CTxOut prevout = GetOutputFor(vin[i], inputs);
1329 if (prevout.scriptPubKey.IsPayToScriptHash())
1330 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1335 bool CTransaction::UpdateCoins(CCoinsView &inputs, CTxUndo &txundo, int nHeight, unsigned int nTimeStamp) const
1337 uint256 hash = GetHash();
1339 // mark inputs spent
1340 if (!IsCoinBase()) {
1341 BOOST_FOREACH(const CTxIn &txin, vin) {
1343 if (!inputs.GetCoins(txin.prevout.hash, coins))
1344 return error("UpdateCoins() : cannot find prevtx");
1345 if (coins.nTime > nTimeStamp)
1346 return error("UpdateCoins() : timestamp violation");
1348 if (!coins.Spend(txin.prevout, undo))
1349 return error("UpdateCoins() : cannot spend input");
1350 txundo.vprevout.push_back(undo);
1351 if (!inputs.SetCoins(txin.prevout.hash, coins))
1352 return error("UpdateCoins() : cannot update input");
1357 if (!inputs.SetCoins(hash, CCoins(*this, nHeight, nTimeStamp)))
1358 return error("UpdateCoins() : cannot update output");
1363 bool CTransaction::HaveInputs(CCoinsView &inputs) const
1365 if (!IsCoinBase()) {
1366 // first check whether information about the prevout hash is available
1367 for (unsigned int i = 0; i < vin.size(); i++) {
1368 const COutPoint &prevout = vin[i].prevout;
1369 if (!inputs.HaveCoins(prevout.hash))
1373 // then check whether the actual outputs are available
1374 for (unsigned int i = 0; i < vin.size(); i++) {
1375 const COutPoint &prevout = vin[i].prevout;
1377 inputs.GetCoins(prevout.hash, coins);
1378 if (!coins.IsAvailable(prevout.n))
1385 bool CTransaction::CheckInputs(CCoinsView &inputs, enum CheckSig_mode csmode, bool fStrictPayToScriptHash, bool fStrictEncodings, CBlock *pblock) const
1391 for (unsigned int i = 0; i < vin.size(); i++)
1393 const COutPoint &prevout = vin[i].prevout;
1395 if (!inputs.GetCoins(prevout.hash, coins))
1396 return error("CheckInputs() : cannot find prevout tx");
1398 // Check for conflicts (double-spend)
1399 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1400 // for an attacker to attempt to split the network.
1401 if (!coins.IsAvailable(prevout.n))
1402 return error("CheckInputs() : %s prev tx already used", GetHash().ToString().substr(0,10).c_str());
1404 // If prev is coinbase or coinstake, check that it's matured
1405 if (coins.IsCoinBase() || coins.IsCoinStake()) {
1406 CBlockIndex *pindexBlock = inputs.GetBestBlock();
1407 if (pindexBlock->nHeight - coins.nHeight < nCoinbaseMaturity)
1408 return error("CheckInputs() : tried to spend %s at depth %d", coins.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - coins.nHeight);
1411 // Check transaction timestamp
1412 if (coins.nTime > nTime)
1413 return DoS(100, error("CheckInputs() : transaction timestamp earlier than input transaction"));
1415 // Check for negative or overflow input values
1416 nValueIn += coins.vout[prevout.n].nValue;
1417 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1418 return DoS(100, error("CheckInputs() : txin values out of range"));
1424 return error("CheckInputs() : %s is a coinstake, but no block specified", GetHash().ToString().substr(0,10).c_str());
1426 // Coin stake tx earns reward instead of paying fee
1428 if (!GetCoinAge(nCoinAge))
1429 return error("CheckInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1431 int64 nStakeReward = GetValueOut() - nValueIn;
1432 int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pblock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1434 if (nStakeReward > nCalculatedStakeReward)
1435 return DoS(100, error("CheckInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1439 if (nValueIn < GetValueOut())
1440 return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1442 // Tally transaction fees
1443 int64 nTxFee = nValueIn - GetValueOut();
1445 return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1447 if (!MoneyRange(nFees))
1448 return DoS(100, error("CheckInputs() : nFees out of range"));
1450 // enforce transaction fees for every block until 1 May 2014 04:00:00 GMT
1451 if (!fTestNet && nTxFee < GetMinFee() && nTime < OUTPUT_SWITCH_TIME)
1452 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;
1455 // The first loop above does all the inexpensive checks.
1456 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1457 // Helps prevent CPU exhaustion attacks.
1459 // Skip ECDSA signature verification when connecting blocks
1460 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1461 // still computed and checked, and any change will be caught at the next checkpoint.
1462 if (csmode == CS_ALWAYS ||
1463 (csmode == CS_AFTER_CHECKPOINT && inputs.GetBestBlock()->nHeight >= Checkpoints::GetTotalBlocksEstimate())) {
1464 for (unsigned int i = 0; i < vin.size(); i++) {
1465 const COutPoint &prevout = vin[i].prevout;
1467 inputs.GetCoins(prevout.hash, coins);
1470 if (!VerifySignature(coins, *this, i, fStrictPayToScriptHash, fStrictEncodings, 0)) {
1471 // only during transition phase for P2SH: do not invoke anti-DoS code for
1472 // potentially old clients relaying bad P2SH transactions
1473 if (fStrictPayToScriptHash && VerifySignature(coins, *this, i, false, fStrictEncodings, 0))
1474 return error("CheckInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1476 return DoS(100,error("CheckInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1486 bool CTransaction::ClientCheckInputs() const
1491 // Take over previous transactions' spent pointers
1495 for (unsigned int i = 0; i < vin.size(); i++)
1497 // Get prev tx from single transactions in memory
1498 COutPoint prevout = vin[i].prevout;
1499 if (!mempool.exists(prevout.hash))
1501 CTransaction& txPrev = mempool.lookup(prevout.hash);
1503 if (prevout.n >= txPrev.vout.size())
1507 if (!VerifySignature(CCoins(txPrev, -1, -1), *this, i, true, false, 0))
1508 return error("ConnectInputs() : VerifySignature failed");
1510 ///// this is redundant with the mempool.mapNextTx stuff,
1511 ///// not sure which I want to get rid of
1512 ///// this has to go away now that posNext is gone
1513 // // Check for conflicts
1514 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1515 // return error("ConnectInputs() : prev tx already used");
1517 // // Flag outpoints as used
1518 // txPrev.vout[prevout.n].posNext = posThisTx;
1520 nValueIn += txPrev.vout[prevout.n].nValue;
1522 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1523 return error("ClientConnectInputs() : txin values out of range");
1525 if (GetValueOut() > nValueIn)
1532 bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsView &view)
1534 assert(pindex == view.GetBestBlock());
1536 CBlockUndo blockUndo;
1538 CDiskBlockPos pos = pindex->GetUndoPos();
1540 return error("DisconnectBlock() : no undo data available");
1541 FILE *file = OpenUndoFile(pos, true);
1543 return error("DisconnectBlock() : undo file not available");
1544 CAutoFile fileUndo(file, SER_DISK, CLIENT_VERSION);
1545 fileUndo >> blockUndo;
1548 assert(blockUndo.vtxundo.size() + 1 == vtx.size());
1550 // undo transactions in reverse order
1551 for (int i = vtx.size() - 1; i >= 0; i--) {
1552 const CTransaction &tx = vtx[i];
1553 uint256 hash = tx.GetHash();
1555 // check that all outputs are available
1557 if (!view.GetCoins(hash, outs))
1558 return error("DisconnectBlock() : outputs still spent? database corrupted");
1560 CCoins outsBlock = CCoins(tx, pindex->nHeight, pindex->nTime);
1561 if (outs != outsBlock)
1562 return error("DisconnectBlock() : added transaction mismatch? database corrupted");
1565 if (!view.SetCoins(hash, CCoins()))
1566 return error("DisconnectBlock() : cannot delete coin outputs");
1569 if (i > 0) { // not coinbases
1570 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1571 assert(txundo.vprevout.size() == tx.vin.size());
1572 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1573 const COutPoint &out = tx.vin[j].prevout;
1574 const CTxInUndo &undo = txundo.vprevout[j];
1576 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1577 if (coins.IsPruned()) {
1578 if (undo.nHeight == 0)
1579 return error("DisconnectBlock() : undo data doesn't contain tx metadata? database corrupted");
1580 coins.fCoinBase = undo.fCoinBase;
1581 coins.nHeight = undo.nHeight;
1582 coins.nVersion = undo.nVersion;
1584 if (undo.nHeight != 0)
1585 return error("DisconnectBlock() : undo data contains unneeded tx metadata? database corrupted");
1587 if (coins.IsAvailable(out.n))
1588 return error("DisconnectBlock() : prevout output not spent? database corrupted");
1589 if (coins.vout.size() < out.n+1)
1590 coins.vout.resize(out.n+1);
1591 coins.vout[out.n] = undo.txout;
1592 if (!view.SetCoins(out.hash, coins))
1593 return error("DisconnectBlock() : cannot restore coin inputs");
1598 // move best block pointer to prevout block
1599 view.SetBestBlock(pindex->pprev);
1604 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1606 bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsView &view, bool fJustCheck)
1608 // Check it again in case a previous version let a bad block in
1609 if (!CheckBlock(!fJustCheck, !fJustCheck))
1612 // verify that the view's current state corresponds to the previous block
1613 assert(pindex->pprev == view.GetBestBlock());
1615 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1616 // unless those are already completely spent.
1617 // If such overwrites are allowed, coinbases and transactions depending upon those
1618 // can be duplicated to remove the ability to spend the first instance -- even after
1619 // being sent to another address.
1620 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1621 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1622 // already refuses previously-known transaction ids entirely.
1623 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1624 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1625 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1626 // initial block download.
1627 bool fEnforceBIP30 = true;
1629 if (fEnforceBIP30) {
1630 BOOST_FOREACH(CTransaction& tx, vtx) {
1631 uint256 hash = tx.GetHash();
1633 if (view.GetCoins(hash, coins) && !coins.IsPruned())
1634 return error("ConnectBlock() : tried to overwrite transaction");
1638 // BIP16 always active
1639 bool fStrictPayToScriptHash = true;
1641 CBlockUndo blockundo;
1643 int64 nFees = 0, nValueIn = 0, nValueOut = 0;
1644 unsigned int nSigOps = 0;
1645 BOOST_FOREACH(CTransaction& tx, vtx)
1647 nSigOps += tx.GetLegacySigOpCount();
1648 if (nSigOps > MAX_BLOCK_SIGOPS)
1649 return DoS(100, error("ConnectBlock() : too many sigops"));
1651 if (!tx.IsCoinBase())
1653 if (!tx.HaveInputs(view))
1654 return DoS(100, error("ConnectBlock() : inputs missing/spent"));
1656 if (fStrictPayToScriptHash)
1658 // Add in sigops done by pay-to-script-hash inputs;
1659 // this is to prevent a "rogue miner" from creating
1660 // an incredibly-expensive-to-validate block.
1661 nSigOps += tx.GetP2SHSigOpCount(view);
1662 if (nSigOps > MAX_BLOCK_SIGOPS)
1663 return DoS(100, error("ConnectBlock() : too many sigops"));
1666 int64 nTxValueOut = tx.GetValueOut();
1667 int64 nTxValueIn = tx.GetValueIn(view);
1669 nValueIn += nTxValueIn;
1670 nValueOut += nTxValueOut;
1672 if (!tx.IsCoinStake())
1673 nFees += nTxValueIn - nTxValueOut;
1675 if (!tx.CheckInputs(view, CS_AFTER_CHECKPOINT, fStrictPayToScriptHash, false, this))
1680 nValueOut += tx.GetValueOut();
1684 if (!tx.UpdateCoins(view, txundo, pindex->nHeight, pindex->nTime))
1685 return error("ConnectBlock() : UpdateInputs failed");
1686 if (!tx.IsCoinBase())
1687 blockundo.vtxundo.push_back(txundo);
1690 pindex->nMint = nValueOut - nValueIn + nFees;
1691 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1699 // Write undo information to disk
1700 if (pindex->GetUndoPos().IsNull())
1702 if (!FindUndoPos(chaindb, pindex->pos.nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 8))
1703 return error("ConnectBlock() : FindUndoPos failed");
1704 if (!blockundo.WriteToDisk(pos))
1705 return error("ConnectBlock() : CBlockUndo::WriteToDisk failed");
1707 // update nUndoPos in block index
1708 pindex->nUndoPos = pos.nPos + 1;
1711 CDiskBlockIndex blockindex(pindex);
1712 if (!chaindb.WriteBlockIndex(blockindex))
1713 return error("ConnectBlock() : WriteBlockIndex failed");
1715 // add this block to the view's blockchain
1716 if (!view.SetBestBlock(pindex))
1719 // fees are destroyed to compensate the entire network
1720 if (fDebug && GetBoolArg("-printcreation"))
1721 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1723 // Watch for transactions paying to me
1724 BOOST_FOREACH(CTransaction& tx, vtx)
1725 SyncWithWallets(tx, this, true);
1730 bool CBlock::SetBestChain(CBlockIndex* pindexNew)
1732 CCoinsViewCache &view = *pcoinsTip;
1734 // special case for attaching the genesis block
1735 // note that no ConnectBlock is called, so its coinbase output is non-spendable
1736 if (pindexGenesisBlock == NULL && pindexNew->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1738 view.SetBestBlock(pindexNew);
1741 pindexGenesisBlock = pindexNew;
1742 pindexBest = pindexNew;
1743 hashBestChain = pindexNew->GetBlockHash();
1744 nBestHeight = pindexBest->nHeight;
1745 nBestChainTrust = pindexNew->nChainTrust;
1749 // Find the fork (typically, there is none)
1750 CBlockIndex* pfork = view.GetBestBlock();
1751 CBlockIndex* plonger = pindexNew;
1752 while (pfork != plonger)
1754 while (plonger->nHeight > pfork->nHeight)
1755 if (!(plonger = plonger->pprev))
1756 return error("SetBestChain() : plonger->pprev is null");
1757 if (pfork == plonger)
1759 if (!(pfork = pfork->pprev))
1760 return error("SetBestChain() : pfork->pprev is null");
1763 // List of what to disconnect (typically nothing)
1764 vector<CBlockIndex*> vDisconnect;
1765 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1766 vDisconnect.push_back(pindex);
1768 // List of what to connect (typically only pindexNew)
1769 vector<CBlockIndex*> vConnect;
1770 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1771 vConnect.push_back(pindex);
1772 reverse(vConnect.begin(), vConnect.end());
1774 if (vDisconnect.size() > 0) {
1775 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());
1776 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());
1779 // Disconnect shorter branch
1780 vector<CTransaction> vResurrect;
1781 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
1783 if (!block.ReadFromDisk(pindex))
1784 return error("SetBestBlock() : ReadFromDisk for disconnect failed");
1785 CCoinsViewCache viewTemp(view, true);
1786 if (!block.DisconnectBlock(pindex, viewTemp))
1787 return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1788 if (!viewTemp.Flush())
1789 return error("SetBestBlock() : Cache flush failed after disconnect");
1791 // Queue memory transactions to resurrect
1792 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1793 if (!tx.IsCoinBase() && !tx.IsCoinStake())
1794 vResurrect.push_back(tx);
1797 // Connect longer branch
1798 vector<CTransaction> vDelete;
1799 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
1802 if (pindex == pindexNew) // connecting *this block
1804 else { // other block; read it from disk
1805 if (!block.ReadFromDisk(pindex))
1806 return error("SetBestBlock() : ReadFromDisk for connect failed");
1809 CCoinsViewCache viewTemp(view, true);
1810 if (!pblock->ConnectBlock(pindex, viewTemp)) {
1811 InvalidChainFound(pindexNew);
1812 return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1814 if (!viewTemp.Flush())
1815 return error("SetBestBlock() : Cache flush failed after connect");
1817 // Queue memory transactions to delete
1818 BOOST_FOREACH(const CTransaction& tx, pblock->vtx)
1819 vDelete.push_back(tx);
1822 // Make sure it's successfully written to disk before changing memory structure
1823 bool fIsInitialDownload = IsInitialBlockDownload();
1824 if (!fIsInitialDownload || view.GetCacheSize()>5000)
1828 // At this point, all changes have been done to the database.
1829 // Proceed by updating the memory structures.
1831 // Disconnect shorter branch
1832 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1834 pindex->pprev->pnext = NULL;
1836 // Connect longer branch
1837 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1839 pindex->pprev->pnext = pindex;
1841 // Resurrect memory transactions that were in the disconnected branch
1842 BOOST_FOREACH(CTransaction& tx, vResurrect)
1843 tx.AcceptToMemoryPool(false);
1845 // Delete redundant memory transactions that are in the connected branch
1846 BOOST_FOREACH(CTransaction& tx, vDelete)
1849 // Update best block in wallet (so we can detect restored wallets)
1850 if (!fIsInitialDownload)
1852 const CBlockLocator locator(pindexNew);
1853 ::SetBestChain(locator);
1857 hashBestChain = pindexNew->GetBlockHash();
1858 pindexBest = pindexNew;
1859 pblockindexFBBHLast = NULL;
1860 nBestHeight = pindexBest->nHeight;
1861 nBestChainTrust = pindexNew->nChainTrust;
1862 nTimeBestReceived = GetTime();
1863 nTransactionsUpdated++;
1865 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1867 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1868 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1869 CBigNum(nBestChainTrust).ToString().c_str(),
1870 nBestBlockTrust.Get64(),
1871 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1873 // Check the version of the last 100 blocks to see if we need to upgrade:
1874 if (!fIsInitialDownload)
1877 const CBlockIndex* pindex = pindexBest;
1878 for (int i = 0; i < 100 && pindex != NULL; i++)
1880 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1882 pindex = pindex->pprev;
1885 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1886 if (nUpgraded > 100/2)
1887 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1888 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1891 std::string strCmd = GetArg("-blocknotify", "");
1893 if (!fIsInitialDownload && !strCmd.empty())
1895 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1896 boost::thread t(runCommand, strCmd); // thread runs free
1902 // Total coin age spent in transaction, in the unit of coin-days.
1903 // Only those coins meeting minimum age requirement counts. As those
1904 // transactions not in main chain are not currently indexed so we
1905 // might not find out about their coin age. Older transactions are
1906 // guaranteed to be in main chain by sync-checkpoint. This rule is
1907 // introduced to help nodes establish a consistent view of the coin
1908 // age (trust score) of competing branches.
1909 bool CTransaction::GetCoinAge(uint64& nCoinAge) const
1911 CCoinsViewCache &inputs = *pcoinsTip;
1913 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1919 for (unsigned int i = 0; i < vin.size(); i++)
1921 const COutPoint &prevout = vin[i].prevout;
1923 if (!inputs.GetCoins(prevout.hash, coins))
1926 if (nTime < coins.nTime)
1927 return false; // Transaction timestamp violation
1929 // only count coins meeting min age requirement
1930 if (coins.nBlockTime + nStakeMinAge > nTime)
1933 int64 nValueIn = coins.vout[vin[i].prevout.n].nValue;
1934 bnCentSecond += CBigNum(nValueIn) * (nTime-coins.nTime) / CENT;
1937 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1938 if (fDebug && GetBoolArg("-printcoinage"))
1939 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1940 nCoinAge = bnCoinDay.getuint64();
1944 // Total coin age spent in block, in the unit of coin-days.
1945 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1949 BOOST_FOREACH(const CTransaction& tx, vtx)
1952 if (tx.GetCoinAge(nTxCoinAge))
1953 nCoinAge += nTxCoinAge;
1958 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1960 if (fDebug && GetBoolArg("-printcoinage"))
1961 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1965 bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
1967 // Check for duplicate
1968 uint256 hash = GetHash();
1969 if (mapBlockIndex.count(hash))
1970 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1972 // Construct new block index object
1973 CBlockIndex* pindexNew = new CBlockIndex(*this);
1975 return error("AddToBlockIndex() : new CBlockIndex failed");
1976 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1977 pindexNew->phashBlock = &((*mi).first);
1978 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1979 if (miPrev != mapBlockIndex.end())
1981 pindexNew->pprev = (*miPrev).second;
1982 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1984 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
1985 pindexNew->pos = pos;
1986 pindexNew->nUndoPos = 0;
1988 // Compute stake entropy bit for stake modifier
1989 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
1990 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
1992 // Record proof-of-stake hash value
1993 if (pindexNew->IsProofOfStake())
1995 if (!mapProofOfStake.count(hash))
1996 return error("AddToBlockIndex() : hashProofOfStake not found in map");
1997 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2000 // Compute stake modifier
2001 uint64 nStakeModifier = 0;
2002 bool fGeneratedStakeModifier = false;
2003 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2004 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2005 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2006 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2007 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2008 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2011 if (!chaindb.TxnBegin())
2013 chaindb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2014 if (!chaindb.TxnCommit())
2018 if (!SetBestChain(pindexNew))
2021 if (pindexNew == pindexBest)
2023 // Notify UI to display prev block's coinbase if it was ours
2024 static uint256 hashPrevBestCoinBase;
2025 UpdatedTransaction(hashPrevBestCoinBase);
2026 hashPrevBestCoinBase = vtx[0].GetHash();
2029 uiInterface.NotifyBlocksChanged();
2033 bool FindBlockPos(CChainDB &chaindb, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime)
2035 bool fUpdatedLast = false;
2037 LOCK(cs_LastBlockFile);
2039 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2040 printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
2041 FILE *file = OpenBlockFile(pos);
2044 file = OpenUndoFile(pos);
2048 infoLastBlockFile.SetNull();
2049 chaindb.ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
2050 fUpdatedLast = true;
2053 pos.nFile = nLastBlockFile;
2054 pos.nPos = infoLastBlockFile.nSize;
2055 infoLastBlockFile.nSize += nAddSize;
2056 infoLastBlockFile.AddBlock(nHeight, nTime);
2058 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2059 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2060 if (nNewChunks > nOldChunks) {
2061 FILE *file = OpenBlockFile(pos);
2063 printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2064 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2069 if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2070 return error("FindBlockPos() : cannot write updated block info");
2072 chaindb.WriteLastBlockFile(nLastBlockFile);
2077 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2081 LOCK(cs_LastBlockFile);
2083 unsigned int nNewSize;
2084 if (nFile == nLastBlockFile) {
2085 pos.nPos = infoLastBlockFile.nUndoSize;
2086 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2087 if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2088 return error("FindUndoPos() : cannot write updated block info");
2090 CBlockFileInfo info;
2091 if (!chaindb.ReadBlockFileInfo(nFile, info))
2092 return error("FindUndoPos() : cannot read block info");
2093 pos.nPos = info.nUndoSize;
2094 nNewSize = (info.nUndoSize += nAddSize);
2095 if (!chaindb.WriteBlockFileInfo(nFile, info))
2096 return error("FindUndoPos() : cannot write updated block info");
2099 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2100 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2101 if (nNewChunks > nOldChunks) {
2102 FILE *file = OpenUndoFile(pos);
2104 printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2105 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2113 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2115 // These are checks that are independent of context
2116 // that can be verified before saving an orphan block.
2119 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2120 return DoS(100, error("CheckBlock() : size limits failed"));
2122 // Check proof of work matches claimed amount
2123 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2124 return DoS(50, error("CheckBlock() : proof of work failed"));
2127 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2128 return error("CheckBlock() : block timestamp too far in the future");
2130 // First transaction must be coinbase, the rest must not be
2131 if (vtx.empty() || !vtx[0].IsCoinBase())
2132 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2133 for (unsigned int i = 1; i < vtx.size(); i++)
2134 if (vtx[i].IsCoinBase())
2135 return DoS(100, error("CheckBlock() : more than one coinbase"));
2137 // Check coinbase timestamp
2138 if (GetBlockTime() > FutureDrift((int64)vtx[0].nTime))
2139 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2141 if (IsProofOfStake())
2143 // Coinbase output should be empty if proof-of-stake block
2144 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2145 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2147 // Second transaction must be coinstake, the rest must not be
2148 if (vtx.empty() || !vtx[1].IsCoinStake())
2149 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2150 for (unsigned int i = 2; i < vtx.size(); i++)
2151 if (vtx[i].IsCoinStake())
2152 return DoS(100, error("CheckBlock() : more than one coinstake"));
2154 // Check coinstake timestamp
2155 if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2156 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2158 // NovaCoin: check proof-of-stake block signature
2159 if (fCheckSig && !CheckBlockSignature(true))
2160 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2164 int64 nReward = GetProofOfWorkReward(nBits);
2165 // Check coinbase reward
2166 if (vtx[0].GetValueOut() > nReward)
2167 return DoS(50, error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
2168 vtx[0].GetValueOut(),
2171 // Should we check proof-of-work block signature or not?
2173 // * Always skip on TestNet
2174 // * Perform checking for the first 9689 blocks
2175 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2177 if(!fTestNet && fCheckSig)
2179 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2181 // NovaCoin: check proof-of-work block signature
2182 if (checkEntropySig && !CheckBlockSignature(false))
2183 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2188 // Check transactions
2189 BOOST_FOREACH(const CTransaction& tx, vtx)
2191 if (!tx.CheckTransaction())
2192 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2194 // check transaction timestamp
2195 if (GetBlockTime() < (int64)tx.nTime)
2196 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2199 // Check for duplicate txids. This is caught by ConnectInputs(),
2200 // but catching it earlier avoids a potential DoS attack:
2201 set<uint256> uniqueTx;
2202 BOOST_FOREACH(const CTransaction& tx, vtx)
2204 uniqueTx.insert(tx.GetHash());
2206 if (uniqueTx.size() != vtx.size())
2207 return DoS(100, error("CheckBlock() : duplicate transaction"));
2209 unsigned int nSigOps = 0;
2210 BOOST_FOREACH(const CTransaction& tx, vtx)
2212 nSigOps += tx.GetLegacySigOpCount();
2214 if (nSigOps > MAX_BLOCK_SIGOPS)
2215 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2217 // Check merkle root
2218 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2219 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2225 bool CBlock::AcceptBlock()
2227 // Check for duplicate
2228 uint256 hash = GetHash();
2229 if (mapBlockIndex.count(hash))
2230 return error("AcceptBlock() : block already in mapBlockIndex");
2232 // Get prev block index
2233 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2234 if (mi == mapBlockIndex.end())
2235 return DoS(10, error("AcceptBlock() : prev block not found"));
2236 CBlockIndex* pindexPrev = (*mi).second;
2237 int nHeight = pindexPrev->nHeight+1;
2239 // Check proof-of-work or proof-of-stake
2240 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2241 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2243 // Check timestamp against prev
2244 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2245 return error("AcceptBlock() : block's timestamp is too early");
2247 // Check that all transactions are finalized
2248 BOOST_FOREACH(const CTransaction& tx, vtx)
2249 if (!tx.IsFinal(nHeight, GetBlockTime()))
2250 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2252 // Check that the block chain matches the known block chain up to a checkpoint
2253 if (!Checkpoints::CheckHardened(nHeight, hash))
2254 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2256 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2258 // Check that the block satisfies synchronized checkpoint
2259 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2260 return error("AcceptBlock() : rejected by synchronized checkpoint");
2262 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2263 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2265 // Enforce rule that the coinbase starts with serialized block height
2266 CScript expect = CScript() << nHeight;
2267 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2268 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2269 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2271 // Write block to history file
2272 unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
2273 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2274 return error("AcceptBlock() : out of disk space");
2275 CDiskBlockPos blockPos;
2278 if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, nHeight, nTime))
2279 return error("AcceptBlock() : FindBlockPos failed");
2281 if (!WriteToDisk(blockPos))
2282 return error("AcceptBlock() : WriteToDisk failed");
2283 if (!AddToBlockIndex(blockPos))
2284 return error("AcceptBlock() : AddToBlockIndex failed");
2286 // Relay inventory, but don't relay old inventory during initial block download
2287 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2288 if (hashBestChain == hash)
2291 BOOST_FOREACH(CNode* pnode, vNodes)
2292 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2293 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2296 // Check pending sync-checkpoint
2297 Checkpoints::AcceptPendingSyncCheckpoint();
2302 uint256 CBlockIndex::GetBlockTrust() const
2305 bnTarget.SetCompact(nBits);
2311 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2312 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2316 // Calculate work amount for block
2317 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2319 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2320 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2322 // Return nPoWTrust for the first 12 blocks
2323 if (pprev == NULL || pprev->nHeight < 12)
2326 const CBlockIndex* currentIndex = pprev;
2328 if(IsProofOfStake())
2330 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2332 // Return 1/3 of score if parent block is not the PoW block
2333 if (!pprev->IsProofOfWork())
2334 return (bnNewTrust / 3).getuint256();
2338 // Check last 12 blocks type
2339 while (pprev->nHeight - currentIndex->nHeight < 12)
2341 if (currentIndex->IsProofOfWork())
2343 currentIndex = currentIndex->pprev;
2346 // Return 1/3 of score if less than 3 PoW blocks found
2348 return (bnNewTrust / 3).getuint256();
2350 return bnNewTrust.getuint256();
2354 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2356 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2357 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2358 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2362 // Check last 12 blocks type
2363 while (pprev->nHeight - currentIndex->nHeight < 12)
2365 if (currentIndex->IsProofOfStake())
2367 currentIndex = currentIndex->pprev;
2370 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2372 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2374 bnTarget.SetCompact(pprev->nBits);
2379 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2381 // Return nPoWTrust + full trust score for previous block nBits
2382 return nPoWTrust + bnNewTrust.getuint256();
2386 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2388 unsigned int nFound = 0;
2389 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2391 if (pstart->nVersion >= minVersion)
2393 pstart = pstart->pprev;
2395 return (nFound >= nRequired);
2398 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2400 // Check for duplicate
2401 uint256 hash = pblock->GetHash();
2402 if (mapBlockIndex.count(hash))
2403 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2404 if (mapOrphanBlocks.count(hash))
2405 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2407 // ppcoin: check proof-of-stake
2408 // Limited duplicity on stake: prevents block flood attack
2409 // Duplicate stake allowed only when there is orphan child block
2410 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2411 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());
2413 // Preliminary checks
2414 if (!pblock->CheckBlock())
2415 return error("ProcessBlock() : CheckBlock FAILED");
2417 // ppcoin: verify hash target and signature of coinstake tx
2418 if (pblock->IsProofOfStake())
2420 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2421 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2423 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2424 return false; // do not error here as we expect this during initial block download
2426 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2427 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2430 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2431 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2433 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2434 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2436 bnNewBlock.SetCompact(pblock->nBits);
2439 if (pblock->IsProofOfStake())
2440 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2442 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2444 if (bnNewBlock > bnRequired)
2447 pfrom->Misbehaving(100);
2448 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2452 // ppcoin: ask for pending sync-checkpoint if any
2453 if (!IsInitialBlockDownload())
2454 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2456 // If don't already have its previous block, shunt it off to holding area until we get it
2457 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2459 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2460 CBlock* pblock2 = new CBlock(*pblock);
2461 // ppcoin: check proof-of-stake
2462 if (pblock2->IsProofOfStake())
2464 // Limited duplicity on stake: prevents block flood attack
2465 // Duplicate stake allowed only when there is orphan child block
2466 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2467 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());
2469 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2471 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2472 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2474 // Ask this guy to fill in what we're missing
2477 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2478 // ppcoin: getblocks may not obtain the ancestor block rejected
2479 // earlier by duplicate-stake check so we ask for it again directly
2480 if (!IsInitialBlockDownload())
2481 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2487 if (!pblock->AcceptBlock())
2488 return error("ProcessBlock() : AcceptBlock FAILED");
2490 // Recursively process any orphan blocks that depended on this one
2491 vector<uint256> vWorkQueue;
2492 vWorkQueue.push_back(hash);
2493 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2495 uint256 hashPrev = vWorkQueue[i];
2496 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2497 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2500 CBlock* pblockOrphan = (*mi).second;
2501 if (pblockOrphan->AcceptBlock())
2502 vWorkQueue.push_back(pblockOrphan->GetHash());
2503 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2504 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2505 delete pblockOrphan;
2507 mapOrphanBlocksByPrev.erase(hashPrev);
2510 printf("ProcessBlock: ACCEPTED\n");
2512 // ppcoin: if responsible for sync-checkpoint send it
2513 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2514 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2519 // novacoin: attempt to generate suitable proof-of-stake
2520 bool CBlock::SignBlock(CWallet& wallet)
2522 // if we are trying to sign
2523 // something except proof-of-stake block template
2524 if (!vtx[0].vout[0].IsEmpty())
2527 // if we are trying to sign
2528 // a complete proof-of-stake block
2529 if (IsProofOfStake())
2532 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2535 CTransaction txCoinStake;
2536 int64 nSearchTime = txCoinStake.nTime; // search to current time
2538 if (nSearchTime > nLastCoinStakeSearchTime)
2540 if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2542 if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2544 // make sure coinstake would meet timestamp protocol
2545 // as it would be the same as the block timestamp
2546 vtx[0].nTime = nTime = txCoinStake.nTime;
2547 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2548 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2550 // we have to make sure that we have no future timestamps in
2551 // our transactions set
2552 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2553 if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2555 vtx.insert(vtx.begin() + 1, txCoinStake);
2556 hashMerkleRoot = BuildMerkleTree();
2558 // append a signature to our block
2559 return key.Sign(GetHash(), vchBlockSig);
2562 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2563 nLastCoinStakeSearchTime = nSearchTime;
2569 // ppcoin: check block signature
2570 bool CBlock::CheckBlockSignature(bool fProofOfStake) const
2572 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2573 return vchBlockSig.empty();
2575 vector<valtype> vSolutions;
2576 txnouttype whichType;
2580 const CTxOut& txout = vtx[1].vout[1];
2582 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2584 if (whichType == TX_PUBKEY)
2586 valtype& vchPubKey = vSolutions[0];
2588 if (!key.SetPubKey(vchPubKey))
2590 if (vchBlockSig.empty())
2592 return key.Verify(GetHash(), vchBlockSig);
2597 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2599 const CTxOut& txout = vtx[0].vout[i];
2601 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2604 if (whichType == TX_PUBKEY)
2607 valtype& vchPubKey = vSolutions[0];
2609 if (!key.SetPubKey(vchPubKey))
2611 if (vchBlockSig.empty())
2613 if(!key.Verify(GetHash(), vchBlockSig))
2623 bool CheckDiskSpace(uint64 nAdditionalBytes)
2625 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2627 // Check for nMinDiskSpace bytes (currently 50MB)
2628 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2631 string strMessage = _("Warning: Disk space is low!");
2632 strMiscWarning = strMessage;
2633 printf("*** %s\n", strMessage.c_str());
2634 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2642 CCriticalSection cs_LastBlockFile;
2643 CBlockFileInfo infoLastBlockFile;
2644 int nLastBlockFile = 0;
2646 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2650 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2651 boost::filesystem::create_directories(path.parent_path());
2652 FILE* file = fopen(path.string().c_str(), "rb+");
2653 if (!file && !fReadOnly)
2654 file = fopen(path.string().c_str(), "wb+");
2656 printf("Unable to open file %s\n", path.string().c_str());
2660 if (fseek(file, pos.nPos, SEEK_SET)) {
2661 printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2669 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2670 return OpenDiskFile(pos, "blk", fReadOnly);
2673 FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2674 return OpenDiskFile(pos, "rev", fReadOnly);
2677 bool LoadBlockIndex(bool fAllowNew)
2679 CBigNum bnTrustedModulus;
2683 pchMessageStart[0] = 0xcd;
2684 pchMessageStart[1] = 0xf2;
2685 pchMessageStart[2] = 0xc0;
2686 pchMessageStart[3] = 0xef;
2688 bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
2689 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2690 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2691 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2692 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2693 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2697 bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
2700 // Set up the Zerocoin Params object
2701 ZCParams = new libzerocoin::Params(bnTrustedModulus);
2706 CChainDB chaindb("cr");
2707 if (!LoadBlockIndex(chaindb))
2712 // Init with genesis block
2714 if (mapBlockIndex.empty())
2723 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2724 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2725 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2727 // vMerkleTree: 4cb33b3b6a
2731 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2732 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2733 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2735 // vMerkleTree: 4cb33b3b6a
2737 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2739 txNew.nTime = 1360105017;
2740 txNew.vin.resize(1);
2741 txNew.vout.resize(1);
2742 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2743 txNew.vout[0].SetEmpty();
2745 block.vtx.push_back(txNew);
2746 block.hashPrevBlock = 0;
2747 block.hashMerkleRoot = block.BuildMerkleTree();
2749 block.nTime = 1360105017;
2750 block.nBits = bnProofOfWorkLimit.GetCompact();
2751 block.nNonce = !fTestNet ? 1575379 : 46534;
2754 uint256 hash = block.GetHash();
2755 printf("%s\n", hash.ToString().c_str());
2756 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2758 assert(hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2759 assert(block.CheckBlock());
2761 // Start new block file
2762 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2763 CDiskBlockPos blockPos;
2766 if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, 0, block.nTime))
2767 return error("AcceptBlock() : FindBlockPos failed");
2769 if (!block.WriteToDisk(blockPos))
2770 return error("LoadBlockIndex() : writing genesis block to disk failed");
2771 if (!block.AddToBlockIndex(blockPos))
2772 return error("LoadBlockIndex() : genesis block not accepted");
2774 // initialize synchronized checkpoint
2775 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2776 return error("LoadBlockIndex() : failed to init sync checkpoint");
2779 string strPubKey = "";
2782 // if checkpoint master key changed must reset sync-checkpoint
2783 if (!chaindb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2785 // write checkpoint master key to db
2787 if (!chaindb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2788 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2789 if (!chaindb.TxnCommit())
2790 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2791 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2792 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2799 void PrintBlockTree()
2801 // pre-compute tree structure
2802 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2803 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2805 CBlockIndex* pindex = (*mi).second;
2806 mapNext[pindex->pprev].push_back(pindex);
2808 //while (rand() % 3 == 0)
2809 // mapNext[pindex->pprev].push_back(pindex);
2812 vector<pair<int, CBlockIndex*> > vStack;
2813 vStack.push_back(make_pair(0, pindexGenesisBlock));
2816 while (!vStack.empty())
2818 int nCol = vStack.back().first;
2819 CBlockIndex* pindex = vStack.back().second;
2822 // print split or gap
2823 if (nCol > nPrevCol)
2825 for (int i = 0; i < nCol-1; i++)
2829 else if (nCol < nPrevCol)
2831 for (int i = 0; i < nCol; i++)
2838 for (int i = 0; i < nCol; i++)
2843 block.ReadFromDisk(pindex);
2844 printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
2846 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2847 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2850 PrintWallets(block);
2852 // put the main time-chain first
2853 vector<CBlockIndex*>& vNext = mapNext[pindex];
2854 for (unsigned int i = 0; i < vNext.size(); i++)
2856 if (vNext[i]->pnext)
2858 swap(vNext[0], vNext[i]);
2864 for (unsigned int i = 0; i < vNext.size(); i++)
2865 vStack.push_back(make_pair(nCol+i, vNext[i]));
2869 bool LoadExternalBlockFile(FILE* fileIn)
2871 int64 nStart = GetTimeMillis();
2877 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2878 unsigned int nPos = 0;
2879 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2881 unsigned char pchData[65536];
2883 fseek(blkdat, nPos, SEEK_SET);
2884 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2887 nPos = (unsigned int)-1;
2890 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2893 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2895 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2898 nPos += ((unsigned char*)nFind - pchData) + 1;
2901 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2902 } while(!fRequestShutdown);
2903 if (nPos == (unsigned int)-1)
2905 fseek(blkdat, nPos, SEEK_SET);
2908 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2912 if (ProcessBlock(NULL,&block))
2920 catch (std::exception &e) {
2921 printf("%s() : Deserialize or I/O error caught during load\n",
2922 __PRETTY_FUNCTION__);
2925 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2929 //////////////////////////////////////////////////////////////////////////////
2934 extern map<uint256, CAlert> mapAlerts;
2935 extern CCriticalSection cs_mapAlerts;
2937 extern string strMintMessage;
2938 extern string strMintWarning;
2940 string GetWarnings(string strFor)
2943 string strStatusBar;
2946 if (GetBoolArg("-testsafemode"))
2949 // ppcoin: wallet lock warning for minting
2950 if (strMintWarning != "")
2953 strStatusBar = strMintWarning;
2956 // Misc warnings like out of disk space and clock is wrong
2957 if (strMiscWarning != "")
2960 strStatusBar = strMiscWarning;
2963 // * Should not enter safe mode for longer invalid chain
2964 // * If sync-checkpoint is too old do not enter safe mode
2965 // * Display warning only in the STRICT mode
2966 if (CheckpointsMode == Checkpoints::STRICT && Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) &&
2967 !fTestNet && !IsInitialBlockDownload())
2970 strStatusBar = _("WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.");
2973 // ppcoin: if detected invalid checkpoint enter safe mode
2974 if (Checkpoints::hashInvalidCheckpoint != 0)
2977 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
2983 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2985 const CAlert& alert = item.second;
2986 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2988 nPriority = alert.nPriority;
2989 strStatusBar = alert.strStatusBar;
2990 if (nPriority > 1000)
2991 strRPC = strStatusBar;
2996 if (strFor == "statusbar")
2997 return strStatusBar;
2998 else if (strFor == "rpc")
3000 assert(!"GetWarnings() : invalid parameter");
3011 //////////////////////////////////////////////////////////////////////////////
3017 bool static AlreadyHave(const CInv& inv)
3023 bool txInMap = false;
3026 txInMap = mempool.exists(inv.hash);
3028 return txInMap || mapOrphanTransactions.count(inv.hash) ||
3029 pcoinsTip->HaveCoins(inv.hash);
3032 return mapBlockIndex.count(inv.hash) ||
3033 mapOrphanBlocks.count(inv.hash);
3035 // Don't know what it is, just say we already got one
3042 // The message start string is designed to be unlikely to occur in normal data.
3043 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3044 // a large 4-byte int at any alignment.
3045 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3047 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3049 static map<CService, CPubKey> mapReuseKey;
3050 RandAddSeedPerfmon();
3052 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3053 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3055 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3059 if (strCommand == "version")
3061 // Each connection can only send one version message
3062 if (pfrom->nVersion != 0)
3064 pfrom->Misbehaving(1);
3072 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3073 if (pfrom->nVersion < MIN_PROTO_VERSION)
3075 // Since February 20, 2012, the protocol is initiated at version 209,
3076 // and earlier versions are no longer supported
3077 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3078 pfrom->fDisconnect = true;
3082 if (pfrom->nVersion == 10300)
3083 pfrom->nVersion = 300;
3085 vRecv >> addrFrom >> nNonce;
3087 vRecv >> pfrom->strSubVer;
3089 vRecv >> pfrom->nStartingHeight;
3091 if (pfrom->fInbound && addrMe.IsRoutable())
3093 pfrom->addrLocal = addrMe;
3097 // Disconnect if we connected to ourself
3098 if (nNonce == nLocalHostNonce && nNonce > 1)
3100 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3101 pfrom->fDisconnect = true;
3105 // record my external IP reported by peer
3106 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3107 addrSeenByPeer = addrMe;
3109 // Be shy and don't send version until we hear
3110 if (pfrom->fInbound)
3111 pfrom->PushVersion();
3113 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3115 AddTimeData(pfrom->addr, nTime);
3118 pfrom->PushMessage("verack");
3119 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3121 if (!pfrom->fInbound)
3123 // Advertise our address
3124 if (!fNoListen && !IsInitialBlockDownload())
3126 CAddress addr = GetLocalAddress(&pfrom->addr);
3127 if (addr.IsRoutable())
3128 pfrom->PushAddress(addr);
3131 // Get recent addresses
3132 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3134 pfrom->PushMessage("getaddr");
3135 pfrom->fGetAddr = true;
3137 addrman.Good(pfrom->addr);
3139 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3141 addrman.Add(addrFrom, addrFrom);
3142 addrman.Good(addrFrom);
3146 // Ask the first connected node for block updates
3147 static int nAskedForBlocks = 0;
3148 if (!pfrom->fClient && !pfrom->fOneShot &&
3149 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3150 (pfrom->nVersion < NOBLKS_VERSION_START ||
3151 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3152 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3155 pfrom->PushGetBlocks(pindexBest, uint256(0));
3161 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3162 item.second.RelayTo(pfrom);
3165 // Relay sync-checkpoint
3167 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3168 if (!Checkpoints::checkpointMessage.IsNull())
3169 Checkpoints::checkpointMessage.RelayTo(pfrom);
3172 pfrom->fSuccessfullyConnected = true;
3174 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());
3176 cPeerBlockCounts.input(pfrom->nStartingHeight);
3178 // ppcoin: ask for pending sync-checkpoint if any
3179 if (!IsInitialBlockDownload())
3180 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3184 else if (pfrom->nVersion == 0)
3186 // Must have a version message before anything else
3187 pfrom->Misbehaving(1);
3192 else if (strCommand == "verack")
3194 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3198 else if (strCommand == "addr")
3200 vector<CAddress> vAddr;
3203 // Don't want addr from older versions unless seeding
3204 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3206 if (vAddr.size() > 1000)
3208 pfrom->Misbehaving(20);
3209 return error("message addr size() = %"PRIszu"", vAddr.size());
3212 // Store the new addresses
3213 vector<CAddress> vAddrOk;
3214 int64 nNow = GetAdjustedTime();
3215 int64 nSince = nNow - 10 * 60;
3216 BOOST_FOREACH(CAddress& addr, vAddr)
3220 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3221 addr.nTime = nNow - 5 * 24 * 60 * 60;
3222 pfrom->AddAddressKnown(addr);
3223 bool fReachable = IsReachable(addr);
3224 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3226 // Relay to a limited number of other nodes
3229 // Use deterministic randomness to send to the same nodes for 24 hours
3230 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3231 static uint256 hashSalt;
3233 hashSalt = GetRandHash();
3234 uint64 hashAddr = addr.GetHash();
3235 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3236 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3237 multimap<uint256, CNode*> mapMix;
3238 BOOST_FOREACH(CNode* pnode, vNodes)
3240 if (pnode->nVersion < CADDR_TIME_VERSION)
3242 unsigned int nPointer;
3243 memcpy(&nPointer, &pnode, sizeof(nPointer));
3244 uint256 hashKey = hashRand ^ nPointer;
3245 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3246 mapMix.insert(make_pair(hashKey, pnode));
3248 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3249 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3250 ((*mi).second)->PushAddress(addr);
3253 // Do not store addresses outside our network
3255 vAddrOk.push_back(addr);
3257 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3258 if (vAddr.size() < 1000)
3259 pfrom->fGetAddr = false;
3260 if (pfrom->fOneShot)
3261 pfrom->fDisconnect = true;
3264 else if (strCommand == "inv")
3268 if (vInv.size() > MAX_INV_SZ)
3270 pfrom->Misbehaving(20);
3271 return error("message inv size() = %"PRIszu"", vInv.size());
3274 // find last block in inv vector
3275 unsigned int nLastBlock = (unsigned int)(-1);
3276 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3277 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3278 nLastBlock = vInv.size() - 1 - nInv;
3282 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3284 const CInv &inv = vInv[nInv];
3288 pfrom->AddInventoryKnown(inv);
3290 bool fAlreadyHave = AlreadyHave(inv);
3292 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3296 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3297 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3298 } else if (nInv == nLastBlock) {
3299 // In case we are on a very long side-chain, it is possible that we already have
3300 // the last block in an inv bundle sent in response to getblocks. Try to detect
3301 // this situation and push another getblocks to continue.
3302 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3304 printf("force request: %s\n", inv.ToString().c_str());
3307 // Track requests for our stuff
3308 Inventory(inv.hash);
3313 else if (strCommand == "getdata")
3317 if (vInv.size() > MAX_INV_SZ)
3319 pfrom->Misbehaving(20);
3320 return error("message getdata size() = %"PRIszu"", vInv.size());
3323 if (fDebugNet || (vInv.size() != 1))
3324 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3326 BOOST_FOREACH(const CInv& inv, vInv)
3330 if (fDebugNet || (vInv.size() == 1))
3331 printf("received getdata for: %s\n", inv.ToString().c_str());
3333 if (inv.type == MSG_BLOCK)
3335 // Send block from disk
3336 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3337 if (mi != mapBlockIndex.end())
3340 block.ReadFromDisk((*mi).second);
3341 pfrom->PushMessage("block", block);
3343 // Trigger them to send a getblocks request for the next batch of inventory
3344 if (inv.hash == pfrom->hashContinue)
3346 // ppcoin: send latest proof-of-work block to allow the
3347 // download node to accept as orphan (proof-of-stake
3348 // block might be rejected by stake connection check)
3350 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3351 pfrom->PushMessage("inv", vInv);
3352 pfrom->hashContinue = 0;
3356 else if (inv.IsKnownType())
3358 // Send stream from relay memory
3359 bool pushed = false;
3362 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3363 if (mi != mapRelay.end()) {
3364 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3368 if (!pushed && inv.type == MSG_TX) {
3370 if (mempool.exists(inv.hash)) {
3371 CTransaction tx = mempool.lookup(inv.hash);
3372 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3375 pfrom->PushMessage("tx", ss);
3380 // Track requests for our stuff
3381 Inventory(inv.hash);
3386 else if (strCommand == "getblocks")
3388 CBlockLocator locator;
3390 vRecv >> locator >> hashStop;
3392 // Find the last block the caller has in the main chain
3393 CBlockIndex* pindex = locator.GetBlockIndex();
3395 // Send the rest of the chain
3397 pindex = pindex->pnext;
3399 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3400 for (; pindex; pindex = pindex->pnext)
3402 if (pindex->GetBlockHash() == hashStop)
3404 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3405 // ppcoin: tell downloading node about the latest block if it's
3406 // without risk being rejected due to stake connection check
3407 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3408 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3411 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3414 // When this block is requested, we'll send an inv that'll make them
3415 // getblocks the next batch of inventory.
3416 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3417 pfrom->hashContinue = pindex->GetBlockHash();
3422 else if (strCommand == "checkpoint")
3424 CSyncCheckpoint checkpoint;
3425 vRecv >> checkpoint;
3427 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3430 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3432 BOOST_FOREACH(CNode* pnode, vNodes)
3433 checkpoint.RelayTo(pnode);
3437 else if (strCommand == "getheaders")
3439 CBlockLocator locator;
3441 vRecv >> locator >> hashStop;
3443 CBlockIndex* pindex = NULL;
3444 if (locator.IsNull())
3446 // If locator is null, return the hashStop block
3447 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3448 if (mi == mapBlockIndex.end())
3450 pindex = (*mi).second;
3454 // Find the last block the caller has in the main chain
3455 pindex = locator.GetBlockIndex();
3457 pindex = pindex->pnext;
3460 vector<CBlock> vHeaders;
3462 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3463 for (; pindex; pindex = pindex->pnext)
3465 vHeaders.push_back(pindex->GetBlockHeader());
3466 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3469 pfrom->PushMessage("headers", vHeaders);
3473 else if (strCommand == "tx")
3475 vector<uint256> vWorkQueue;
3476 vector<uint256> vEraseQueue;
3477 CDataStream vMsg(vRecv);
3481 CInv inv(MSG_TX, tx.GetHash());
3482 pfrom->AddInventoryKnown(inv);
3484 bool fMissingInputs = false;
3485 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
3487 SyncWithWallets(tx, NULL, true);
3488 RelayTransaction(tx, inv.hash);
3489 mapAlreadyAskedFor.erase(inv);
3490 vWorkQueue.push_back(inv.hash);
3491 vEraseQueue.push_back(inv.hash);
3493 // Recursively process any orphan transactions that depended on this one
3494 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3496 uint256 hashPrev = vWorkQueue[i];
3497 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3498 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3501 const uint256& orphanTxHash = *mi;
3502 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3503 bool fMissingInputs2 = false;
3505 if (orphanTx.AcceptToMemoryPool(true, &fMissingInputs2))
3507 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3508 SyncWithWallets(tx, NULL, true);
3509 RelayTransaction(orphanTx, orphanTxHash);
3510 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3511 vWorkQueue.push_back(orphanTxHash);
3512 vEraseQueue.push_back(orphanTxHash);
3514 else if (!fMissingInputs2)
3517 vEraseQueue.push_back(orphanTxHash);
3518 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3523 BOOST_FOREACH(uint256 hash, vEraseQueue)
3524 EraseOrphanTx(hash);
3526 else if (fMissingInputs)
3530 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3531 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3533 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3535 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3539 else if (strCommand == "block")
3543 uint256 hashBlock = block.GetHash();
3545 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3548 CInv inv(MSG_BLOCK, hashBlock);
3549 pfrom->AddInventoryKnown(inv);
3551 if (ProcessBlock(pfrom, &block))
3552 mapAlreadyAskedFor.erase(inv);
3553 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3557 else if (strCommand == "getaddr")
3559 // Don't return addresses older than nCutOff timestamp
3560 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3561 pfrom->vAddrToSend.clear();
3562 vector<CAddress> vAddr = addrman.GetAddr();
3563 BOOST_FOREACH(const CAddress &addr, vAddr)
3564 if(addr.nTime > nCutOff)
3565 pfrom->PushAddress(addr);
3569 else if (strCommand == "mempool")
3571 std::vector<uint256> vtxid;
3572 mempool.queryHashes(vtxid);
3574 for (unsigned int i = 0; i < vtxid.size(); i++) {
3575 CInv inv(MSG_TX, vtxid[i]);
3576 vInv.push_back(inv);
3577 if (i == (MAX_INV_SZ - 1))
3580 if (vInv.size() > 0)
3581 pfrom->PushMessage("inv", vInv);
3585 else if (strCommand == "checkorder")
3590 if (!GetBoolArg("-allowreceivebyip"))
3592 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3599 /// we have a chance to check the order here
3601 // Keep giving the same key to the same ip until they use it
3602 if (!mapReuseKey.count(pfrom->addr))
3603 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3605 // Send back approval of order and pubkey to use
3606 CScript scriptPubKey;
3607 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3608 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3612 else if (strCommand == "reply")
3617 CRequestTracker tracker;
3619 LOCK(pfrom->cs_mapRequests);
3620 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3621 if (mi != pfrom->mapRequests.end())
3623 tracker = (*mi).second;
3624 pfrom->mapRequests.erase(mi);
3627 if (!tracker.IsNull())
3628 tracker.fn(tracker.param1, vRecv);
3632 else if (strCommand == "ping")
3634 if (pfrom->nVersion > BIP0031_VERSION)
3638 // Echo the message back with the nonce. This allows for two useful features:
3640 // 1) A remote node can quickly check if the connection is operational
3641 // 2) Remote nodes can measure the latency of the network thread. If this node
3642 // is overloaded it won't respond to pings quickly and the remote node can
3643 // avoid sending us more work, like chain download requests.
3645 // The nonce stops the remote getting confused between different pings: without
3646 // it, if the remote node sends a ping once per second and this node takes 5
3647 // seconds to respond to each, the 5th ping the remote sends would appear to
3648 // return very quickly.
3649 pfrom->PushMessage("pong", nonce);
3654 else if (strCommand == "alert")
3659 uint256 alertHash = alert.GetHash();
3660 if (pfrom->setKnown.count(alertHash) == 0)
3662 if (alert.ProcessAlert())
3665 pfrom->setKnown.insert(alertHash);
3668 BOOST_FOREACH(CNode* pnode, vNodes)
3669 alert.RelayTo(pnode);
3673 // Small DoS penalty so peers that send us lots of
3674 // duplicate/expired/invalid-signature/whatever alerts
3675 // eventually get banned.
3676 // This isn't a Misbehaving(100) (immediate ban) because the
3677 // peer might be an older or different implementation with
3678 // a different signature key, etc.
3679 pfrom->Misbehaving(10);
3687 // Ignore unknown commands for extensibility
3691 // Update the last seen time for this node's address
3692 if (pfrom->fNetworkNode)
3693 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3694 AddressCurrentlyConnected(pfrom->addr);
3700 bool ProcessMessages(CNode* pfrom)
3702 CDataStream& vRecv = pfrom->vRecv;
3706 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3710 // (4) message start
3719 // Don't bother if send buffer is too full to respond anyway
3720 if (pfrom->vSend.size() >= SendBufferSize())
3723 // Scan for message start
3724 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3725 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3726 if (vRecv.end() - pstart < nHeaderSize)
3728 if ((int)vRecv.size() > nHeaderSize)
3730 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3731 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3735 if (pstart - vRecv.begin() > 0)
3736 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3737 vRecv.erase(vRecv.begin(), pstart);
3740 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3745 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3748 string strCommand = hdr.GetCommand();
3751 unsigned int nMessageSize = hdr.nMessageSize;
3752 if (nMessageSize > MAX_SIZE)
3754 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3757 if (nMessageSize > vRecv.size())
3759 // Rewind and wait for rest of message
3760 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3765 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3766 unsigned int nChecksum = 0;
3767 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3768 if (nChecksum != hdr.nChecksum)
3770 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3771 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3775 // Copy message to its own buffer
3776 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3777 vRecv.ignore(nMessageSize);
3785 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3790 catch (std::ios_base::failure& e)
3792 if (strstr(e.what(), "end of data"))
3794 // Allow exceptions from under-length message on vRecv
3795 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());
3797 else if (strstr(e.what(), "size too large"))
3799 // Allow exceptions from over-long size
3800 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3804 PrintExceptionContinue(&e, "ProcessMessages()");
3807 catch (std::exception& e) {
3808 PrintExceptionContinue(&e, "ProcessMessages()");
3810 PrintExceptionContinue(NULL, "ProcessMessages()");
3814 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3822 bool SendMessages(CNode* pto, bool fSendTrickle)
3824 TRY_LOCK(cs_main, lockMain);
3826 // Don't send anything until we get their version message
3827 if (pto->nVersion == 0)
3830 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3832 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3834 if (pto->nVersion > BIP0031_VERSION)
3835 pto->PushMessage("ping", nonce);
3837 pto->PushMessage("ping");
3840 // Resend wallet transactions that haven't gotten in a block yet
3841 ResendWalletTransactions();
3843 // Address refresh broadcast
3844 static int64 nLastRebroadcast;
3845 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3849 BOOST_FOREACH(CNode* pnode, vNodes)
3851 // Periodically clear setAddrKnown to allow refresh broadcasts
3852 if (nLastRebroadcast)
3853 pnode->setAddrKnown.clear();
3855 // Rebroadcast our address
3858 CAddress addr = GetLocalAddress(&pnode->addr);
3859 if (addr.IsRoutable())
3860 pnode->PushAddress(addr);
3864 nLastRebroadcast = GetTime();
3872 vector<CAddress> vAddr;
3873 vAddr.reserve(pto->vAddrToSend.size());
3874 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3876 // returns true if wasn't already contained in the set
3877 if (pto->setAddrKnown.insert(addr).second)
3879 vAddr.push_back(addr);
3880 // receiver rejects addr messages larger than 1000
3881 if (vAddr.size() >= 1000)
3883 pto->PushMessage("addr", vAddr);
3888 pto->vAddrToSend.clear();
3890 pto->PushMessage("addr", vAddr);
3895 // Message: inventory
3898 vector<CInv> vInvWait;
3900 LOCK(pto->cs_inventory);
3901 vInv.reserve(pto->vInventoryToSend.size());
3902 vInvWait.reserve(pto->vInventoryToSend.size());
3903 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3905 if (pto->setInventoryKnown.count(inv))
3908 // trickle out tx inv to protect privacy
3909 if (inv.type == MSG_TX && !fSendTrickle)
3911 // 1/4 of tx invs blast to all immediately
3912 static uint256 hashSalt;
3914 hashSalt = GetRandHash();
3915 uint256 hashRand = inv.hash ^ hashSalt;
3916 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3917 bool fTrickleWait = ((hashRand & 3) != 0);
3919 // always trickle our own transactions
3923 if (GetTransaction(inv.hash, wtx))
3925 fTrickleWait = true;
3930 vInvWait.push_back(inv);
3935 // returns true if wasn't already contained in the set
3936 if (pto->setInventoryKnown.insert(inv).second)
3938 vInv.push_back(inv);
3939 if (vInv.size() >= 1000)
3941 pto->PushMessage("inv", vInv);
3946 pto->vInventoryToSend = vInvWait;
3949 pto->PushMessage("inv", vInv);
3955 vector<CInv> vGetData;
3956 int64 nNow = GetTime() * 1000000;
3957 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3959 const CInv& inv = (*pto->mapAskFor.begin()).second;
3960 if (!AlreadyHave(inv))
3963 printf("sending getdata: %s\n", inv.ToString().c_str());
3964 vGetData.push_back(inv);
3965 if (vGetData.size() >= 1000)
3967 pto->PushMessage("getdata", vGetData);
3970 mapAlreadyAskedFor[inv] = nNow;
3972 pto->mapAskFor.erase(pto->mapAskFor.begin());
3974 if (!vGetData.empty())
3975 pto->PushMessage("getdata", vGetData);
3981 // Amount compression:
3982 // * If the amount is 0, output 0
3983 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
3984 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
3985 // * call the result n
3986 // * output 1 + 10*(9*n + d - 1) + e
3987 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
3988 // (this is decodable, as d is in [1-9] and e is in [0-9])
3990 uint64 CTxOutCompressor::CompressAmount(uint64 n)
3995 while (((n % 10) == 0) && e < 9) {
4001 assert(d >= 1 && d <= 9);
4003 return 1 + (n*9 + d - 1)*10 + e;
4005 return 1 + (n - 1)*10 + 9;
4009 uint64 CTxOutCompressor::DecompressAmount(uint64 x)
4011 // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
4015 // x = 10*(9*n + d - 1) + e
4021 int d = (x % 9) + 1;