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; }
198 CCoinsViewBacked::CCoinsViewBacked(CCoinsView &viewIn) : base(&viewIn) { }
199 bool CCoinsViewBacked::GetCoins(uint256 txid, CCoins &coins) { return base->GetCoins(txid, coins); }
200 bool CCoinsViewBacked::SetCoins(uint256 txid, const CCoins &coins) { return base->SetCoins(txid, coins); }
201 bool CCoinsViewBacked::HaveCoins(uint256 txid) { return base->HaveCoins(txid); }
202 CBlockIndex *CCoinsViewBacked::GetBestBlock() { return base->GetBestBlock(); }
203 bool CCoinsViewBacked::SetBestBlock(CBlockIndex *pindex) { return base->SetBestBlock(pindex); }
204 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
206 CCoinsViewDB::CCoinsViewDB(CCoinsDB &dbIn) : db(dbIn) {}
207 bool CCoinsViewDB::GetCoins(uint256 txid, CCoins &coins) { return db.ReadCoins(txid, coins); }
208 bool CCoinsViewDB::SetCoins(uint256 txid, const CCoins &coins) { return db.WriteCoins(txid, coins); }
209 bool CCoinsViewDB::HaveCoins(uint256 txid) { return db.HaveCoins(txid); }
210 CBlockIndex *CCoinsViewDB::GetBestBlock() { return pindexBest; }
211 bool CCoinsViewDB::SetBestBlock(CBlockIndex *pindex) { return db.WriteHashBestChain(pindex->GetBlockHash()); }
213 CCoinsViewCache::CCoinsViewCache(CCoinsView &baseIn, bool fDummy) : CCoinsViewBacked(baseIn), pindexTip(NULL) { }
215 bool CCoinsViewCache::GetCoins(uint256 txid, CCoins &coins) {
216 if (cacheCoins.count(txid)) {
217 coins = cacheCoins[txid];
220 if (base->GetCoins(txid, coins)) {
221 cacheCoins[txid] = coins;
227 bool CCoinsViewCache::SetCoins(uint256 txid, const CCoins &coins) {
228 cacheCoins[txid] = coins;
232 bool CCoinsViewCache::HaveCoins(uint256 txid) {
233 return cacheCoins.count(txid) || base->HaveCoins(txid);
236 CBlockIndex *CCoinsViewCache::GetBestBlock() {
237 if (pindexTip == NULL)
238 pindexTip = base->GetBestBlock();
242 bool CCoinsViewCache::SetBestBlock(CBlockIndex *pindex) {
247 bool CCoinsViewCache::Flush() {
248 for (std::map<uint256,CCoins>::iterator it = cacheCoins.begin(); it != cacheCoins.end(); it++) {
249 if (!base->SetCoins(it->first, it->second))
252 if (!base->SetBestBlock(pindexTip))
259 /** CCoinsView that brings transactions from a memorypool into view.
260 It does not check for spendings by memory pool transactions. */
261 CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
263 bool CCoinsViewMemPool::GetCoins(uint256 txid, CCoins &coins) {
264 if (base->GetCoins(txid, coins))
266 if (mempool.exists(txid)) {
267 const CTransaction &tx = mempool.lookup(txid);
268 coins = CCoins(tx, MEMPOOL_HEIGHT, -1);
274 bool CCoinsViewMemPool::HaveCoins(uint256 txid) {
275 return mempool.exists(txid) || base->HaveCoins(txid);
279 //////////////////////////////////////////////////////////////////////////////
281 // mapOrphanTransactions
284 bool AddOrphanTx(const CTransaction& tx)
286 uint256 hash = tx.GetHash();
287 if (mapOrphanTransactions.count(hash))
290 // Ignore big transactions, to avoid a
291 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
292 // large transaction with a missing parent then we assume
293 // it will rebroadcast it later, after the parent transaction(s)
294 // have been mined or received.
295 // 10,000 orphans, each of which is at most 5,000 bytes big is
296 // at most 500 megabytes of orphans:
298 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
302 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
306 mapOrphanTransactions[hash] = tx;
307 BOOST_FOREACH(const CTxIn& txin, tx.vin)
308 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
310 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
311 mapOrphanTransactions.size());
315 void static EraseOrphanTx(uint256 hash)
317 if (!mapOrphanTransactions.count(hash))
319 const CTransaction& tx = mapOrphanTransactions[hash];
320 BOOST_FOREACH(const CTxIn& txin, tx.vin)
322 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
323 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
324 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
326 mapOrphanTransactions.erase(hash);
329 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
331 unsigned int nEvicted = 0;
332 while (mapOrphanTransactions.size() > nMaxOrphans)
334 // Evict a random orphan:
335 uint256 randomhash = GetRandHash();
336 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
337 if (it == mapOrphanTransactions.end())
338 it = mapOrphanTransactions.begin();
339 EraseOrphanTx(it->first);
351 //////////////////////////////////////////////////////////////////////////////
356 bool CTransaction::IsStandard() const
358 if (nVersion > CTransaction::CURRENT_VERSION)
361 BOOST_FOREACH(const CTxIn& txin, vin)
363 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
364 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
365 // ~65-byte public keys, plus a few script ops.
366 if (txin.scriptSig.size() > 500)
368 if (!txin.scriptSig.IsPushOnly())
371 BOOST_FOREACH(const CTxOut& txout, vout) {
372 if (!::IsStandard(txout.scriptPubKey))
374 if (txout.nValue == 0)
381 // Check transaction inputs, and make sure any
382 // pay-to-script-hash transactions are evaluating IsStandard scripts
384 // Why bother? To avoid denial-of-service attacks; an attacker
385 // can submit a standard HASH... OP_EQUAL transaction,
386 // which will get accepted into blocks. The redemption
387 // script can be anything; an attacker could use a very
388 // expensive-to-check-upon-redemption script like:
389 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
391 bool CTransaction::AreInputsStandard(CCoinsView& mapInputs) const
394 return true; // Coinbases don't use vin normally
396 for (unsigned int i = 0; i < vin.size(); i++)
398 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
400 vector<vector<unsigned char> > vSolutions;
401 txnouttype whichType;
402 // get the scriptPubKey corresponding to this input:
403 const CScript& prevScript = prev.scriptPubKey;
404 if (!Solver(prevScript, whichType, vSolutions))
406 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
407 if (nArgsExpected < 0)
410 // Transactions with extra stuff in their scriptSigs are
411 // non-standard. Note that this EvalScript() call will
412 // be quick, because if there are any operations
413 // beside "push data" in the scriptSig the
414 // IsStandard() call returns false
415 vector<vector<unsigned char> > stack;
416 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
419 if (whichType == TX_SCRIPTHASH)
423 CScript subscript(stack.back().begin(), stack.back().end());
424 vector<vector<unsigned char> > vSolutions2;
425 txnouttype whichType2;
426 if (!Solver(subscript, whichType2, vSolutions2))
428 if (whichType2 == TX_SCRIPTHASH)
432 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
435 nArgsExpected += tmpExpected;
438 if (stack.size() != (unsigned int)nArgsExpected)
446 CTransaction::GetLegacySigOpCount() const
448 unsigned int nSigOps = 0;
449 BOOST_FOREACH(const CTxIn& txin, vin)
451 nSigOps += txin.scriptSig.GetSigOpCount(false);
453 BOOST_FOREACH(const CTxOut& txout, vout)
455 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
461 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
472 if (pblock == NULL) {
473 CCoinsDB coinsdb("r");
475 if (coinsdb.ReadCoins(GetHash(), coins)) {
476 CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
478 if (!blockTmp.ReadFromDisk(pindex))
486 // Update the tx's hashBlock
487 hashBlock = pblock->GetHash();
489 // Locate the transaction
490 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
491 if (pblock->vtx[nIndex] == *(CTransaction*)this)
493 if (nIndex == (int)pblock->vtx.size())
495 vMerkleBranch.clear();
497 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
501 // Fill in merkle branch
502 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
506 // Is the tx in a block that's in the main chain
507 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
508 if (mi == mapBlockIndex.end())
510 CBlockIndex* pindex = (*mi).second;
511 if (!pindex || !pindex->IsInMainChain())
514 return pindexBest->nHeight - pindex->nHeight + 1;
517 bool CTransaction::CheckTransaction() const
519 // Basic checks that don't depend on any context
521 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
523 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
525 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
526 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
528 // Check for negative or overflow output values
530 for (unsigned int i = 0; i < vout.size(); i++)
532 const CTxOut& txout = vout[i];
533 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
534 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
536 // NovaCoin: enforce minimum output amount for user transactions until 1 May 2014 04:00:00 GMT
537 if (!fTestNet && !IsCoinBase() && !txout.IsEmpty() && nTime < OUTPUT_SWITCH_TIME && txout.nValue < MIN_TXOUT_AMOUNT)
538 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
540 if (txout.nValue > MAX_MONEY)
541 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
542 nValueOut += txout.nValue;
543 if (!MoneyRange(nValueOut))
544 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
547 // Check for duplicate inputs
548 set<COutPoint> vInOutPoints;
549 BOOST_FOREACH(const CTxIn& txin, vin)
551 if (vInOutPoints.count(txin.prevout))
553 vInOutPoints.insert(txin.prevout);
558 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
559 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
563 BOOST_FOREACH(const CTxIn& txin, vin)
564 if (txin.prevout.IsNull())
565 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
571 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
572 enum GetMinFee_mode mode, unsigned int nBytes) const
574 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
575 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
577 unsigned int nNewBlockSize = nBlockSize + nBytes;
578 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
580 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
581 if (nMinFee < nBaseFee)
583 BOOST_FOREACH(const CTxOut& txout, vout)
584 if (txout.nValue < CENT)
588 // Raise the price as the block approaches full
589 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
591 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
593 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
596 if (!MoneyRange(nMinFee))
601 void CTxMemPool::pruneSpent(const uint256 &hashTx, CCoins &coins)
605 std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
607 // iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
608 while (it != mapNextTx.end() && it->first.hash == hashTx) {
609 coins.Spend(it->first.n); // and remove those outputs from coins
614 bool CTxMemPool::accept(CCoinsDB& coinsdb, CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs)
617 *pfMissingInputs = false;
619 if (!tx.CheckTransaction())
620 return error("CTxMemPool::accept() : CheckTransaction failed");
622 // Coinbase is only valid in a block, not as a loose transaction
624 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
626 // Coinstake is also only valid in a block, not as a loose transaction
627 if (tx.IsCoinStake())
628 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
630 // To help v0.1.5 clients who would see it as a negative number
631 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
632 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
634 // Rather not work on nonstandard transactions (unless -testnet)
635 if (!fTestNet && !tx.IsStandard())
636 return error("CTxMemPool::accept() : nonstandard transaction type");
638 // is it already in the memory pool?
639 uint256 hash = tx.GetHash();
642 if (mapTx.count(hash))
646 // Check for conflicts with in-memory transactions
647 CTransaction* ptxOld = NULL;
648 for (unsigned int i = 0; i < tx.vin.size(); i++)
650 COutPoint outpoint = tx.vin[i].prevout;
651 if (mapNextTx.count(outpoint))
653 // Disable replacement feature for now
656 // Allow replacing with a newer version of the same transaction
659 ptxOld = mapNextTx[outpoint].ptx;
660 if (ptxOld->IsFinal())
662 if (!tx.IsNewerThan(*ptxOld))
664 for (unsigned int i = 0; i < tx.vin.size(); i++)
666 COutPoint outpoint = tx.vin[i].prevout;
667 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
676 CCoinsViewDB viewDB(coinsdb);
677 CCoinsViewMemPool viewMemPool(viewDB, mempool);
678 CCoinsViewCache view(viewMemPool);
680 // do we already have it?
681 if (view.HaveCoins(hash))
684 // do all inputs exist?
685 BOOST_FOREACH(const CTxIn txin, tx.vin) {
686 if (!view.HaveCoins(txin.prevout.hash)) {
688 *pfMissingInputs = true;
693 // Check for non-standard pay-to-script-hash in inputs
694 if (!tx.AreInputsStandard(view) && !fTestNet)
695 return error("CTxMemPool::accept() : nonstandard transaction input");
697 // Note: if you modify this code to accept non-standard transactions, then
698 // you should add code here to check that the transaction does a
699 // reasonable number of ECDSA signature verifications.
701 int64 nFees = tx.GetValueIn(view)-tx.GetValueOut();
702 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
704 // Don't accept it if it can't get into a block
705 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY, nSize);
706 if (nFees < txMinFee)
707 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
708 hash.ToString().c_str(),
712 // Continuously rate-limit free transactions
713 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
714 // be annoying or make others' transactions take longer to confirm.
715 if (nFees < MIN_RELAY_TX_FEE)
717 static CCriticalSection cs;
718 static double dFreeCount;
719 static int64 nLastTime;
720 int64 nNow = GetTime();
724 // Use an exponentially decaying ~10-minute window:
725 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
727 // -limitfreerelay unit is thousand-bytes-per-minute
728 // At default rate it would take over a month to fill 1GB
729 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
730 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
732 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
737 // Check against previous transactions
738 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
739 if (!tx.CheckInputs(view, CS_ALWAYS, true, false))
741 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
745 // Store transaction in memory
750 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
753 addUnchecked(hash, tx);
756 ///// are we sure this is ok when loading transactions or restoring block txes
757 // If updated, erase old tx from wallet
759 EraseFromWallets(ptxOld->GetHash());
761 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
762 hash.ToString().substr(0,10).c_str(),
767 bool CTransaction::AcceptToMemoryPool(CCoinsDB& coinsdb, bool fCheckInputs, bool* pfMissingInputs)
769 return mempool.accept(coinsdb, *this, fCheckInputs, pfMissingInputs);
772 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
774 // Add to memory pool without checking anything. Don't call this directly,
775 // call CTxMemPool::accept to properly check the transaction first.
778 for (unsigned int i = 0; i < tx.vin.size(); i++)
779 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
780 nTransactionsUpdated++;
786 bool CTxMemPool::remove(CTransaction &tx)
788 // Remove transaction from memory pool
791 uint256 hash = tx.GetHash();
792 if (mapTx.count(hash))
794 BOOST_FOREACH(const CTxIn& txin, tx.vin)
795 mapNextTx.erase(txin.prevout);
797 nTransactionsUpdated++;
803 void CTxMemPool::clear()
808 ++nTransactionsUpdated;
811 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
816 vtxid.reserve(mapTx.size());
817 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
818 vtxid.push_back((*mi).first);
824 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
826 if (hashBlock == 0 || nIndex == -1)
829 // Find the block it claims to be in
830 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
831 if (mi == mapBlockIndex.end())
833 CBlockIndex* pindex = (*mi).second;
834 if (!pindex || !pindex->IsInMainChain())
837 // Make sure the merkle branch connects to this block
838 if (!fMerkleVerified)
840 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
842 fMerkleVerified = true;
846 return pindexBest->nHeight - pindex->nHeight + 1;
849 int CMerkleTx::GetBlocksToMaturity() const
851 if (!(IsCoinBase() || IsCoinStake()))
853 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
857 bool CMerkleTx::AcceptToMemoryPool(CCoinsDB& coinsdb, bool fCheckInputs)
861 if (!IsInMainChain() && !ClientCheckInputs())
863 return CTransaction::AcceptToMemoryPool(coinsdb, false);
867 return CTransaction::AcceptToMemoryPool(coinsdb, fCheckInputs);
871 bool CMerkleTx::AcceptToMemoryPool()
873 CCoinsDB coinsdb("r");
874 return AcceptToMemoryPool(coinsdb);
877 bool CWalletTx::AcceptWalletTransaction(CCoinsDB& coinsdb, bool fCheckInputs)
882 // Add previous supporting transactions first
883 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
885 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
887 uint256 hash = tx.GetHash();
888 if (!mempool.exists(hash) && !coinsdb.HaveCoins(hash))
889 tx.AcceptToMemoryPool(coinsdb, fCheckInputs);
892 return AcceptToMemoryPool(coinsdb, fCheckInputs);
897 bool CWalletTx::AcceptWalletTransaction()
899 CCoinsDB coinsdb("r");
900 return AcceptWalletTransaction(coinsdb);
903 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
904 bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
906 CBlockIndex *pindexSlow = NULL;
911 if (mempool.exists(hash))
913 txOut = mempool.lookup(hash);
918 if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
921 CCoinsDB coindb("r");
922 CCoinsViewDB view(coindb);
924 if (view.GetCoins(hash, coins))
925 nHeight = coins.nHeight;
928 pindexSlow = FindBlockByHeight(nHeight);
934 if (block.ReadFromDisk(pindexSlow)) {
935 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
936 if (tx.GetHash() == hash) {
938 hashBlock = pindexSlow->GetBlockHash();
949 //////////////////////////////////////////////////////////////////////////////
951 // CBlock and CBlockIndex
954 static CBlockIndex* pblockindexFBBHLast;
955 CBlockIndex* FindBlockByHeight(int nHeight)
957 CBlockIndex *pblockindex;
958 if (nHeight < nBestHeight / 2)
959 pblockindex = pindexGenesisBlock;
961 pblockindex = pindexBest;
962 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
963 pblockindex = pblockindexFBBHLast;
964 while (pblockindex->nHeight > nHeight)
965 pblockindex = pblockindex->pprev;
966 while (pblockindex->nHeight < nHeight)
967 pblockindex = pblockindex->pnext;
968 pblockindexFBBHLast = pblockindex;
972 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
974 if (!fReadTransactions)
976 *this = pindex->GetBlockHeader();
979 if (!ReadFromDisk(pindex->GetBlockPos(), fReadTransactions))
981 if (GetHash() != pindex->GetBlockHash())
982 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
986 uint256 static GetOrphanRoot(const CBlock* pblock)
988 // Work back to the first block in the orphan chain
989 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
990 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
991 return pblock->GetHash();
994 // ppcoin: find block wanted by given orphan block
995 uint256 WantedByOrphan(const CBlock* pblockOrphan)
997 // Work back to the first block in the orphan chain
998 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
999 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
1000 return pblockOrphan->hashPrevBlock;
1003 // select stake target limit according to hard-coded conditions
1004 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1006 if(fTestNet) // separate proof of stake target limit for testnet
1007 return bnProofOfStakeLimit;
1008 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1009 return bnProofOfStakeLimit;
1010 if(nHeight + 1 > 15000) // 24 bits since block 15000
1011 return bnProofOfStakeLegacyLimit;
1012 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1013 return bnProofOfStakeHardLimit;
1015 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1018 // miner's coin base reward based on nBits
1019 int64 GetProofOfWorkReward(unsigned int nBits)
1021 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1024 bnTarget.SetCompact(nBits);
1025 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1026 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1028 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1029 // A reasonably continuous curve is used to avoid shock to market
1030 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1032 // Human readable form:
1034 // nSubsidy = 100 / (diff ^ 1/6)
1035 CBigNum bnLowerBound = CENT;
1036 CBigNum bnUpperBound = bnSubsidyLimit;
1037 while (bnLowerBound + CENT <= bnUpperBound)
1039 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1040 if (fDebug && GetBoolArg("-printcreation"))
1041 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1042 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1043 bnUpperBound = bnMidValue;
1045 bnLowerBound = bnMidValue;
1048 int64 nSubsidy = bnUpperBound.getuint64();
1050 nSubsidy = (nSubsidy / CENT) * CENT;
1051 if (fDebug && GetBoolArg("-printcreation"))
1052 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1054 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
1057 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1058 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
1060 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1062 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1064 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1066 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1068 bnTarget.SetCompact(nBits);
1069 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1070 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1072 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1074 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1075 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1076 bnMidPart, bnRewardPart;
1078 while (bnLowerBound + CENT <= bnUpperBound)
1080 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1081 if (fDebug && GetBoolArg("-printcreation"))
1082 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1084 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1087 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1089 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1091 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1094 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1095 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1100 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1102 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1104 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1107 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1108 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1111 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1112 bnUpperBound = bnMidValue;
1114 bnLowerBound = bnMidValue;
1117 nRewardCoinYear = bnUpperBound.getuint64();
1118 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1122 // Old creation amount per coin-year, 5% fixed stake mint rate
1123 nRewardCoinYear = 5 * CENT;
1127 return nRewardCoinYear;
1129 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1131 // Set reasonable reward limit for large inputs since 20 Oct 2013
1133 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1134 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1136 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1137 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1139 nSubsidy = min(nSubsidy, nSubsidyLimit);
1142 if (fDebug && GetBoolArg("-printcreation"))
1143 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1147 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1149 // get proof of work blocks max spacing according to hard-coded conditions
1150 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1152 if(nTime > TARGETS_SWITCH_TIME)
1153 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1156 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1158 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1162 // maximum nBits value could possible be required nTime after
1164 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1167 bnResult.SetCompact(nBase);
1169 while (nTime > 0 && bnResult < bnTargetLimit)
1171 // Maximum 200% adjustment per day...
1173 nTime -= 24 * 60 * 60;
1175 if (bnResult > bnTargetLimit)
1176 bnResult = bnTargetLimit;
1177 return bnResult.GetCompact();
1181 // minimum amount of work that could possibly be required nTime after
1182 // minimum proof-of-work required was nBase
1184 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1186 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1190 // minimum amount of stake that could possibly be required nTime after
1191 // minimum proof-of-stake required was nBase
1193 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1195 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1199 // ppcoin: find last block index up to pindex
1200 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1202 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1203 pindex = pindex->pprev;
1207 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1209 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1211 if (pindexLast == NULL)
1212 return bnTargetLimit.GetCompact(); // genesis block
1214 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1215 if (pindexPrev->pprev == NULL)
1216 return bnTargetLimit.GetCompact(); // first block
1217 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1218 if (pindexPrevPrev->pprev == NULL)
1219 return bnTargetLimit.GetCompact(); // second block
1221 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1223 // ppcoin: target change every block
1224 // ppcoin: retarget with exponential moving toward target spacing
1226 bnNew.SetCompact(pindexPrev->nBits);
1227 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1228 int64 nInterval = nTargetTimespan / nTargetSpacing;
1229 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1230 bnNew /= ((nInterval + 1) * nTargetSpacing);
1232 if (bnNew > bnTargetLimit)
1233 bnNew = bnTargetLimit;
1235 return bnNew.GetCompact();
1238 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1241 bnTarget.SetCompact(nBits);
1244 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1245 return error("CheckProofOfWork() : nBits below minimum work");
1247 // Check proof of work matches claimed amount
1248 if (hash > bnTarget.getuint256())
1249 return error("CheckProofOfWork() : hash doesn't match nBits");
1254 // Return maximum amount of blocks that other nodes claim to have
1255 int GetNumBlocksOfPeers()
1257 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1260 bool IsInitialBlockDownload()
1262 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1264 static int64 nLastUpdate;
1265 static CBlockIndex* pindexLastBest;
1266 if (pindexBest != pindexLastBest)
1268 pindexLastBest = pindexBest;
1269 nLastUpdate = GetTime();
1271 return (GetTime() - nLastUpdate < 10 &&
1272 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1275 void static InvalidChainFound(CBlockIndex* pindexNew)
1277 if (pindexNew->nChainTrust > nBestInvalidTrust)
1279 nBestInvalidTrust = pindexNew->nChainTrust;
1280 CChainDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1281 uiInterface.NotifyBlocksChanged();
1284 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1285 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1287 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1288 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1289 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1290 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1291 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1292 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1293 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1294 nBestBlockTrust.Get64(),
1295 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1299 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1301 nTime = max(GetBlockTime(), GetAdjustedTime());
1305 CTxOut CTransaction::GetOutputFor(const CTxIn& input, CCoinsView& view)
1308 if (!view.GetCoins(input.prevout.hash, coins))
1309 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1311 if (input.prevout.n >= coins.vout.size())
1312 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range or already spent");
1314 const CTxOut &out = coins.vout[input.prevout.n];
1316 throw std::runtime_error("CTransaction::GetOutputFor() : already spent");
1321 int64 CTransaction::GetValueIn(CCoinsView& inputs) const
1327 for (unsigned int i = 0; i < vin.size(); i++)
1329 nResult += GetOutputFor(vin[i], inputs).nValue;
1334 unsigned int CTransaction::GetP2SHSigOpCount(CCoinsView& inputs) const
1339 unsigned int nSigOps = 0;
1340 for (unsigned int i = 0; i < vin.size(); i++)
1342 CTxOut prevout = GetOutputFor(vin[i], inputs);
1343 if (prevout.scriptPubKey.IsPayToScriptHash())
1344 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1349 bool CTransaction::UpdateCoins(CCoinsView &inputs, CTxUndo &txundo, int nHeight, unsigned int nTimeStamp) const
1351 uint256 hash = GetHash();
1353 // mark inputs spent
1354 if (!IsCoinBase()) {
1355 BOOST_FOREACH(const CTxIn &txin, vin) {
1357 if (!inputs.GetCoins(txin.prevout.hash, coins))
1358 return error("UpdateCoins() : cannot find prevtx");
1360 if (coins.nTime > nTimeStamp)
1361 return error("UpdateCoins() : timestamp violation");
1364 if (!coins.Spend(txin.prevout, undo))
1365 return error("UpdateCoins() : cannot spend input");
1366 txundo.vprevout.push_back(undo);
1367 if (!inputs.SetCoins(txin.prevout.hash, coins))
1368 return error("UpdateCoins() : cannot update input");
1373 if (!inputs.SetCoins(hash, CCoins(*this, nHeight, nTimeStamp)))
1374 return error("UpdateCoins() : cannot update output");
1379 bool CTransaction::HaveInputs(CCoinsView &inputs) const
1381 if (!IsCoinBase()) {
1382 // first check whether information about the prevout hash is available
1383 for (unsigned int i = 0; i < vin.size(); i++) {
1384 const COutPoint &prevout = vin[i].prevout;
1385 if (!inputs.HaveCoins(prevout.hash))
1389 // then check whether the actual outputs are available
1390 for (unsigned int i = 0; i < vin.size(); i++) {
1391 const COutPoint &prevout = vin[i].prevout;
1393 inputs.GetCoins(prevout.hash, coins);
1394 if (!coins.IsAvailable(prevout.n))
1401 bool CTransaction::CheckInputs(CCoinsView &inputs, enum CheckSig_mode csmode, bool fStrictPayToScriptHash, bool fStrictEncodings, CBlock *pblock) const
1407 for (unsigned int i = 0; i < vin.size(); i++)
1409 const COutPoint &prevout = vin[i].prevout;
1411 if (!inputs.GetCoins(prevout.hash, coins))
1412 return error("CheckInputs() : cannot find prevout tx");
1414 // Check for conflicts (double-spend)
1415 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1416 // for an attacker to attempt to split the network.
1417 if (!coins.IsAvailable(prevout.n))
1418 return error("CheckInputs() : %s prev tx already used", GetHash().ToString().substr(0,10).c_str());
1420 // If prev is coinbase or coinstake, check that it's matured
1421 if (coins.IsCoinBase() || coins.IsCoinStake()) {
1422 CBlockIndex *pindexBlock = inputs.GetBestBlock();
1423 if (pindexBlock->nHeight - coins.nHeight < nCoinbaseMaturity)
1424 return error("CheckInputs() : tried to spend %s at depth %d", coins.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - coins.nHeight);
1427 // Check transaction timestamp
1428 if (coins.nTime > nTime)
1429 return DoS(100, error("CheckInputs() : transaction timestamp earlier than input transaction"));
1431 // Check for negative or overflow input values
1432 nValueIn += coins.vout[prevout.n].nValue;
1433 if (!MoneyRange(coins.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1434 return DoS(100, error("CheckInputs() : txin values out of range"));
1440 return error("CheckInputs() : %s is a coinstake, but no block specified", GetHash().ToString().substr(0,10).c_str());
1442 // Coin stake tx earns reward instead of paying fee
1444 if (!GetCoinAge(inputs, nCoinAge))
1445 return error("CheckInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1447 int64 nStakeReward = GetValueOut() - nValueIn;
1448 int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pblock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1450 if (nStakeReward > nCalculatedStakeReward)
1451 return DoS(100, error("CheckInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1455 if (nValueIn < GetValueOut())
1456 return DoS(100, error("ChecktInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1458 // Tally transaction fees
1459 int64 nTxFee = nValueIn - GetValueOut();
1461 return DoS(100, error("CheckInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1463 if (!MoneyRange(nFees))
1464 return DoS(100, error("CheckInputs() : nFees out of range"));
1466 // enforce transaction fees for every block until 1 May 2014 04:00:00 GMT
1467 if (!fTestNet && nTxFee < GetMinFee() && nTime < OUTPUT_SWITCH_TIME)
1468 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;
1471 // The first loop above does all the inexpensive checks.
1472 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1473 // Helps prevent CPU exhaustion attacks.
1475 // Skip ECDSA signature verification when connecting blocks
1476 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1477 // still computed and checked, and any change will be caught at the next checkpoint.
1478 if (csmode == CS_ALWAYS ||
1479 (csmode == CS_AFTER_CHECKPOINT && inputs.GetBestBlock()->nHeight >= Checkpoints::GetTotalBlocksEstimate())) {
1480 for (unsigned int i = 0; i < vin.size(); i++) {
1481 const COutPoint &prevout = vin[i].prevout;
1483 inputs.GetCoins(prevout.hash, coins);
1486 if (!VerifySignature(coins, *this, i, fStrictPayToScriptHash, fStrictEncodings, 0)) {
1487 // only during transition phase for P2SH: do not invoke anti-DoS code for
1488 // potentially old clients relaying bad P2SH transactions
1489 if (fStrictPayToScriptHash && VerifySignature(coins, *this, i, false, fStrictEncodings, 0))
1490 return error("CheckInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1492 return DoS(100,error("CheckInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1504 bool CTransaction::ClientCheckInputs() const
1509 // Take over previous transactions' spent pointers
1513 for (unsigned int i = 0; i < vin.size(); i++)
1515 // Get prev tx from single transactions in memory
1516 COutPoint prevout = vin[i].prevout;
1517 if (!mempool.exists(prevout.hash))
1519 CTransaction& txPrev = mempool.lookup(prevout.hash);
1521 if (prevout.n >= txPrev.vout.size())
1525 if (!VerifySignature(CCoins(txPrev, -1, -1), *this, i, true, false, 0))
1526 return error("ConnectInputs() : VerifySignature failed");
1528 ///// this is redundant with the mempool.mapNextTx stuff,
1529 ///// not sure which I want to get rid of
1530 ///// this has to go away now that posNext is gone
1531 // // Check for conflicts
1532 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1533 // return error("ConnectInputs() : prev tx already used");
1535 // // Flag outpoints as used
1536 // txPrev.vout[prevout.n].posNext = posThisTx;
1538 nValueIn += txPrev.vout[prevout.n].nValue;
1540 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1541 return error("ClientConnectInputs() : txin values out of range");
1543 if (GetValueOut() > nValueIn)
1550 bool CBlock::DisconnectBlock(CBlockIndex *pindex, CCoinsView &view)
1552 assert(pindex == view.GetBestBlock());
1554 CBlockUndo blockUndo;
1556 CDiskBlockPos pos = pindex->GetUndoPos();
1558 return error("DisconnectBlock() : no undo data available");
1559 FILE *file = OpenUndoFile(pos, true);
1561 return error("DisconnectBlock() : undo file not available");
1562 CAutoFile fileUndo(file, SER_DISK, CLIENT_VERSION);
1563 fileUndo >> blockUndo;
1566 assert(blockUndo.vtxundo.size() + 1 == vtx.size());
1568 // undo transactions in reverse order
1569 for (int i = vtx.size() - 1; i >= 0; i--) {
1570 const CTransaction &tx = vtx[i];
1571 uint256 hash = tx.GetHash();
1573 // check that all outputs are available
1575 if (!view.GetCoins(hash, outs))
1576 return error("DisconnectBlock() : outputs still spent? database corrupted");
1578 CCoins outsBlock = CCoins(tx, pindex->nHeight, pindex->nTime);
1579 if (outs != outsBlock)
1580 return error("DisconnectBlock() : added transaction mismatch? database corrupted");
1583 if (!view.SetCoins(hash, CCoins()))
1584 return error("DisconnectBlock() : cannot delete coin outputs");
1587 if (i > 0) { // not coinbases
1588 const CTxUndo &txundo = blockUndo.vtxundo[i-1];
1589 assert(txundo.vprevout.size() == tx.vin.size());
1590 for (unsigned int j = tx.vin.size(); j-- > 0;) {
1591 const COutPoint &out = tx.vin[j].prevout;
1592 const CTxInUndo &undo = txundo.vprevout[j];
1594 view.GetCoins(out.hash, coins); // this can fail if the prevout was already entirely spent
1595 if (coins.IsPruned()) {
1596 if (undo.nHeight == 0)
1597 return error("DisconnectBlock() : undo data doesn't contain tx metadata? database corrupted");
1598 coins.fCoinBase = undo.fCoinBase;
1599 coins.nHeight = undo.nHeight;
1600 coins.nVersion = undo.nVersion;
1602 if (undo.nHeight != 0)
1603 return error("DisconnectBlock() : undo data contains unneeded tx metadata? database corrupted");
1605 if (coins.IsAvailable(out.n))
1606 return error("DisconnectBlock() : prevout output not spent? database corrupted");
1607 if (coins.vout.size() < out.n+1)
1608 coins.vout.resize(out.n+1);
1609 coins.vout[out.n] = undo.txout;
1610 if (!view.SetCoins(out.hash, coins))
1611 return error("DisconnectBlock() : cannot restore coin inputs");
1616 // move best block pointer to prevout block
1617 view.SetBestBlock(pindex->pprev);
1622 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize);
1624 bool CBlock::ConnectBlock(CBlockIndex* pindex, CCoinsView &view, bool fJustCheck)
1626 // Check it again in case a previous version let a bad block in
1627 if (!CheckBlock(!fJustCheck, !fJustCheck))
1630 // verify that the view's current state corresponds to the previous block
1631 assert(pindex->pprev == view.GetBestBlock());
1633 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1634 // unless those are already completely spent.
1635 // If such overwrites are allowed, coinbases and transactions depending upon those
1636 // can be duplicated to remove the ability to spend the first instance -- even after
1637 // being sent to another address.
1638 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1639 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1640 // already refuses previously-known transaction ids entirely.
1641 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1642 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1643 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1644 // initial block download.
1645 bool fEnforceBIP30 = true;
1647 if (fEnforceBIP30) {
1648 BOOST_FOREACH(CTransaction& tx, vtx) {
1649 uint256 hash = tx.GetHash();
1651 if (view.GetCoins(hash, coins) && !coins.IsPruned())
1652 return error("ConnectBlock() : tried to overwrite transaction");
1656 // BIP16 always active
1657 bool fStrictPayToScriptHash = true;
1659 CBlockUndo blockundo;
1661 int64 nFees = 0, nValueIn = 0, nValueOut = 0;
1662 unsigned int nSigOps = 0;
1663 BOOST_FOREACH(CTransaction& tx, vtx)
1665 nSigOps += tx.GetLegacySigOpCount();
1666 if (nSigOps > MAX_BLOCK_SIGOPS)
1667 return DoS(100, error("ConnectBlock() : too many sigops"));
1669 if (!tx.IsCoinBase())
1671 if (!tx.HaveInputs(view))
1672 return DoS(100, error("ConnectBlock() : inputs missing/spent"));
1674 if (fStrictPayToScriptHash)
1676 // Add in sigops done by pay-to-script-hash inputs;
1677 // this is to prevent a "rogue miner" from creating
1678 // an incredibly-expensive-to-validate block.
1679 nSigOps += tx.GetP2SHSigOpCount(view);
1680 if (nSigOps > MAX_BLOCK_SIGOPS)
1681 return DoS(100, error("ConnectBlock() : too many sigops"));
1684 int64 nTxValueOut = tx.GetValueOut();
1685 int64 nTxValueIn = tx.GetValueIn(view);
1687 nValueIn += nTxValueIn;
1688 nValueOut += nTxValueOut;
1690 if (!tx.IsCoinStake())
1691 nFees += nTxValueIn - nTxValueOut;
1693 if (!tx.CheckInputs(view, CS_AFTER_CHECKPOINT, fStrictPayToScriptHash, false, this))
1698 nValueOut += tx.GetValueOut();
1702 if (!tx.UpdateCoins(view, txundo, pindex->nHeight, pindex->nTime))
1703 return error("ConnectBlock() : UpdateInputs failed");
1704 if (!tx.IsCoinBase())
1705 blockundo.vtxundo.push_back(txundo);
1708 pindex->nMint = nValueOut - nValueIn + nFees;
1709 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1717 // Write undo information to disk
1718 if (pindex->GetUndoPos().IsNull())
1720 if (!FindUndoPos(chaindb, pindex->pos.nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 8))
1721 return error("ConnectBlock() : FindUndoPos failed");
1722 if (!blockundo.WriteToDisk(pos))
1723 return error("ConnectBlock() : CBlockUndo::WriteToDisk failed");
1725 // update nUndoPos in block index
1726 pindex->nUndoPos = pos.nPos + 1;
1729 CDiskBlockIndex blockindex(pindex);
1730 if (!chaindb.WriteBlockIndex(blockindex))
1731 return error("ConnectBlock() : WriteBlockIndex failed");
1733 // add this block to the view's blockchain
1734 if (!view.SetBestBlock(pindex))
1737 // fees are destroyed to compensate the entire network
1738 if (fDebug && GetBoolArg("-printcreation"))
1739 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1741 // Watch for transactions paying to me
1742 BOOST_FOREACH(CTransaction& tx, vtx)
1743 SyncWithWallets(tx, this, true);
1748 bool CBlock::SetBestChain(CBlockIndex* pindexNew)
1750 // if this functions exits prematurely, the transaction is aborted
1752 if (!coinsdb.TxnBegin())
1753 return error("SetBestChain() : TxnBegin failed");
1755 // special case for attaching the genesis block
1756 // note that no ConnectBlock is called, so its coinbase output is non-spendable
1757 if (pindexGenesisBlock == NULL && pindexNew->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1759 coinsdb.WriteHashBestChain(pindexNew->GetBlockHash());
1760 if (!coinsdb.TxnCommit())
1761 return error("SetBestChain() : TxnCommit failed");
1762 pindexGenesisBlock = pindexNew;
1763 pindexBest = pindexNew;
1764 hashBestChain = pindexNew->GetBlockHash();
1765 nBestHeight = pindexBest->nHeight;
1766 nBestChainTrust = pindexNew->nChainTrust;
1770 // create cached view to the coins database
1771 CCoinsViewDB viewDB(coinsdb);
1772 CCoinsViewCache view(viewDB);
1774 // Find the fork (typically, there is none)
1775 CBlockIndex* pfork = view.GetBestBlock();
1776 CBlockIndex* plonger = pindexNew;
1777 while (pfork != plonger)
1779 while (plonger->nHeight > pfork->nHeight)
1780 if (!(plonger = plonger->pprev))
1781 return error("SetBestChain() : plonger->pprev is null");
1782 if (pfork == plonger)
1784 if (!(pfork = pfork->pprev))
1785 return error("SetBestChain() : pfork->pprev is null");
1788 // List of what to disconnect (typically nothing)
1789 vector<CBlockIndex*> vDisconnect;
1790 for (CBlockIndex* pindex = view.GetBestBlock(); pindex != pfork; pindex = pindex->pprev)
1791 vDisconnect.push_back(pindex);
1793 // List of what to connect (typically only pindexNew)
1794 vector<CBlockIndex*> vConnect;
1795 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1796 vConnect.push_back(pindex);
1797 reverse(vConnect.begin(), vConnect.end());
1799 if (vDisconnect.size() > 0) {
1800 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());
1801 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());
1804 // Disconnect shorter branch
1805 vector<CTransaction> vResurrect;
1806 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) {
1808 if (!block.ReadFromDisk(pindex))
1809 return error("SetBestBlock() : ReadFromDisk for disconnect failed");
1810 if (!block.DisconnectBlock(pindex, view))
1811 return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1813 // Queue memory transactions to resurrect
1814 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1815 if (!tx.IsCoinBase())
1816 vResurrect.push_back(tx);
1819 // Connect longer branch
1820 vector<CTransaction> vDelete;
1821 BOOST_FOREACH(CBlockIndex *pindex, vConnect) {
1824 if (pindex == pindexNew) // connecting *this block
1826 else { // other block; read it from disk
1827 if (!block.ReadFromDisk(pindex))
1828 return error("SetBestBlock() : ReadFromDisk for connect failed");
1831 if (!pblock->ConnectBlock(pindex, view)) {
1832 InvalidChainFound(pindexNew);
1833 return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1836 // Queue memory transactions to delete
1837 BOOST_FOREACH(const CTransaction& tx, pblock->vtx)
1838 vDelete.push_back(tx);
1841 // Make sure it's successfully written to disk before changing memory structure
1843 return error("SetBestBlock() : failed to write coin changes");
1844 if (!coinsdb.TxnCommit())
1845 return error("SetBestBlock() : TxnCommit failed");
1848 // At this point, all changes have been done to the database.
1849 // Proceed by updating the memory structures.
1851 // Disconnect shorter branch
1852 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1854 pindex->pprev->pnext = NULL;
1856 // Connect longer branch
1857 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1859 pindex->pprev->pnext = pindex;
1861 // Resurrect memory transactions that were in the disconnected branch
1862 BOOST_FOREACH(CTransaction& tx, vResurrect)
1863 tx.AcceptToMemoryPool(coinsdb, false);
1865 // Delete redundant memory transactions that are in the connected branch
1866 BOOST_FOREACH(CTransaction& tx, vDelete)
1869 // Update best block in wallet (so we can detect restored wallets)
1870 bool fIsInitialDownload = IsInitialBlockDownload();
1871 if (!fIsInitialDownload)
1873 const CBlockLocator locator(pindexNew);
1874 ::SetBestChain(locator);
1878 hashBestChain = pindexNew->GetBlockHash();
1879 pindexBest = pindexNew;
1880 pblockindexFBBHLast = NULL;
1881 nBestHeight = pindexBest->nHeight;
1882 nBestChainTrust = pindexNew->nChainTrust;
1883 nTimeBestReceived = GetTime();
1884 nTransactionsUpdated++;
1886 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1888 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1889 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1890 CBigNum(nBestChainTrust).ToString().c_str(),
1891 nBestBlockTrust.Get64(),
1892 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1894 // Check the version of the last 100 blocks to see if we need to upgrade:
1895 if (!fIsInitialDownload)
1898 const CBlockIndex* pindex = pindexBest;
1899 for (int i = 0; i < 100 && pindex != NULL; i++)
1901 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1903 pindex = pindex->pprev;
1906 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1907 if (nUpgraded > 100/2)
1908 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1909 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1912 std::string strCmd = GetArg("-blocknotify", "");
1914 if (!fIsInitialDownload && !strCmd.empty())
1916 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1917 boost::thread t(runCommand, strCmd); // thread runs free
1923 // Total coin age spent in transaction, in the unit of coin-days.
1924 // Only those coins meeting minimum age requirement counts. As those
1925 // transactions not in main chain are not currently indexed so we
1926 // might not find out about their coin age. Older transactions are
1927 // guaranteed to be in main chain by sync-checkpoint. This rule is
1928 // introduced to help nodes establish a consistent view of the coin
1929 // age (trust score) of competing branches.
1930 bool CTransaction::GetCoinAge(CCoinsView& inputs, uint64& nCoinAge) const
1932 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1938 for (unsigned int i = 0; i < vin.size(); i++)
1940 const COutPoint &prevout = vin[i].prevout;
1942 if (!inputs.GetCoins(prevout.hash, coins))
1945 if (nTime < coins.nTime)
1946 return false; // Transaction timestamp violation
1948 // only count coins meeting min age requirement
1949 if (coins.nBlockTime + nStakeMinAge > nTime)
1952 int64 nValueIn = coins.vout[vin[i].prevout.n].nValue;
1953 bnCentSecond += CBigNum(nValueIn) * (nTime-coins.nTime) / CENT;
1956 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1957 if (fDebug && GetBoolArg("-printcoinage"))
1958 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1959 nCoinAge = bnCoinDay.getuint64();
1963 // Total coin age spent in block, in the unit of coin-days.
1964 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1968 CCoinsDB coindb("r");
1969 CCoinsViewDB view(coindb);
1971 BOOST_FOREACH(const CTransaction& tx, vtx)
1974 if (tx.GetCoinAge(view, nTxCoinAge))
1975 nCoinAge += nTxCoinAge;
1980 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1982 if (fDebug && GetBoolArg("-printcoinage"))
1983 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1987 bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
1989 // Check for duplicate
1990 uint256 hash = GetHash();
1991 if (mapBlockIndex.count(hash))
1992 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1994 // Construct new block index object
1995 CBlockIndex* pindexNew = new CBlockIndex(*this);
1997 return error("AddToBlockIndex() : new CBlockIndex failed");
1998 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1999 pindexNew->phashBlock = &((*mi).first);
2000 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2001 if (miPrev != mapBlockIndex.end())
2003 pindexNew->pprev = (*miPrev).second;
2004 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2006 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2007 pindexNew->pos = pos;
2008 pindexNew->nUndoPos = 0;
2010 // Compute stake entropy bit for stake modifier
2011 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2012 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2014 // Record proof-of-stake hash value
2015 if (pindexNew->IsProofOfStake())
2017 if (!mapProofOfStake.count(hash))
2018 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2019 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2022 // Compute stake modifier
2023 uint64 nStakeModifier = 0;
2024 bool fGeneratedStakeModifier = false;
2025 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2026 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2027 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2028 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2029 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2030 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2033 if (!chaindb.TxnBegin())
2035 chaindb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2036 if (!chaindb.TxnCommit())
2040 if (pindexNew->nChainTrust > nBestChainTrust) {
2041 if (!IsInitialBlockDownload() || (pindexNew->nHeight % 1) == 0)
2042 if (!SetBestChain(pindexNew))
2046 if (pindexNew == pindexBest)
2048 // Notify UI to display prev block's coinbase if it was ours
2049 static uint256 hashPrevBestCoinBase;
2050 UpdatedTransaction(hashPrevBestCoinBase);
2051 hashPrevBestCoinBase = vtx[0].GetHash();
2054 uiInterface.NotifyBlocksChanged();
2058 bool FindBlockPos(CChainDB &chaindb, CDiskBlockPos &pos, unsigned int nAddSize, unsigned int nHeight, uint64 nTime)
2060 bool fUpdatedLast = false;
2062 LOCK(cs_LastBlockFile);
2064 while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
2065 printf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
2066 FILE *file = OpenBlockFile(pos);
2069 file = OpenUndoFile(pos);
2073 infoLastBlockFile.SetNull();
2074 chaindb.ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile); // check whether data for the new file somehow already exist; can fail just fine
2075 fUpdatedLast = true;
2078 pos.nFile = nLastBlockFile;
2079 pos.nPos = infoLastBlockFile.nSize;
2080 infoLastBlockFile.nSize += nAddSize;
2081 infoLastBlockFile.AddBlock(nHeight, nTime);
2083 unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2084 unsigned int nNewChunks = (infoLastBlockFile.nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
2085 if (nNewChunks > nOldChunks) {
2086 FILE *file = OpenBlockFile(pos);
2088 printf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
2089 AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
2094 if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2095 return error("FindBlockPos() : cannot write updated block info");
2097 chaindb.WriteLastBlockFile(nLastBlockFile);
2102 bool FindUndoPos(CChainDB &chaindb, int nFile, CDiskBlockPos &pos, unsigned int nAddSize)
2106 LOCK(cs_LastBlockFile);
2108 unsigned int nNewSize;
2109 if (nFile == nLastBlockFile) {
2110 pos.nPos = infoLastBlockFile.nUndoSize;
2111 nNewSize = (infoLastBlockFile.nUndoSize += nAddSize);
2112 if (!chaindb.WriteBlockFileInfo(nLastBlockFile, infoLastBlockFile))
2113 return error("FindUndoPos() : cannot write updated block info");
2115 CBlockFileInfo info;
2116 if (!chaindb.ReadBlockFileInfo(nFile, info))
2117 return error("FindUndoPos() : cannot read block info");
2118 pos.nPos = info.nUndoSize;
2119 nNewSize = (info.nUndoSize += nAddSize);
2120 if (!chaindb.WriteBlockFileInfo(nFile, info))
2121 return error("FindUndoPos() : cannot write updated block info");
2124 unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2125 unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
2126 if (nNewChunks > nOldChunks) {
2127 FILE *file = OpenUndoFile(pos);
2129 printf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
2130 AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
2138 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2140 // These are checks that are independent of context
2141 // that can be verified before saving an orphan block.
2144 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2145 return DoS(100, error("CheckBlock() : size limits failed"));
2147 // Check proof of work matches claimed amount
2148 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2149 return DoS(50, error("CheckBlock() : proof of work failed"));
2152 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
2153 return error("CheckBlock() : block timestamp too far in the future");
2155 // First transaction must be coinbase, the rest must not be
2156 if (vtx.empty() || !vtx[0].IsCoinBase())
2157 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2158 for (unsigned int i = 1; i < vtx.size(); i++)
2159 if (vtx[i].IsCoinBase())
2160 return DoS(100, error("CheckBlock() : more than one coinbase"));
2162 // Check coinbase timestamp
2163 if (GetBlockTime() > FutureDrift((int64)vtx[0].nTime))
2164 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2166 if (IsProofOfStake())
2168 // Coinbase output should be empty if proof-of-stake block
2169 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2170 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2172 // Second transaction must be coinstake, the rest must not be
2173 if (vtx.empty() || !vtx[1].IsCoinStake())
2174 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2175 for (unsigned int i = 2; i < vtx.size(); i++)
2176 if (vtx[i].IsCoinStake())
2177 return DoS(100, error("CheckBlock() : more than one coinstake"));
2179 // Check coinstake timestamp
2180 if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2181 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2183 // NovaCoin: check proof-of-stake block signature
2184 if (fCheckSig && !CheckBlockSignature(true))
2185 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2189 int64 nReward = GetProofOfWorkReward(nBits);
2190 // Check coinbase reward
2191 if (vtx[0].GetValueOut() > nReward)
2192 return DoS(50, error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
2193 vtx[0].GetValueOut(),
2196 // Should we check proof-of-work block signature or not?
2198 // * Always skip on TestNet
2199 // * Perform checking for the first 9689 blocks
2200 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2202 if(!fTestNet && fCheckSig)
2204 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2206 // NovaCoin: check proof-of-work block signature
2207 if (checkEntropySig && !CheckBlockSignature(false))
2208 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2213 // Check transactions
2214 BOOST_FOREACH(const CTransaction& tx, vtx)
2216 if (!tx.CheckTransaction())
2217 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2219 // check transaction timestamp
2220 if (GetBlockTime() < (int64)tx.nTime)
2221 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2224 // Check for duplicate txids. This is caught by ConnectInputs(),
2225 // but catching it earlier avoids a potential DoS attack:
2226 set<uint256> uniqueTx;
2227 BOOST_FOREACH(const CTransaction& tx, vtx)
2229 uniqueTx.insert(tx.GetHash());
2231 if (uniqueTx.size() != vtx.size())
2232 return DoS(100, error("CheckBlock() : duplicate transaction"));
2234 unsigned int nSigOps = 0;
2235 BOOST_FOREACH(const CTransaction& tx, vtx)
2237 nSigOps += tx.GetLegacySigOpCount();
2239 if (nSigOps > MAX_BLOCK_SIGOPS)
2240 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2242 // Check merkle root
2243 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2244 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2250 bool CBlock::AcceptBlock()
2252 // Check for duplicate
2253 uint256 hash = GetHash();
2254 if (mapBlockIndex.count(hash))
2255 return error("AcceptBlock() : block already in mapBlockIndex");
2257 // Get prev block index
2258 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2259 if (mi == mapBlockIndex.end())
2260 return DoS(10, error("AcceptBlock() : prev block not found"));
2261 CBlockIndex* pindexPrev = (*mi).second;
2262 int nHeight = pindexPrev->nHeight+1;
2264 // Check proof-of-work or proof-of-stake
2265 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2266 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2268 // Check timestamp against prev
2269 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2270 return error("AcceptBlock() : block's timestamp is too early");
2272 // Check that all transactions are finalized
2273 BOOST_FOREACH(const CTransaction& tx, vtx)
2274 if (!tx.IsFinal(nHeight, GetBlockTime()))
2275 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2277 // Check that the block chain matches the known block chain up to a checkpoint
2278 if (!Checkpoints::CheckHardened(nHeight, hash))
2279 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2281 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2283 // Check that the block satisfies synchronized checkpoint
2284 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2285 return error("AcceptBlock() : rejected by synchronized checkpoint");
2287 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2288 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2290 // Enforce rule that the coinbase starts with serialized block height
2291 CScript expect = CScript() << nHeight;
2292 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2293 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2294 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2296 // Write block to history file
2297 unsigned int nBlockSize = ::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION);
2298 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2299 return error("AcceptBlock() : out of disk space");
2300 CDiskBlockPos blockPos;
2303 if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, nHeight, nTime))
2304 return error("AcceptBlock() : FindBlockPos failed");
2306 if (!WriteToDisk(blockPos))
2307 return error("AcceptBlock() : WriteToDisk failed");
2308 if (!AddToBlockIndex(blockPos))
2309 return error("AcceptBlock() : AddToBlockIndex failed");
2311 // Relay inventory, but don't relay old inventory during initial block download
2312 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2313 if (hashBestChain == hash)
2316 BOOST_FOREACH(CNode* pnode, vNodes)
2317 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2318 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2321 // Check pending sync-checkpoint
2322 Checkpoints::AcceptPendingSyncCheckpoint();
2327 uint256 CBlockIndex::GetBlockTrust() const
2330 bnTarget.SetCompact(nBits);
2336 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2337 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2341 // Calculate work amount for block
2342 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2344 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2345 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2347 // Return nPoWTrust for the first 12 blocks
2348 if (pprev == NULL || pprev->nHeight < 12)
2351 const CBlockIndex* currentIndex = pprev;
2353 if(IsProofOfStake())
2355 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2357 // Return 1/3 of score if parent block is not the PoW block
2358 if (!pprev->IsProofOfWork())
2359 return (bnNewTrust / 3).getuint256();
2363 // Check last 12 blocks type
2364 while (pprev->nHeight - currentIndex->nHeight < 12)
2366 if (currentIndex->IsProofOfWork())
2368 currentIndex = currentIndex->pprev;
2371 // Return 1/3 of score if less than 3 PoW blocks found
2373 return (bnNewTrust / 3).getuint256();
2375 return bnNewTrust.getuint256();
2379 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2381 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2382 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2383 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2387 // Check last 12 blocks type
2388 while (pprev->nHeight - currentIndex->nHeight < 12)
2390 if (currentIndex->IsProofOfStake())
2392 currentIndex = currentIndex->pprev;
2395 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2397 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2399 bnTarget.SetCompact(pprev->nBits);
2404 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2406 // Return nPoWTrust + full trust score for previous block nBits
2407 return nPoWTrust + bnNewTrust.getuint256();
2411 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2413 unsigned int nFound = 0;
2414 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2416 if (pstart->nVersion >= minVersion)
2418 pstart = pstart->pprev;
2420 return (nFound >= nRequired);
2423 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2425 // Check for duplicate
2426 uint256 hash = pblock->GetHash();
2427 if (mapBlockIndex.count(hash))
2428 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2429 if (mapOrphanBlocks.count(hash))
2430 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2432 // ppcoin: check proof-of-stake
2433 // Limited duplicity on stake: prevents block flood attack
2434 // Duplicate stake allowed only when there is orphan child block
2435 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2436 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());
2438 // Preliminary checks
2439 if (!pblock->CheckBlock())
2440 return error("ProcessBlock() : CheckBlock FAILED");
2442 // ppcoin: verify hash target and signature of coinstake tx
2443 if (pblock->IsProofOfStake())
2445 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2446 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2448 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2449 return false; // do not error here as we expect this during initial block download
2451 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2452 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2455 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2456 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2458 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2459 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2461 bnNewBlock.SetCompact(pblock->nBits);
2464 if (pblock->IsProofOfStake())
2465 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2467 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2469 if (bnNewBlock > bnRequired)
2472 pfrom->Misbehaving(100);
2473 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2477 // ppcoin: ask for pending sync-checkpoint if any
2478 if (!IsInitialBlockDownload())
2479 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2481 // If don't already have its previous block, shunt it off to holding area until we get it
2482 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2484 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2485 CBlock* pblock2 = new CBlock(*pblock);
2486 // ppcoin: check proof-of-stake
2487 if (pblock2->IsProofOfStake())
2489 // Limited duplicity on stake: prevents block flood attack
2490 // Duplicate stake allowed only when there is orphan child block
2491 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2492 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());
2494 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2496 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2497 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2499 // Ask this guy to fill in what we're missing
2502 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2503 // ppcoin: getblocks may not obtain the ancestor block rejected
2504 // earlier by duplicate-stake check so we ask for it again directly
2505 if (!IsInitialBlockDownload())
2506 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2512 if (!pblock->AcceptBlock())
2513 return error("ProcessBlock() : AcceptBlock FAILED");
2515 // Recursively process any orphan blocks that depended on this one
2516 vector<uint256> vWorkQueue;
2517 vWorkQueue.push_back(hash);
2518 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2520 uint256 hashPrev = vWorkQueue[i];
2521 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2522 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2525 CBlock* pblockOrphan = (*mi).second;
2526 if (pblockOrphan->AcceptBlock())
2527 vWorkQueue.push_back(pblockOrphan->GetHash());
2528 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2529 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2530 delete pblockOrphan;
2532 mapOrphanBlocksByPrev.erase(hashPrev);
2535 printf("ProcessBlock: ACCEPTED\n");
2537 // ppcoin: if responsible for sync-checkpoint send it
2538 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2539 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2544 // novacoin: attempt to generate suitable proof-of-stake
2545 bool CBlock::SignBlock(CWallet& wallet)
2547 // if we are trying to sign
2548 // something except proof-of-stake block template
2549 if (!vtx[0].vout[0].IsEmpty())
2552 // if we are trying to sign
2553 // a complete proof-of-stake block
2554 if (IsProofOfStake())
2557 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2560 CTransaction txCoinStake;
2561 int64 nSearchTime = txCoinStake.nTime; // search to current time
2563 if (nSearchTime > nLastCoinStakeSearchTime)
2565 if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2567 if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2569 // make sure coinstake would meet timestamp protocol
2570 // as it would be the same as the block timestamp
2571 vtx[0].nTime = nTime = txCoinStake.nTime;
2572 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2573 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2575 // we have to make sure that we have no future timestamps in
2576 // our transactions set
2577 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2578 if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2580 vtx.insert(vtx.begin() + 1, txCoinStake);
2581 hashMerkleRoot = BuildMerkleTree();
2583 // append a signature to our block
2584 return key.Sign(GetHash(), vchBlockSig);
2587 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2588 nLastCoinStakeSearchTime = nSearchTime;
2594 // ppcoin: check block signature
2595 bool CBlock::CheckBlockSignature(bool fProofOfStake) const
2597 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2598 return vchBlockSig.empty();
2600 vector<valtype> vSolutions;
2601 txnouttype whichType;
2605 const CTxOut& txout = vtx[1].vout[1];
2607 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2609 if (whichType == TX_PUBKEY)
2611 valtype& vchPubKey = vSolutions[0];
2613 if (!key.SetPubKey(vchPubKey))
2615 if (vchBlockSig.empty())
2617 return key.Verify(GetHash(), vchBlockSig);
2622 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2624 const CTxOut& txout = vtx[0].vout[i];
2626 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2629 if (whichType == TX_PUBKEY)
2632 valtype& vchPubKey = vSolutions[0];
2634 if (!key.SetPubKey(vchPubKey))
2636 if (vchBlockSig.empty())
2638 if(!key.Verify(GetHash(), vchBlockSig))
2648 bool CheckDiskSpace(uint64 nAdditionalBytes)
2650 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2652 // Check for nMinDiskSpace bytes (currently 50MB)
2653 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2656 string strMessage = _("Warning: Disk space is low!");
2657 strMiscWarning = strMessage;
2658 printf("*** %s\n", strMessage.c_str());
2659 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2667 CCriticalSection cs_LastBlockFile;
2668 CBlockFileInfo infoLastBlockFile;
2669 int nLastBlockFile = 0;
2671 FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
2675 boost::filesystem::path path = GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
2676 boost::filesystem::create_directories(path.parent_path());
2677 FILE* file = fopen(path.string().c_str(), "rb+");
2678 if (!file && !fReadOnly)
2679 file = fopen(path.string().c_str(), "wb+");
2681 printf("Unable to open file %s\n", path.string().c_str());
2685 if (fseek(file, pos.nPos, SEEK_SET)) {
2686 printf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
2694 FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly) {
2695 return OpenDiskFile(pos, "blk", fReadOnly);
2698 FILE *OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly) {
2699 return OpenDiskFile(pos, "rev", fReadOnly);
2702 bool LoadBlockIndex(bool fAllowNew)
2704 CBigNum bnTrustedModulus;
2708 pchMessageStart[0] = 0xcd;
2709 pchMessageStart[1] = 0xf2;
2710 pchMessageStart[2] = 0xc0;
2711 pchMessageStart[3] = 0xef;
2713 bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
2714 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2715 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2716 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2717 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2718 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2722 bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
2725 // Set up the Zerocoin Params object
2726 ZCParams = new libzerocoin::Params(bnTrustedModulus);
2731 CChainDB chaindb("cr");
2732 CCoinsDB coinsdb("cr");
2733 if (!LoadBlockIndex(coinsdb, chaindb))
2739 // Init with genesis block
2741 if (mapBlockIndex.empty())
2750 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2751 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2752 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2754 // vMerkleTree: 4cb33b3b6a
2758 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2759 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2760 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2762 // vMerkleTree: 4cb33b3b6a
2764 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2766 txNew.nTime = 1360105017;
2767 txNew.vin.resize(1);
2768 txNew.vout.resize(1);
2769 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2770 txNew.vout[0].SetEmpty();
2772 block.vtx.push_back(txNew);
2773 block.hashPrevBlock = 0;
2774 block.hashMerkleRoot = block.BuildMerkleTree();
2776 block.nTime = 1360105017;
2777 block.nBits = bnProofOfWorkLimit.GetCompact();
2778 block.nNonce = !fTestNet ? 1575379 : 46534;
2781 uint256 hash = block.GetHash();
2782 printf("%s\n", hash.ToString().c_str());
2783 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2785 assert(hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2786 assert(block.CheckBlock());
2788 // Start new block file
2789 unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
2790 CDiskBlockPos blockPos;
2793 if (!FindBlockPos(chaindb, blockPos, nBlockSize+8, 0, block.nTime))
2794 return error("AcceptBlock() : FindBlockPos failed");
2796 if (!block.WriteToDisk(blockPos))
2797 return error("LoadBlockIndex() : writing genesis block to disk failed");
2798 if (!block.AddToBlockIndex(blockPos))
2799 return error("LoadBlockIndex() : genesis block not accepted");
2801 // initialize synchronized checkpoint
2802 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2803 return error("LoadBlockIndex() : failed to init sync checkpoint");
2806 string strPubKey = "";
2809 // if checkpoint master key changed must reset sync-checkpoint
2810 if (!chaindb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2812 // write checkpoint master key to db
2814 if (!chaindb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2815 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2816 if (!chaindb.TxnCommit())
2817 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2818 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2819 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2826 void PrintBlockTree()
2828 // pre-compute tree structure
2829 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2830 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2832 CBlockIndex* pindex = (*mi).second;
2833 mapNext[pindex->pprev].push_back(pindex);
2835 //while (rand() % 3 == 0)
2836 // mapNext[pindex->pprev].push_back(pindex);
2839 vector<pair<int, CBlockIndex*> > vStack;
2840 vStack.push_back(make_pair(0, pindexGenesisBlock));
2843 while (!vStack.empty())
2845 int nCol = vStack.back().first;
2846 CBlockIndex* pindex = vStack.back().second;
2849 // print split or gap
2850 if (nCol > nPrevCol)
2852 for (int i = 0; i < nCol-1; i++)
2856 else if (nCol < nPrevCol)
2858 for (int i = 0; i < nCol; i++)
2865 for (int i = 0; i < nCol; i++)
2870 block.ReadFromDisk(pindex);
2871 printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
2873 pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
2874 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2877 PrintWallets(block);
2879 // put the main time-chain first
2880 vector<CBlockIndex*>& vNext = mapNext[pindex];
2881 for (unsigned int i = 0; i < vNext.size(); i++)
2883 if (vNext[i]->pnext)
2885 swap(vNext[0], vNext[i]);
2891 for (unsigned int i = 0; i < vNext.size(); i++)
2892 vStack.push_back(make_pair(nCol+i, vNext[i]));
2896 bool LoadExternalBlockFile(FILE* fileIn)
2898 int64 nStart = GetTimeMillis();
2904 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2905 unsigned int nPos = 0;
2906 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2908 unsigned char pchData[65536];
2910 fseek(blkdat, nPos, SEEK_SET);
2911 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2914 nPos = (unsigned int)-1;
2917 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2920 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2922 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2925 nPos += ((unsigned char*)nFind - pchData) + 1;
2928 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2929 } while(!fRequestShutdown);
2930 if (nPos == (unsigned int)-1)
2932 fseek(blkdat, nPos, SEEK_SET);
2935 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2939 if (ProcessBlock(NULL,&block))
2947 catch (std::exception &e) {
2948 printf("%s() : Deserialize or I/O error caught during load\n",
2949 __PRETTY_FUNCTION__);
2952 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2956 //////////////////////////////////////////////////////////////////////////////
2961 extern map<uint256, CAlert> mapAlerts;
2962 extern CCriticalSection cs_mapAlerts;
2964 extern string strMintMessage;
2965 extern string strMintWarning;
2967 string GetWarnings(string strFor)
2970 string strStatusBar;
2973 if (GetBoolArg("-testsafemode"))
2976 // ppcoin: wallet lock warning for minting
2977 if (strMintWarning != "")
2980 strStatusBar = strMintWarning;
2983 // Misc warnings like out of disk space and clock is wrong
2984 if (strMiscWarning != "")
2987 strStatusBar = strMiscWarning;
2990 // * Should not enter safe mode for longer invalid chain
2991 // * If sync-checkpoint is too old do not enter safe mode
2992 // * Display warning only in the STRICT mode
2993 if (CheckpointsMode == Checkpoints::STRICT && Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) &&
2994 !fTestNet && !IsInitialBlockDownload())
2997 strStatusBar = _("WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.");
3000 // ppcoin: if detected invalid checkpoint enter safe mode
3001 if (Checkpoints::hashInvalidCheckpoint != 0)
3004 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3010 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3012 const CAlert& alert = item.second;
3013 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3015 nPriority = alert.nPriority;
3016 strStatusBar = alert.strStatusBar;
3017 if (nPriority > 1000)
3018 strRPC = strStatusBar;
3023 if (strFor == "statusbar")
3024 return strStatusBar;
3025 else if (strFor == "rpc")
3027 assert(!"GetWarnings() : invalid parameter");
3038 //////////////////////////////////////////////////////////////////////////////
3044 bool static AlreadyHave(CCoinsDB &coinsdb, const CInv& inv)
3050 bool txInMap = false;
3053 txInMap = mempool.exists(inv.hash);
3055 return txInMap || mapOrphanTransactions.count(inv.hash) ||
3056 coinsdb.HaveCoins(inv.hash);
3059 return mapBlockIndex.count(inv.hash) ||
3060 mapOrphanBlocks.count(inv.hash);
3062 // Don't know what it is, just say we already got one
3069 // The message start string is designed to be unlikely to occur in normal data.
3070 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3071 // a large 4-byte int at any alignment.
3072 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3074 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3076 static map<CService, CPubKey> mapReuseKey;
3077 RandAddSeedPerfmon();
3079 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3080 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3082 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3086 if (strCommand == "version")
3088 // Each connection can only send one version message
3089 if (pfrom->nVersion != 0)
3091 pfrom->Misbehaving(1);
3099 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3100 if (pfrom->nVersion < MIN_PROTO_VERSION)
3102 // Since February 20, 2012, the protocol is initiated at version 209,
3103 // and earlier versions are no longer supported
3104 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3105 pfrom->fDisconnect = true;
3109 if (pfrom->nVersion == 10300)
3110 pfrom->nVersion = 300;
3112 vRecv >> addrFrom >> nNonce;
3114 vRecv >> pfrom->strSubVer;
3116 vRecv >> pfrom->nStartingHeight;
3118 if (pfrom->fInbound && addrMe.IsRoutable())
3120 pfrom->addrLocal = addrMe;
3124 // Disconnect if we connected to ourself
3125 if (nNonce == nLocalHostNonce && nNonce > 1)
3127 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3128 pfrom->fDisconnect = true;
3132 // record my external IP reported by peer
3133 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3134 addrSeenByPeer = addrMe;
3136 // Be shy and don't send version until we hear
3137 if (pfrom->fInbound)
3138 pfrom->PushVersion();
3140 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3142 AddTimeData(pfrom->addr, nTime);
3145 pfrom->PushMessage("verack");
3146 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3148 if (!pfrom->fInbound)
3150 // Advertise our address
3151 if (!fNoListen && !IsInitialBlockDownload())
3153 CAddress addr = GetLocalAddress(&pfrom->addr);
3154 if (addr.IsRoutable())
3155 pfrom->PushAddress(addr);
3158 // Get recent addresses
3159 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3161 pfrom->PushMessage("getaddr");
3162 pfrom->fGetAddr = true;
3164 addrman.Good(pfrom->addr);
3166 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3168 addrman.Add(addrFrom, addrFrom);
3169 addrman.Good(addrFrom);
3173 // Ask the first connected node for block updates
3174 static int nAskedForBlocks = 0;
3175 if (!pfrom->fClient && !pfrom->fOneShot &&
3176 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3177 (pfrom->nVersion < NOBLKS_VERSION_START ||
3178 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3179 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3182 pfrom->PushGetBlocks(pindexBest, uint256(0));
3188 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3189 item.second.RelayTo(pfrom);
3192 // Relay sync-checkpoint
3194 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3195 if (!Checkpoints::checkpointMessage.IsNull())
3196 Checkpoints::checkpointMessage.RelayTo(pfrom);
3199 pfrom->fSuccessfullyConnected = true;
3201 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());
3203 cPeerBlockCounts.input(pfrom->nStartingHeight);
3205 // ppcoin: ask for pending sync-checkpoint if any
3206 if (!IsInitialBlockDownload())
3207 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3211 else if (pfrom->nVersion == 0)
3213 // Must have a version message before anything else
3214 pfrom->Misbehaving(1);
3219 else if (strCommand == "verack")
3221 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3225 else if (strCommand == "addr")
3227 vector<CAddress> vAddr;
3230 // Don't want addr from older versions unless seeding
3231 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3233 if (vAddr.size() > 1000)
3235 pfrom->Misbehaving(20);
3236 return error("message addr size() = %"PRIszu"", vAddr.size());
3239 // Store the new addresses
3240 vector<CAddress> vAddrOk;
3241 int64 nNow = GetAdjustedTime();
3242 int64 nSince = nNow - 10 * 60;
3243 BOOST_FOREACH(CAddress& addr, vAddr)
3247 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3248 addr.nTime = nNow - 5 * 24 * 60 * 60;
3249 pfrom->AddAddressKnown(addr);
3250 bool fReachable = IsReachable(addr);
3251 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3253 // Relay to a limited number of other nodes
3256 // Use deterministic randomness to send to the same nodes for 24 hours
3257 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3258 static uint256 hashSalt;
3260 hashSalt = GetRandHash();
3261 uint64 hashAddr = addr.GetHash();
3262 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3263 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3264 multimap<uint256, CNode*> mapMix;
3265 BOOST_FOREACH(CNode* pnode, vNodes)
3267 if (pnode->nVersion < CADDR_TIME_VERSION)
3269 unsigned int nPointer;
3270 memcpy(&nPointer, &pnode, sizeof(nPointer));
3271 uint256 hashKey = hashRand ^ nPointer;
3272 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3273 mapMix.insert(make_pair(hashKey, pnode));
3275 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3276 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3277 ((*mi).second)->PushAddress(addr);
3280 // Do not store addresses outside our network
3282 vAddrOk.push_back(addr);
3284 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3285 if (vAddr.size() < 1000)
3286 pfrom->fGetAddr = false;
3287 if (pfrom->fOneShot)
3288 pfrom->fDisconnect = true;
3291 else if (strCommand == "inv")
3295 if (vInv.size() > MAX_INV_SZ)
3297 pfrom->Misbehaving(20);
3298 return error("message inv size() = %"PRIszu"", vInv.size());
3301 // find last block in inv vector
3302 unsigned int nLastBlock = (unsigned int)(-1);
3303 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3304 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3305 nLastBlock = vInv.size() - 1 - nInv;
3309 CCoinsDB coinsdb("r");
3310 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3312 const CInv &inv = vInv[nInv];
3316 pfrom->AddInventoryKnown(inv);
3318 bool fAlreadyHave = AlreadyHave(coinsdb, inv);
3320 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3324 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3325 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3326 } else if (nInv == nLastBlock) {
3327 // In case we are on a very long side-chain, it is possible that we already have
3328 // the last block in an inv bundle sent in response to getblocks. Try to detect
3329 // this situation and push another getblocks to continue.
3330 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3332 printf("force request: %s\n", inv.ToString().c_str());
3335 // Track requests for our stuff
3336 Inventory(inv.hash);
3341 else if (strCommand == "getdata")
3345 if (vInv.size() > MAX_INV_SZ)
3347 pfrom->Misbehaving(20);
3348 return error("message getdata size() = %"PRIszu"", vInv.size());
3351 if (fDebugNet || (vInv.size() != 1))
3352 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3354 BOOST_FOREACH(const CInv& inv, vInv)
3358 if (fDebugNet || (vInv.size() == 1))
3359 printf("received getdata for: %s\n", inv.ToString().c_str());
3361 if (inv.type == MSG_BLOCK)
3363 // Send block from disk
3364 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3365 if (mi != mapBlockIndex.end())
3368 block.ReadFromDisk((*mi).second);
3369 pfrom->PushMessage("block", block);
3371 // Trigger them to send a getblocks request for the next batch of inventory
3372 if (inv.hash == pfrom->hashContinue)
3374 // ppcoin: send latest proof-of-work block to allow the
3375 // download node to accept as orphan (proof-of-stake
3376 // block might be rejected by stake connection check)
3378 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3379 pfrom->PushMessage("inv", vInv);
3380 pfrom->hashContinue = 0;
3384 else if (inv.IsKnownType())
3386 // Send stream from relay memory
3387 bool pushed = false;
3390 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3391 if (mi != mapRelay.end()) {
3392 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3396 if (!pushed && inv.type == MSG_TX) {
3398 if (mempool.exists(inv.hash)) {
3399 CTransaction tx = mempool.lookup(inv.hash);
3400 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3403 pfrom->PushMessage("tx", ss);
3408 // Track requests for our stuff
3409 Inventory(inv.hash);
3414 else if (strCommand == "getblocks")
3416 CBlockLocator locator;
3418 vRecv >> locator >> hashStop;
3420 // Find the last block the caller has in the main chain
3421 CBlockIndex* pindex = locator.GetBlockIndex();
3423 // Send the rest of the chain
3425 pindex = pindex->pnext;
3427 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3428 for (; pindex; pindex = pindex->pnext)
3430 if (pindex->GetBlockHash() == hashStop)
3432 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3433 // ppcoin: tell downloading node about the latest block if it's
3434 // without risk being rejected due to stake connection check
3435 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3436 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3439 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3442 // When this block is requested, we'll send an inv that'll make them
3443 // getblocks the next batch of inventory.
3444 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3445 pfrom->hashContinue = pindex->GetBlockHash();
3450 else if (strCommand == "checkpoint")
3452 CSyncCheckpoint checkpoint;
3453 vRecv >> checkpoint;
3455 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3458 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3460 BOOST_FOREACH(CNode* pnode, vNodes)
3461 checkpoint.RelayTo(pnode);
3465 else if (strCommand == "getheaders")
3467 CBlockLocator locator;
3469 vRecv >> locator >> hashStop;
3471 CBlockIndex* pindex = NULL;
3472 if (locator.IsNull())
3474 // If locator is null, return the hashStop block
3475 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3476 if (mi == mapBlockIndex.end())
3478 pindex = (*mi).second;
3482 // Find the last block the caller has in the main chain
3483 pindex = locator.GetBlockIndex();
3485 pindex = pindex->pnext;
3488 vector<CBlock> vHeaders;
3490 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3491 for (; pindex; pindex = pindex->pnext)
3493 vHeaders.push_back(pindex->GetBlockHeader());
3494 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3497 pfrom->PushMessage("headers", vHeaders);
3501 else if (strCommand == "tx")
3503 vector<uint256> vWorkQueue;
3504 vector<uint256> vEraseQueue;
3505 CDataStream vMsg(vRecv);
3506 CCoinsDB coinsdb("r");
3510 CInv inv(MSG_TX, tx.GetHash());
3511 pfrom->AddInventoryKnown(inv);
3513 bool fMissingInputs = false;
3514 if (tx.AcceptToMemoryPool(coinsdb, true, &fMissingInputs))
3516 SyncWithWallets(tx, NULL, true);
3517 RelayTransaction(tx, inv.hash);
3518 mapAlreadyAskedFor.erase(inv);
3519 vWorkQueue.push_back(inv.hash);
3520 vEraseQueue.push_back(inv.hash);
3522 // Recursively process any orphan transactions that depended on this one
3523 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3525 uint256 hashPrev = vWorkQueue[i];
3526 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3527 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3530 const uint256& orphanTxHash = *mi;
3531 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3532 bool fMissingInputs2 = false;
3534 if (orphanTx.AcceptToMemoryPool(coinsdb, true, &fMissingInputs2))
3536 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3537 SyncWithWallets(tx, NULL, true);
3538 RelayTransaction(orphanTx, orphanTxHash);
3539 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3540 vWorkQueue.push_back(orphanTxHash);
3541 vEraseQueue.push_back(orphanTxHash);
3543 else if (!fMissingInputs2)
3546 vEraseQueue.push_back(orphanTxHash);
3547 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3552 BOOST_FOREACH(uint256 hash, vEraseQueue)
3553 EraseOrphanTx(hash);
3555 else if (fMissingInputs)
3559 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3560 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3562 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3564 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3568 else if (strCommand == "block")
3572 uint256 hashBlock = block.GetHash();
3574 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3577 CInv inv(MSG_BLOCK, hashBlock);
3578 pfrom->AddInventoryKnown(inv);
3580 if (ProcessBlock(pfrom, &block))
3581 mapAlreadyAskedFor.erase(inv);
3582 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3586 else if (strCommand == "getaddr")
3588 // Don't return addresses older than nCutOff timestamp
3589 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3590 pfrom->vAddrToSend.clear();
3591 vector<CAddress> vAddr = addrman.GetAddr();
3592 BOOST_FOREACH(const CAddress &addr, vAddr)
3593 if(addr.nTime > nCutOff)
3594 pfrom->PushAddress(addr);
3598 else if (strCommand == "mempool")
3600 std::vector<uint256> vtxid;
3601 mempool.queryHashes(vtxid);
3603 for (unsigned int i = 0; i < vtxid.size(); i++) {
3604 CInv inv(MSG_TX, vtxid[i]);
3605 vInv.push_back(inv);
3606 if (i == (MAX_INV_SZ - 1))
3609 if (vInv.size() > 0)
3610 pfrom->PushMessage("inv", vInv);
3614 else if (strCommand == "checkorder")
3619 if (!GetBoolArg("-allowreceivebyip"))
3621 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3628 /// we have a chance to check the order here
3630 // Keep giving the same key to the same ip until they use it
3631 if (!mapReuseKey.count(pfrom->addr))
3632 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3634 // Send back approval of order and pubkey to use
3635 CScript scriptPubKey;
3636 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3637 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3641 else if (strCommand == "reply")
3646 CRequestTracker tracker;
3648 LOCK(pfrom->cs_mapRequests);
3649 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3650 if (mi != pfrom->mapRequests.end())
3652 tracker = (*mi).second;
3653 pfrom->mapRequests.erase(mi);
3656 if (!tracker.IsNull())
3657 tracker.fn(tracker.param1, vRecv);
3661 else if (strCommand == "ping")
3663 if (pfrom->nVersion > BIP0031_VERSION)
3667 // Echo the message back with the nonce. This allows for two useful features:
3669 // 1) A remote node can quickly check if the connection is operational
3670 // 2) Remote nodes can measure the latency of the network thread. If this node
3671 // is overloaded it won't respond to pings quickly and the remote node can
3672 // avoid sending us more work, like chain download requests.
3674 // The nonce stops the remote getting confused between different pings: without
3675 // it, if the remote node sends a ping once per second and this node takes 5
3676 // seconds to respond to each, the 5th ping the remote sends would appear to
3677 // return very quickly.
3678 pfrom->PushMessage("pong", nonce);
3683 else if (strCommand == "alert")
3688 uint256 alertHash = alert.GetHash();
3689 if (pfrom->setKnown.count(alertHash) == 0)
3691 if (alert.ProcessAlert())
3694 pfrom->setKnown.insert(alertHash);
3697 BOOST_FOREACH(CNode* pnode, vNodes)
3698 alert.RelayTo(pnode);
3702 // Small DoS penalty so peers that send us lots of
3703 // duplicate/expired/invalid-signature/whatever alerts
3704 // eventually get banned.
3705 // This isn't a Misbehaving(100) (immediate ban) because the
3706 // peer might be an older or different implementation with
3707 // a different signature key, etc.
3708 pfrom->Misbehaving(10);
3716 // Ignore unknown commands for extensibility
3720 // Update the last seen time for this node's address
3721 if (pfrom->fNetworkNode)
3722 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3723 AddressCurrentlyConnected(pfrom->addr);
3729 bool ProcessMessages(CNode* pfrom)
3731 CDataStream& vRecv = pfrom->vRecv;
3735 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3739 // (4) message start
3748 // Don't bother if send buffer is too full to respond anyway
3749 if (pfrom->vSend.size() >= SendBufferSize())
3752 // Scan for message start
3753 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3754 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3755 if (vRecv.end() - pstart < nHeaderSize)
3757 if ((int)vRecv.size() > nHeaderSize)
3759 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3760 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3764 if (pstart - vRecv.begin() > 0)
3765 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3766 vRecv.erase(vRecv.begin(), pstart);
3769 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3774 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3777 string strCommand = hdr.GetCommand();
3780 unsigned int nMessageSize = hdr.nMessageSize;
3781 if (nMessageSize > MAX_SIZE)
3783 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3786 if (nMessageSize > vRecv.size())
3788 // Rewind and wait for rest of message
3789 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3794 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3795 unsigned int nChecksum = 0;
3796 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3797 if (nChecksum != hdr.nChecksum)
3799 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3800 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3804 // Copy message to its own buffer
3805 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3806 vRecv.ignore(nMessageSize);
3814 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3819 catch (std::ios_base::failure& e)
3821 if (strstr(e.what(), "end of data"))
3823 // Allow exceptions from under-length message on vRecv
3824 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());
3826 else if (strstr(e.what(), "size too large"))
3828 // Allow exceptions from over-long size
3829 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3833 PrintExceptionContinue(&e, "ProcessMessages()");
3836 catch (std::exception& e) {
3837 PrintExceptionContinue(&e, "ProcessMessages()");
3839 PrintExceptionContinue(NULL, "ProcessMessages()");
3843 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3851 bool SendMessages(CNode* pto, bool fSendTrickle)
3853 TRY_LOCK(cs_main, lockMain);
3855 // Don't send anything until we get their version message
3856 if (pto->nVersion == 0)
3859 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3861 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3863 if (pto->nVersion > BIP0031_VERSION)
3864 pto->PushMessage("ping", nonce);
3866 pto->PushMessage("ping");
3869 // Resend wallet transactions that haven't gotten in a block yet
3870 ResendWalletTransactions();
3872 // Address refresh broadcast
3873 static int64 nLastRebroadcast;
3874 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3878 BOOST_FOREACH(CNode* pnode, vNodes)
3880 // Periodically clear setAddrKnown to allow refresh broadcasts
3881 if (nLastRebroadcast)
3882 pnode->setAddrKnown.clear();
3884 // Rebroadcast our address
3887 CAddress addr = GetLocalAddress(&pnode->addr);
3888 if (addr.IsRoutable())
3889 pnode->PushAddress(addr);
3893 nLastRebroadcast = GetTime();
3901 vector<CAddress> vAddr;
3902 vAddr.reserve(pto->vAddrToSend.size());
3903 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3905 // returns true if wasn't already contained in the set
3906 if (pto->setAddrKnown.insert(addr).second)
3908 vAddr.push_back(addr);
3909 // receiver rejects addr messages larger than 1000
3910 if (vAddr.size() >= 1000)
3912 pto->PushMessage("addr", vAddr);
3917 pto->vAddrToSend.clear();
3919 pto->PushMessage("addr", vAddr);
3924 // Message: inventory
3927 vector<CInv> vInvWait;
3929 LOCK(pto->cs_inventory);
3930 vInv.reserve(pto->vInventoryToSend.size());
3931 vInvWait.reserve(pto->vInventoryToSend.size());
3932 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3934 if (pto->setInventoryKnown.count(inv))
3937 // trickle out tx inv to protect privacy
3938 if (inv.type == MSG_TX && !fSendTrickle)
3940 // 1/4 of tx invs blast to all immediately
3941 static uint256 hashSalt;
3943 hashSalt = GetRandHash();
3944 uint256 hashRand = inv.hash ^ hashSalt;
3945 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3946 bool fTrickleWait = ((hashRand & 3) != 0);
3948 // always trickle our own transactions
3952 if (GetTransaction(inv.hash, wtx))
3954 fTrickleWait = true;
3959 vInvWait.push_back(inv);
3964 // returns true if wasn't already contained in the set
3965 if (pto->setInventoryKnown.insert(inv).second)
3967 vInv.push_back(inv);
3968 if (vInv.size() >= 1000)
3970 pto->PushMessage("inv", vInv);
3975 pto->vInventoryToSend = vInvWait;
3978 pto->PushMessage("inv", vInv);
3984 vector<CInv> vGetData;
3985 int64 nNow = GetTime() * 1000000;
3986 CCoinsDB coinsdb("r");
3987 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3989 const CInv& inv = (*pto->mapAskFor.begin()).second;
3990 if (!AlreadyHave(coinsdb, inv))
3993 printf("sending getdata: %s\n", inv.ToString().c_str());
3994 vGetData.push_back(inv);
3995 if (vGetData.size() >= 1000)
3997 pto->PushMessage("getdata", vGetData);
4000 mapAlreadyAskedFor[inv] = nNow;
4002 pto->mapAskFor.erase(pto->mapAskFor.begin());
4004 if (!vGetData.empty())
4005 pto->PushMessage("getdata", vGetData);
4011 // Amount compression:
4012 // * If the amount is 0, output 0
4013 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
4014 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
4015 // * call the result n
4016 // * output 1 + 10*(9*n + d - 1) + e
4017 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
4018 // (this is decodable, as d is in [1-9] and e is in [0-9])
4020 uint64 CTxOutCompressor::CompressAmount(uint64 n)
4025 while (((n % 10) == 0) && e < 9) {
4031 assert(d >= 1 && d <= 9);
4033 return 1 + (n*9 + d - 1)*10 + e;
4035 return 1 + (n - 1)*10 + 9;
4039 uint64 CTxOutCompressor::DecompressAmount(uint64 x)
4041 // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
4045 // x = 10*(9*n + d - 1) + e
4051 int d = (x % 9) + 1;