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"
12 #include "ui_interface.h"
14 #include "zerocoin/Zerocoin.h"
15 #include <boost/algorithm/string/replace.hpp>
16 #include <boost/filesystem.hpp>
17 #include <boost/filesystem/fstream.hpp>
21 using namespace boost;
27 CCriticalSection cs_setpwalletRegistered;
28 set<CWallet*> setpwalletRegistered;
30 CCriticalSection cs_main;
33 unsigned int nTransactionsUpdated = 0;
35 map<uint256, CBlockIndex*> mapBlockIndex;
36 set<pair<COutPoint, unsigned int> > setStakeSeen;
37 libzerocoin::Params* ZCParams;
39 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
40 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
41 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
42 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
43 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
45 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
47 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as zero time weight
48 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
49 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
50 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
52 int nCoinbaseMaturity = 500;
53 CBlockIndex* pindexGenesisBlock = NULL;
56 uint256 nBestChainTrust = 0;
57 uint256 nBestInvalidTrust = 0;
59 uint256 hashBestChain = 0;
60 CBlockIndex* pindexBest = NULL;
61 int64 nTimeBestReceived = 0;
63 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
65 map<uint256, CBlock*> mapOrphanBlocks;
66 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
67 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
68 map<uint256, uint256> mapProofOfStake;
70 map<uint256, CTransaction> mapOrphanTransactions;
71 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
73 // Constant stuff for coinbase transactions we create:
74 CScript COINBASE_FLAGS;
76 const string strMessageMagic = "NovaCoin Signed Message:\n";
79 int64 nTransactionFee = MIN_TX_FEE;
80 int64 nMinimumInputValue = MIN_TX_FEE;
82 extern enum Checkpoints::CPMode CheckpointsMode;
84 //////////////////////////////////////////////////////////////////////////////
86 // dispatching functions
89 // These functions dispatch to one or all registered wallets
92 void RegisterWallet(CWallet* pwalletIn)
95 LOCK(cs_setpwalletRegistered);
96 setpwalletRegistered.insert(pwalletIn);
100 void UnregisterWallet(CWallet* pwalletIn)
103 LOCK(cs_setpwalletRegistered);
104 setpwalletRegistered.erase(pwalletIn);
108 // check whether the passed transaction is from us
109 bool static IsFromMe(CTransaction& tx)
111 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
112 if (pwallet->IsFromMe(tx))
117 // get the wallet transaction with the given hash (if it exists)
118 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
120 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
121 if (pwallet->GetTransaction(hashTx,wtx))
126 // erases transaction with the given hash from all wallets
127 void static EraseFromWallets(uint256 hash)
129 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
130 pwallet->EraseFromWallet(hash);
133 // make sure all wallets know about the given transaction, in the given block
134 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
138 // ppcoin: wallets need to refund inputs when disconnecting coinstake
139 if (tx.IsCoinStake())
141 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
142 if (pwallet->IsFromMe(tx))
143 pwallet->DisableTransaction(tx);
148 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
149 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
152 // notify wallets about a new best chain
153 void static SetBestChain(const CBlockLocator& loc)
155 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
156 pwallet->SetBestChain(loc);
159 // notify wallets about an updated transaction
160 void static UpdatedTransaction(const uint256& hashTx)
162 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
163 pwallet->UpdatedTransaction(hashTx);
167 void static PrintWallets(const CBlock& block)
169 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
170 pwallet->PrintWallet(block);
173 // notify wallets about an incoming inventory (for request counts)
174 void static Inventory(const uint256& hash)
176 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
177 pwallet->Inventory(hash);
180 // ask wallets to resend their transactions
181 void ResendWalletTransactions()
183 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
184 pwallet->ResendWalletTransactions();
193 //////////////////////////////////////////////////////////////////////////////
195 // mapOrphanTransactions
198 bool AddOrphanTx(const CTransaction& tx)
200 uint256 hash = tx.GetHash();
201 if (mapOrphanTransactions.count(hash))
204 // Ignore big transactions, to avoid a
205 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
206 // large transaction with a missing parent then we assume
207 // it will rebroadcast it later, after the parent transaction(s)
208 // have been mined or received.
209 // 10,000 orphans, each of which is at most 5,000 bytes big is
210 // at most 500 megabytes of orphans:
212 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
216 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
220 mapOrphanTransactions[hash] = tx;
221 BOOST_FOREACH(const CTxIn& txin, tx.vin)
222 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
224 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
225 mapOrphanTransactions.size());
229 void static EraseOrphanTx(uint256 hash)
231 if (!mapOrphanTransactions.count(hash))
233 const CTransaction& tx = mapOrphanTransactions[hash];
234 BOOST_FOREACH(const CTxIn& txin, tx.vin)
236 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
237 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
238 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
240 mapOrphanTransactions.erase(hash);
243 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
245 unsigned int nEvicted = 0;
246 while (mapOrphanTransactions.size() > nMaxOrphans)
248 // Evict a random orphan:
249 uint256 randomhash = GetRandHash();
250 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
251 if (it == mapOrphanTransactions.end())
252 it = mapOrphanTransactions.begin();
253 EraseOrphanTx(it->first);
265 //////////////////////////////////////////////////////////////////////////////
267 // CTransaction and CTxIndex
270 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
273 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
275 if (!ReadFromDisk(txindexRet.pos))
277 if (prevout.n >= vout.size())
285 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
288 return ReadFromDisk(txdb, prevout, txindex);
291 bool CTransaction::ReadFromDisk(COutPoint prevout)
295 return ReadFromDisk(txdb, prevout, txindex);
298 bool CTransaction::IsStandard() const
300 if (nVersion > CTransaction::CURRENT_VERSION)
303 BOOST_FOREACH(const CTxIn& txin, vin)
305 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
306 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
307 // ~65-byte public keys, plus a few script ops.
308 if (txin.scriptSig.size() > 500)
310 if (!txin.scriptSig.IsPushOnly())
313 BOOST_FOREACH(const CTxOut& txout, vout) {
314 if (!::IsStandard(txout.scriptPubKey))
316 if (txout.nValue == 0)
323 // Check transaction inputs, and make sure any
324 // pay-to-script-hash transactions are evaluating IsStandard scripts
326 // Why bother? To avoid denial-of-service attacks; an attacker
327 // can submit a standard HASH... OP_EQUAL transaction,
328 // which will get accepted into blocks. The redemption
329 // script can be anything; an attacker could use a very
330 // expensive-to-check-upon-redemption script like:
331 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
333 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
336 return true; // Coinbases don't use vin normally
338 for (unsigned int i = 0; i < vin.size(); i++)
340 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
342 vector<vector<unsigned char> > vSolutions;
343 txnouttype whichType;
344 // get the scriptPubKey corresponding to this input:
345 const CScript& prevScript = prev.scriptPubKey;
346 if (!Solver(prevScript, whichType, vSolutions))
348 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
349 if (nArgsExpected < 0)
352 // Transactions with extra stuff in their scriptSigs are
353 // non-standard. Note that this EvalScript() call will
354 // be quick, because if there are any operations
355 // beside "push data" in the scriptSig the
356 // IsStandard() call returns false
357 vector<vector<unsigned char> > stack;
358 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
361 if (whichType == TX_SCRIPTHASH)
365 CScript subscript(stack.back().begin(), stack.back().end());
366 vector<vector<unsigned char> > vSolutions2;
367 txnouttype whichType2;
368 if (!Solver(subscript, whichType2, vSolutions2))
370 if (whichType2 == TX_SCRIPTHASH)
374 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
377 nArgsExpected += tmpExpected;
380 if (stack.size() != (unsigned int)nArgsExpected)
388 CTransaction::GetLegacySigOpCount() const
390 unsigned int nSigOps = 0;
391 BOOST_FOREACH(const CTxIn& txin, vin)
393 nSigOps += txin.scriptSig.GetSigOpCount(false);
395 BOOST_FOREACH(const CTxOut& txout, vout)
397 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
403 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
415 // Load the block this tx is in
417 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
419 if (!blockTmp.ReadFromDisk(txindex.pos.blockPos))
424 // Update the tx's hashBlock
425 hashBlock = pblock->GetHash();
427 // Locate the transaction
428 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
429 if (pblock->vtx[nIndex] == *(CTransaction*)this)
431 if (nIndex == (int)pblock->vtx.size())
433 vMerkleBranch.clear();
435 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
439 // Fill in merkle branch
440 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
443 // Is the tx in a block that's in the main chain
444 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
445 if (mi == mapBlockIndex.end())
447 CBlockIndex* pindex = (*mi).second;
448 if (!pindex || !pindex->IsInMainChain())
451 return pindexBest->nHeight - pindex->nHeight + 1;
460 bool CTransaction::CheckTransaction() const
462 // Basic checks that don't depend on any context
464 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
466 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
468 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
469 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
471 // Check for negative or overflow output values
473 for (unsigned int i = 0; i < vout.size(); i++)
475 const CTxOut& txout = vout[i];
476 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
477 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
479 // NovaCoin: enforce minimum output amount for user transactions until 1 May 2014 04:00:00 GMT
480 if (!fTestNet && !IsCoinBase() && !txout.IsEmpty() && nTime < OUTPUT_SWITCH_TIME && txout.nValue < MIN_TXOUT_AMOUNT)
481 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
483 if (txout.nValue > MAX_MONEY)
484 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
485 nValueOut += txout.nValue;
486 if (!MoneyRange(nValueOut))
487 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
490 // Check for duplicate inputs
491 set<COutPoint> vInOutPoints;
492 BOOST_FOREACH(const CTxIn& txin, vin)
494 if (vInOutPoints.count(txin.prevout))
496 vInOutPoints.insert(txin.prevout);
501 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
502 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
506 BOOST_FOREACH(const CTxIn& txin, vin)
507 if (txin.prevout.IsNull())
508 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
514 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
515 enum GetMinFee_mode mode, unsigned int nBytes) const
517 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
518 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
520 unsigned int nNewBlockSize = nBlockSize + nBytes;
521 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
523 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
524 if (nMinFee < nBaseFee)
526 BOOST_FOREACH(const CTxOut& txout, vout)
527 if (txout.nValue < CENT)
531 // Raise the price as the block approaches full
532 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
534 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
536 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
539 if (!MoneyRange(nMinFee))
545 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
546 bool* pfMissingInputs)
549 *pfMissingInputs = false;
551 if (!tx.CheckTransaction())
552 return error("CTxMemPool::accept() : CheckTransaction failed");
554 // Coinbase is only valid in a block, not as a loose transaction
556 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
558 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
559 if (tx.IsCoinStake())
560 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
562 // To help v0.1.5 clients who would see it as a negative number
563 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
564 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
566 // Rather not work on nonstandard transactions (unless -testnet)
567 if (!fTestNet && !tx.IsStandard())
568 return error("CTxMemPool::accept() : nonstandard transaction type");
570 // Do we already have it?
571 uint256 hash = tx.GetHash();
574 if (mapTx.count(hash))
578 if (txdb.ContainsTx(hash))
581 // Check for conflicts with in-memory transactions
582 CTransaction* ptxOld = NULL;
583 for (unsigned int i = 0; i < tx.vin.size(); i++)
585 COutPoint outpoint = tx.vin[i].prevout;
586 if (mapNextTx.count(outpoint))
588 // Disable replacement feature for now
591 // Allow replacing with a newer version of the same transaction
594 ptxOld = mapNextTx[outpoint].ptx;
595 if (ptxOld->IsFinal())
597 if (!tx.IsNewerThan(*ptxOld))
599 for (unsigned int i = 0; i < tx.vin.size(); i++)
601 COutPoint outpoint = tx.vin[i].prevout;
602 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
612 map<uint256, CTxIndex> mapUnused;
613 bool fInvalid = false;
614 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
617 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
619 *pfMissingInputs = true;
623 // Check for non-standard pay-to-script-hash in inputs
624 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
625 return error("CTxMemPool::accept() : nonstandard transaction input");
627 // Note: if you modify this code to accept non-standard transactions, then
628 // you should add code here to check that the transaction does a
629 // reasonable number of ECDSA signature verifications.
631 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
632 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
634 // Don't accept it if it can't get into a block
635 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY, nSize);
636 if (nFees < txMinFee)
637 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
638 hash.ToString().c_str(),
641 // Continuously rate-limit free transactions
642 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
643 // be annoying or make others' transactions take longer to confirm.
644 if (nFees < MIN_RELAY_TX_FEE)
646 static CCriticalSection cs;
647 static double dFreeCount;
648 static int64 nLastTime;
649 int64 nNow = GetTime();
653 // Use an exponentially decaying ~10-minute window:
654 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
656 // -limitfreerelay unit is thousand-bytes-per-minute
657 // At default rate it would take over a month to fill 1GB
658 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
659 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
661 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
666 // Check against previous transactions
667 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
668 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(true), pindexBest, false, false))
670 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
674 // Store transaction in memory
679 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
682 addUnchecked(hash, tx);
685 ///// are we sure this is ok when loading transactions or restoring block txes
686 // If updated, erase old tx from wallet
688 EraseFromWallets(ptxOld->GetHash());
690 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
691 hash.ToString().substr(0,10).c_str(),
696 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
698 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
701 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
703 // Add to memory pool without checking anything. Don't call this directly,
704 // call CTxMemPool::accept to properly check the transaction first.
707 for (unsigned int i = 0; i < tx.vin.size(); i++)
708 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
709 nTransactionsUpdated++;
715 bool CTxMemPool::remove(CTransaction &tx)
717 // Remove transaction from memory pool
720 uint256 hash = tx.GetHash();
721 if (mapTx.count(hash))
723 BOOST_FOREACH(const CTxIn& txin, tx.vin)
724 mapNextTx.erase(txin.prevout);
726 nTransactionsUpdated++;
732 void CTxMemPool::clear()
737 ++nTransactionsUpdated;
740 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
745 vtxid.reserve(mapTx.size());
746 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
747 vtxid.push_back((*mi).first);
753 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
755 if (hashBlock == 0 || nIndex == -1)
758 // Find the block it claims to be in
759 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
760 if (mi == mapBlockIndex.end())
762 CBlockIndex* pindex = (*mi).second;
763 if (!pindex || !pindex->IsInMainChain())
766 // Make sure the merkle branch connects to this block
767 if (!fMerkleVerified)
769 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
771 fMerkleVerified = true;
775 return pindexBest->nHeight - pindex->nHeight + 1;
779 int CMerkleTx::GetBlocksToMaturity() const
781 if (!(IsCoinBase() || IsCoinStake()))
783 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
787 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
791 if (!IsInMainChain() && !ClientConnectInputs())
793 return CTransaction::AcceptToMemoryPool(txdb, false);
797 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
801 bool CMerkleTx::AcceptToMemoryPool()
804 return AcceptToMemoryPool(txdb);
809 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
814 // Add previous supporting transactions first
815 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
817 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
819 uint256 hash = tx.GetHash();
820 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
821 tx.AcceptToMemoryPool(txdb, fCheckInputs);
824 return AcceptToMemoryPool(txdb, fCheckInputs);
829 bool CWalletTx::AcceptWalletTransaction()
832 return AcceptWalletTransaction(txdb);
835 int CTxIndex::GetDepthInMainChain() const
839 if (!block.ReadFromDisk(pos.blockPos, false))
841 // Find the block in the index
842 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
843 if (mi == mapBlockIndex.end())
845 CBlockIndex* pindex = (*mi).second;
846 if (!pindex || !pindex->IsInMainChain())
848 return 1 + nBestHeight - pindex->nHeight;
851 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
852 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
858 if (mempool.exists(hash))
860 tx = mempool.lookup(hash);
866 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
869 if (block.ReadFromDisk(txindex.pos.blockPos, false))
870 hashBlock = block.GetHash();
884 //////////////////////////////////////////////////////////////////////////////
886 // CBlock and CBlockIndex
889 static CBlockIndex* pblockindexFBBHLast;
890 CBlockIndex* FindBlockByHeight(int nHeight)
892 CBlockIndex *pblockindex;
893 if (nHeight < nBestHeight / 2)
894 pblockindex = pindexGenesisBlock;
896 pblockindex = pindexBest;
897 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
898 pblockindex = pblockindexFBBHLast;
899 while (pblockindex->nHeight > nHeight)
900 pblockindex = pblockindex->pprev;
901 while (pblockindex->nHeight < nHeight)
902 pblockindex = pblockindex->pnext;
903 pblockindexFBBHLast = pblockindex;
907 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
909 if (!fReadTransactions)
911 *this = pindex->GetBlockHeader();
914 if (!ReadFromDisk(pindex->GetBlockPos(), fReadTransactions))
916 if (GetHash() != pindex->GetBlockHash())
917 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
921 uint256 static GetOrphanRoot(const CBlock* pblock)
923 // Work back to the first block in the orphan chain
924 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
925 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
926 return pblock->GetHash();
929 // ppcoin: find block wanted by given orphan block
930 uint256 WantedByOrphan(const CBlock* pblockOrphan)
932 // Work back to the first block in the orphan chain
933 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
934 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
935 return pblockOrphan->hashPrevBlock;
938 // select stake target limit according to hard-coded conditions
939 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
941 if(fTestNet) // separate proof of stake target limit for testnet
942 return bnProofOfStakeLimit;
943 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
944 return bnProofOfStakeLimit;
945 if(nHeight + 1 > 15000) // 24 bits since block 15000
946 return bnProofOfStakeLegacyLimit;
947 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
948 return bnProofOfStakeHardLimit;
950 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
953 // miner's coin base reward based on nBits
954 int64 GetProofOfWorkReward(unsigned int nBits)
956 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
959 bnTarget.SetCompact(nBits);
960 CBigNum bnTargetLimit = bnProofOfWorkLimit;
961 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
963 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
964 // A reasonably continuous curve is used to avoid shock to market
965 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
967 // Human readable form:
969 // nSubsidy = 100 / (diff ^ 1/6)
970 CBigNum bnLowerBound = CENT;
971 CBigNum bnUpperBound = bnSubsidyLimit;
972 while (bnLowerBound + CENT <= bnUpperBound)
974 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
975 if (fDebug && GetBoolArg("-printcreation"))
976 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
977 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
978 bnUpperBound = bnMidValue;
980 bnLowerBound = bnMidValue;
983 int64 nSubsidy = bnUpperBound.getuint64();
985 nSubsidy = (nSubsidy / CENT) * CENT;
986 if (fDebug && GetBoolArg("-printcreation"))
987 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
989 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
992 // miner's coin stake reward based on nBits and coin age spent (coin-days)
993 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
995 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
997 if(fTestNet || nTime > STAKE_SWITCH_TIME)
999 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1001 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1003 bnTarget.SetCompact(nBits);
1004 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1005 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1007 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1009 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1010 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1011 bnMidPart, bnRewardPart;
1013 while (bnLowerBound + CENT <= bnUpperBound)
1015 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1016 if (fDebug && GetBoolArg("-printcreation"))
1017 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1019 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1022 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1024 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1026 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1029 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1030 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1035 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1037 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1039 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1042 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1043 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1046 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1047 bnUpperBound = bnMidValue;
1049 bnLowerBound = bnMidValue;
1052 nRewardCoinYear = bnUpperBound.getuint64();
1053 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1057 // Old creation amount per coin-year, 5% fixed stake mint rate
1058 nRewardCoinYear = 5 * CENT;
1062 return nRewardCoinYear;
1064 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1066 // Set reasonable reward limit for large inputs since 20 Oct 2013
1068 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1069 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1071 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1072 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1074 nSubsidy = min(nSubsidy, nSubsidyLimit);
1077 if (fDebug && GetBoolArg("-printcreation"))
1078 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1082 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1084 // get proof of work blocks max spacing according to hard-coded conditions
1085 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1087 if(nTime > TARGETS_SWITCH_TIME)
1088 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1091 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1093 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1097 // maximum nBits value could possible be required nTime after
1099 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1102 bnResult.SetCompact(nBase);
1104 while (nTime > 0 && bnResult < bnTargetLimit)
1106 // Maximum 200% adjustment per day...
1108 nTime -= 24 * 60 * 60;
1110 if (bnResult > bnTargetLimit)
1111 bnResult = bnTargetLimit;
1112 return bnResult.GetCompact();
1116 // minimum amount of work that could possibly be required nTime after
1117 // minimum proof-of-work required was nBase
1119 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1121 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1125 // minimum amount of stake that could possibly be required nTime after
1126 // minimum proof-of-stake required was nBase
1128 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1130 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1134 // ppcoin: find last block index up to pindex
1135 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1137 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1138 pindex = pindex->pprev;
1142 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1144 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1146 if (pindexLast == NULL)
1147 return bnTargetLimit.GetCompact(); // genesis block
1149 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1150 if (pindexPrev->pprev == NULL)
1151 return bnTargetLimit.GetCompact(); // first block
1152 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1153 if (pindexPrevPrev->pprev == NULL)
1154 return bnTargetLimit.GetCompact(); // second block
1156 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1158 // ppcoin: target change every block
1159 // ppcoin: retarget with exponential moving toward target spacing
1161 bnNew.SetCompact(pindexPrev->nBits);
1162 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1163 int64 nInterval = nTargetTimespan / nTargetSpacing;
1164 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1165 bnNew /= ((nInterval + 1) * nTargetSpacing);
1167 if (bnNew > bnTargetLimit)
1168 bnNew = bnTargetLimit;
1170 return bnNew.GetCompact();
1173 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1176 bnTarget.SetCompact(nBits);
1179 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1180 return error("CheckProofOfWork() : nBits below minimum work");
1182 // Check proof of work matches claimed amount
1183 if (hash > bnTarget.getuint256())
1184 return error("CheckProofOfWork() : hash doesn't match nBits");
1189 // Return maximum amount of blocks that other nodes claim to have
1190 int GetNumBlocksOfPeers()
1192 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1195 bool IsInitialBlockDownload()
1197 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1199 static int64 nLastUpdate;
1200 static CBlockIndex* pindexLastBest;
1201 if (pindexBest != pindexLastBest)
1203 pindexLastBest = pindexBest;
1204 nLastUpdate = GetTime();
1206 return (GetTime() - nLastUpdate < 10 &&
1207 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1210 void static InvalidChainFound(CBlockIndex* pindexNew)
1212 if (pindexNew->nChainTrust > nBestInvalidTrust)
1214 nBestInvalidTrust = pindexNew->nChainTrust;
1215 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1216 uiInterface.NotifyBlocksChanged();
1219 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1220 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1222 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1223 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1224 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1225 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1226 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1227 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1228 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1229 nBestBlockTrust.Get64(),
1230 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1234 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1236 nTime = max(GetBlockTime(), GetAdjustedTime());
1249 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1251 // Relinquish previous transactions' spent pointers
1254 BOOST_FOREACH(const CTxIn& txin, vin)
1256 COutPoint prevout = txin.prevout;
1258 // Get prev txindex from disk
1260 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1261 return error("DisconnectInputs() : ReadTxIndex failed");
1263 if (prevout.n >= txindex.vSpent.size())
1264 return error("DisconnectInputs() : prevout.n out of range");
1266 // Mark outpoint as not spent
1267 txindex.vSpent[prevout.n].SetNull();
1270 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1271 return error("DisconnectInputs() : UpdateTxIndex failed");
1275 // Remove transaction from index
1276 // This can fail if a duplicate of this transaction was in a chain that got
1277 // reorganized away. This is only possible if this transaction was completely
1278 // spent, so erasing it would be a no-op anyway.
1279 txdb.EraseTxIndex(*this);
1285 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1286 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1288 // FetchInputs can return false either because we just haven't seen some inputs
1289 // (in which case the transaction should be stored as an orphan)
1290 // or because the transaction is malformed (in which case the transaction should
1291 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1295 return true; // Coinbase transactions have no inputs to fetch.
1297 for (unsigned int i = 0; i < vin.size(); i++)
1299 COutPoint prevout = vin[i].prevout;
1300 if (inputsRet.count(prevout.hash))
1301 continue; // Got it already
1304 CTxIndex& txindex = inputsRet[prevout.hash].first;
1306 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1308 // Get txindex from current proposed changes
1309 txindex = mapTestPool.find(prevout.hash)->second;
1313 // Read txindex from txdb
1314 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1316 if (!fFound && (fBlock || fMiner))
1317 return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1320 CTransaction& txPrev = inputsRet[prevout.hash].second;
1321 if (!fFound || txindex.pos.IsMemPool())
1323 // Get prev tx from single transactions in memory
1326 if (!mempool.exists(prevout.hash))
1327 return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1328 txPrev = mempool.lookup(prevout.hash);
1331 txindex.vSpent.resize(txPrev.vout.size());
1335 // Get prev tx from disk
1336 if (!txPrev.ReadFromDisk(txindex.pos))
1337 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1341 // Make sure all prevout.n indexes are valid:
1342 for (unsigned int i = 0; i < vin.size(); i++)
1344 const COutPoint prevout = vin[i].prevout;
1345 assert(inputsRet.count(prevout.hash) != 0);
1346 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1347 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1348 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1350 // Revisit this if/when transaction replacement is implemented and allows
1353 return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
1360 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1362 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1363 if (mi == inputs.end())
1364 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1366 const CTransaction& txPrev = (mi->second).second;
1367 if (input.prevout.n >= txPrev.vout.size())
1368 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1370 return txPrev.vout[input.prevout.n];
1373 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1379 for (unsigned int i = 0; i < vin.size(); i++)
1381 nResult += GetOutputFor(vin[i], inputs).nValue;
1387 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1392 unsigned int nSigOps = 0;
1393 for (unsigned int i = 0; i < vin.size(); i++)
1395 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1396 if (prevout.scriptPubKey.IsPayToScriptHash())
1397 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1402 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1403 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1405 // Take over previous transactions' spent pointers
1406 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1407 // fMiner is true when called from the internal bitcoin miner
1408 // ... both are false when called from CTransaction::AcceptToMemoryPool
1413 for (unsigned int i = 0; i < vin.size(); i++)
1415 COutPoint prevout = vin[i].prevout;
1416 assert(inputs.count(prevout.hash) > 0);
1417 CTxIndex& txindex = inputs[prevout.hash].first;
1418 CTransaction& txPrev = inputs[prevout.hash].second;
1420 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1421 return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
1423 // If prev is coinbase or coinstake, check that it's matured
1424 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1425 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1426 if (pindex->GetBlockPos() == txindex.pos.blockPos)
1427 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1429 // ppcoin: check transaction timestamp
1430 if (txPrev.nTime > nTime)
1431 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1433 // Check for negative or overflow input values
1434 nValueIn += txPrev.vout[prevout.n].nValue;
1435 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1436 return DoS(100, error("ConnectInputs() : txin values out of range"));
1439 // The first loop above does all the inexpensive checks.
1440 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1441 // Helps prevent CPU exhaustion attacks.
1442 for (unsigned int i = 0; i < vin.size(); i++)
1444 COutPoint prevout = vin[i].prevout;
1445 assert(inputs.count(prevout.hash) > 0);
1446 CTxIndex& txindex = inputs[prevout.hash].first;
1447 CTransaction& txPrev = inputs[prevout.hash].second;
1449 // Check for conflicts (double-spend)
1450 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1451 // for an attacker to attempt to split the network.
1452 if (!txindex.vSpent[prevout.n].IsNull())
1453 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
1455 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1456 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1457 // still computed and checked, and any change will be caught at the next checkpoint.
1458 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1461 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1463 // only during transition phase for P2SH: do not invoke anti-DoS code for
1464 // potentially old clients relaying bad P2SH transactions
1465 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1466 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1468 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1472 // Mark outpoints as spent
1473 txindex.vSpent[prevout.n] = posThisTx;
1476 if (fBlock || fMiner)
1478 mapTestPool[prevout.hash] = txindex;
1484 // ppcoin: coin stake tx earns reward instead of paying fee
1486 if (!GetCoinAge(txdb, nCoinAge))
1487 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1489 int64 nStakeReward = GetValueOut() - nValueIn;
1490 int64 nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee() + MIN_TX_FEE;
1492 if (nStakeReward > nCalculatedStakeReward)
1493 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nStakeReward, nCalculatedStakeReward));
1497 if (nValueIn < GetValueOut())
1498 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1500 // Tally transaction fees
1501 int64 nTxFee = nValueIn - GetValueOut();
1503 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1505 // enforce transaction fees for every block until 1 May 2014 04:00:00 GMT
1506 if (!fTestNet && nTxFee < GetMinFee() && nTime < OUTPUT_SWITCH_TIME)
1507 return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false;
1510 if (!MoneyRange(nFees))
1511 return DoS(100, error("ConnectInputs() : nFees out of range"));
1519 bool CTransaction::ClientConnectInputs()
1524 // Take over previous transactions' spent pointers
1528 for (unsigned int i = 0; i < vin.size(); i++)
1530 // Get prev tx from single transactions in memory
1531 COutPoint prevout = vin[i].prevout;
1532 if (!mempool.exists(prevout.hash))
1534 CTransaction& txPrev = mempool.lookup(prevout.hash);
1536 if (prevout.n >= txPrev.vout.size())
1540 if (!VerifySignature(txPrev, *this, i, true, 0))
1541 return error("ConnectInputs() : VerifySignature failed");
1543 ///// this is redundant with the mempool.mapNextTx stuff,
1544 ///// not sure which I want to get rid of
1545 ///// this has to go away now that posNext is gone
1546 // // Check for conflicts
1547 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1548 // return error("ConnectInputs() : prev tx already used");
1550 // // Flag outpoints as used
1551 // txPrev.vout[prevout.n].posNext = posThisTx;
1553 nValueIn += txPrev.vout[prevout.n].nValue;
1555 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1556 return error("ClientConnectInputs() : txin values out of range");
1558 if (GetValueOut() > nValueIn)
1568 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1570 // Disconnect in reverse order
1571 for (int i = vtx.size()-1; i >= 0; i--)
1572 if (!vtx[i].DisconnectInputs(txdb))
1575 // Update block index on disk without changing it in memory.
1576 // The memory index structure will be changed after the db commits.
1579 CDiskBlockIndex blockindexPrev(pindex->pprev);
1580 blockindexPrev.hashNext = 0;
1581 if (!txdb.WriteBlockIndex(blockindexPrev))
1582 return error("DisconnectBlock() : WriteBlockIndex failed");
1585 // ppcoin: clean up wallet after disconnecting coinstake
1586 BOOST_FOREACH(CTransaction& tx, vtx)
1587 SyncWithWallets(tx, this, false, false);
1592 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1594 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1595 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1598 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1599 // unless those are already completely spent.
1600 // If such overwrites are allowed, coinbases and transactions depending upon those
1601 // can be duplicated to remove the ability to spend the first instance -- even after
1602 // being sent to another address.
1603 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1604 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1605 // already refuses previously-known transaction ids entirely.
1606 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1607 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1608 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1609 // initial block download.
1610 bool fEnforceBIP30 = true; // Always active in NovaCoin
1611 bool fStrictPayToScriptHash = true; // Always active in NovaCoin
1613 //// issue here: it doesn't know the version
1614 unsigned int nTxPos;
1616 // Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from
1619 nTxPos = ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1621 CBlockUndo blockundo;
1623 map<uint256, CTxIndex> mapQueuedChanges;
1626 int64 nValueOut = 0;
1627 unsigned int nSigOps = 0;
1628 BOOST_FOREACH(CTransaction& tx, vtx)
1630 uint256 hashTx = tx.GetHash();
1632 if (fEnforceBIP30) {
1633 CTxIndex txindexOld;
1634 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1635 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1641 nSigOps += tx.GetLegacySigOpCount();
1642 if (nSigOps > MAX_BLOCK_SIGOPS)
1643 return DoS(100, error("ConnectBlock() : too many sigops"));
1645 CDiskTxPos posThisTx(pindex->GetBlockPos(), nTxPos);
1647 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1649 MapPrevTx mapInputs;
1650 if (tx.IsCoinBase())
1651 nValueOut += tx.GetValueOut();
1657 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1660 if (fStrictPayToScriptHash)
1662 // Add in sigops done by pay-to-script-hash inputs;
1663 // this is to prevent a "rogue miner" from creating
1664 // an incredibly-expensive-to-validate block.
1665 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1666 if (nSigOps > MAX_BLOCK_SIGOPS)
1667 return DoS(100, error("ConnectBlock() : too many sigops"));
1670 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1671 int64 nTxValueOut = tx.GetValueOut();
1672 nValueIn += nTxValueIn;
1673 nValueOut += nTxValueOut;
1674 if (!tx.IsCoinStake())
1675 nFees += nTxValueIn - nTxValueOut;
1678 BOOST_FOREACH(const CTxIn &in, tx.vin) {
1679 undo.vprevout.push_back(CTxInUndo(mapInputs[in.prevout.hash].second.vout[in.prevout.n], pindex->nHeight));
1682 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1685 blockundo.vtxundo.push_back(undo);
1688 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1691 // ppcoin: track money supply and mint amount info
1692 pindex->nMint = nValueOut - nValueIn + nFees;
1693 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1694 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1695 return error("Connect() : WriteBlockIndex for pindex failed");
1697 // ppcoin: fees are not collected by miners as in bitcoin
1698 // ppcoin: fees are destroyed to compensate the entire network
1699 if (fDebug && GetBoolArg("-printcreation"))
1700 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1705 // Write queued txindex changes
1706 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1708 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1709 return error("ConnectBlock() : UpdateTxIndex failed");
1712 // Update block index on disk without changing it in memory.
1713 // The memory index structure will be changed after the db commits.
1716 CDiskBlockIndex blockindexPrev(pindex->pprev);
1717 blockindexPrev.hashNext = pindex->GetBlockHash();
1718 if (!txdb.WriteBlockIndex(blockindexPrev))
1719 return error("ConnectBlock() : WriteBlockIndex failed");
1722 // Write undo information to disk
1723 if (pindex->nHeight > Checkpoints::GetTotalBlocksEstimate())
1725 CAutoFile fileUndo(fopen(pindex->GetBlockPos().GetUndoFile(GetDataDir()).string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
1726 fileUndo << blockundo;
1729 // Watch for transactions paying to me
1730 BOOST_FOREACH(CTransaction& tx, vtx)
1731 SyncWithWallets(tx, this, true);
1736 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1738 printf("REORGANIZE\n");
1741 CBlockIndex* pfork = pindexBest;
1742 CBlockIndex* plonger = pindexNew;
1743 while (pfork != plonger)
1745 while (plonger->nHeight > pfork->nHeight)
1746 if (!(plonger = plonger->pprev))
1747 return error("Reorganize() : plonger->pprev is null");
1748 if (pfork == plonger)
1750 if (!(pfork = pfork->pprev))
1751 return error("Reorganize() : pfork->pprev is null");
1754 // List of what to disconnect
1755 vector<CBlockIndex*> vDisconnect;
1756 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1757 vDisconnect.push_back(pindex);
1759 // List of what to connect
1760 vector<CBlockIndex*> vConnect;
1761 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1762 vConnect.push_back(pindex);
1763 reverse(vConnect.begin(), vConnect.end());
1765 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());
1766 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());
1768 // Disconnect shorter branch
1769 vector<CTransaction> vResurrect;
1770 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1773 if (!block.ReadFromDisk(pindex))
1774 return error("Reorganize() : ReadFromDisk for disconnect failed");
1775 if (!block.DisconnectBlock(txdb, pindex))
1776 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1778 // Queue memory transactions to resurrect
1779 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1780 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1781 vResurrect.push_back(tx);
1784 // Connect longer branch
1785 vector<CTransaction> vDelete;
1786 for (unsigned int i = 0; i < vConnect.size(); i++)
1788 CBlockIndex* pindex = vConnect[i];
1790 if (!block.ReadFromDisk(pindex))
1791 return error("Reorganize() : ReadFromDisk for connect failed");
1792 if (!block.ConnectBlock(txdb, pindex))
1795 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1798 // Queue memory transactions to delete
1799 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1800 vDelete.push_back(tx);
1802 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1803 return error("Reorganize() : WriteHashBestChain failed");
1805 // Make sure it's successfully written to disk before changing memory structure
1806 if (!txdb.TxnCommit())
1807 return error("Reorganize() : TxnCommit failed");
1809 // Disconnect shorter branch
1810 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1812 pindex->pprev->pnext = NULL;
1814 // Connect longer branch
1815 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1817 pindex->pprev->pnext = pindex;
1819 // Resurrect memory transactions that were in the disconnected branch
1820 BOOST_FOREACH(CTransaction& tx, vResurrect)
1821 tx.AcceptToMemoryPool(txdb, false);
1823 // Delete redundant memory transactions that are in the connected branch
1824 BOOST_FOREACH(CTransaction& tx, vDelete)
1827 printf("REORGANIZE: done\n");
1833 // Called from inside SetBestChain: attaches a block to the new best chain being built
1834 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1836 uint256 hash = GetHash();
1838 // Adding to current best branch
1839 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1842 InvalidChainFound(pindexNew);
1845 if (!txdb.TxnCommit())
1846 return error("SetBestChain() : TxnCommit failed");
1848 // Add to current best branch
1849 pindexNew->pprev->pnext = pindexNew;
1851 // Delete redundant memory transactions
1852 BOOST_FOREACH(CTransaction& tx, vtx)
1858 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1860 uint256 hash = GetHash();
1862 if (!txdb.TxnBegin())
1863 return error("SetBestChain() : TxnBegin failed");
1865 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1867 txdb.WriteHashBestChain(hash);
1868 if (!txdb.TxnCommit())
1869 return error("SetBestChain() : TxnCommit failed");
1870 pindexGenesisBlock = pindexNew;
1872 else if (hashPrevBlock == hashBestChain)
1874 if (!SetBestChainInner(txdb, pindexNew))
1875 return error("SetBestChain() : SetBestChainInner failed");
1879 // the first block in the new chain that will cause it to become the new best chain
1880 CBlockIndex *pindexIntermediate = pindexNew;
1882 // list of blocks that need to be connected afterwards
1883 std::vector<CBlockIndex*> vpindexSecondary;
1885 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1886 // Try to limit how much needs to be done inside
1887 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1889 vpindexSecondary.push_back(pindexIntermediate);
1890 pindexIntermediate = pindexIntermediate->pprev;
1893 if (!vpindexSecondary.empty())
1894 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1896 // Switch to new best branch
1897 if (!Reorganize(txdb, pindexIntermediate))
1900 InvalidChainFound(pindexNew);
1901 return error("SetBestChain() : Reorganize failed");
1904 // Connect further blocks
1905 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1908 if (!block.ReadFromDisk(pindex))
1910 printf("SetBestChain() : ReadFromDisk failed\n");
1913 if (!txdb.TxnBegin()) {
1914 printf("SetBestChain() : TxnBegin 2 failed\n");
1917 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1918 if (!block.SetBestChainInner(txdb, pindex))
1923 // Update best block in wallet (so we can detect restored wallets)
1924 bool fIsInitialDownload = IsInitialBlockDownload();
1925 if (!fIsInitialDownload)
1927 const CBlockLocator locator(pindexNew);
1928 ::SetBestChain(locator);
1932 hashBestChain = hash;
1933 pindexBest = pindexNew;
1934 pblockindexFBBHLast = NULL;
1935 nBestHeight = pindexBest->nHeight;
1936 nBestChainTrust = pindexNew->nChainTrust;
1937 nTimeBestReceived = GetTime();
1938 nTransactionsUpdated++;
1940 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1942 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1943 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1944 CBigNum(nBestChainTrust).ToString().c_str(),
1945 nBestBlockTrust.Get64(),
1946 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1948 // Check the version of the last 100 blocks to see if we need to upgrade:
1949 if (!fIsInitialDownload)
1952 const CBlockIndex* pindex = pindexBest;
1953 for (int i = 0; i < 100 && pindex != NULL; i++)
1955 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1957 pindex = pindex->pprev;
1960 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1961 if (nUpgraded > 100/2)
1962 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1963 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1966 std::string strCmd = GetArg("-blocknotify", "");
1968 if (!fIsInitialDownload && !strCmd.empty())
1970 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1971 boost::thread t(runCommand, strCmd); // thread runs free
1977 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1978 // Only those coins meeting minimum age requirement counts. As those
1979 // transactions not in main chain are not currently indexed so we
1980 // might not find out about their coin age. Older transactions are
1981 // guaranteed to be in main chain by sync-checkpoint. This rule is
1982 // introduced to help nodes establish a consistent view of the coin
1983 // age (trust score) of competing branches.
1984 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1986 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1992 BOOST_FOREACH(const CTxIn& txin, vin)
1994 // First try finding the previous transaction in database
1995 CTransaction txPrev;
1997 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1998 continue; // previous transaction not in main chain
1999 if (nTime < txPrev.nTime)
2000 return false; // Transaction timestamp violation
2002 // Read block header
2004 if (!block.ReadFromDisk(txindex.pos.blockPos, false))
2005 return false; // unable to read block of previous transaction
2006 if (block.GetBlockTime() + nStakeMinAge > nTime)
2007 continue; // only count coins meeting min age requirement
2009 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2010 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2012 if (fDebug && GetBoolArg("-printcoinage"))
2013 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2016 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
2017 if (fDebug && GetBoolArg("-printcoinage"))
2018 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2019 nCoinAge = bnCoinDay.getuint64();
2023 // ppcoin: total coin age spent in block, in the unit of coin-days.
2024 bool CBlock::GetCoinAge(uint64& nCoinAge) const
2029 BOOST_FOREACH(const CTransaction& tx, vtx)
2032 if (tx.GetCoinAge(txdb, nTxCoinAge))
2033 nCoinAge += nTxCoinAge;
2038 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2040 if (fDebug && GetBoolArg("-printcoinage"))
2041 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
2045 bool CBlock::AddToBlockIndex(const CDiskBlockPos &pos)
2047 // Check for duplicate
2048 uint256 hash = GetHash();
2049 if (mapBlockIndex.count(hash))
2050 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2052 // Construct new block index object
2053 CBlockIndex* pindexNew = new CBlockIndex(*this);
2055 return error("AddToBlockIndex() : new CBlockIndex failed");
2056 pindexNew->phashBlock = &hash;
2057 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2058 if (miPrev != mapBlockIndex.end())
2060 pindexNew->pprev = (*miPrev).second;
2061 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2064 // ppcoin: compute chain trust score
2065 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2067 assert(pos.nHeight == pindexNew->nHeight);
2068 pindexNew->nAlternative = pos.nAlternative;
2070 // ppcoin: compute stake entropy bit for stake modifier
2071 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2072 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2074 // ppcoin: record proof-of-stake hash value
2075 if (pindexNew->IsProofOfStake())
2077 if (!mapProofOfStake.count(hash))
2078 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2079 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2082 // ppcoin: compute stake modifier
2083 uint64 nStakeModifier = 0;
2084 bool fGeneratedStakeModifier = false;
2085 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2086 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2087 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2088 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2089 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2090 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2092 // Add to mapBlockIndex
2093 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2094 if (pindexNew->IsProofOfStake())
2095 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2096 pindexNew->phashBlock = &((*mi).first);
2098 // Write to disk block index
2100 if (!txdb.TxnBegin())
2102 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2103 if (!txdb.TxnCommit())
2107 if (pindexNew->nChainTrust > nBestChainTrust)
2108 if (!SetBestChain(txdb, pindexNew))
2111 if (pindexNew == pindexBest)
2113 // Notify UI to display prev block's coinbase if it was ours
2114 static uint256 hashPrevBestCoinBase;
2115 UpdatedTransaction(hashPrevBestCoinBase);
2116 hashPrevBestCoinBase = vtx[0].GetHash();
2119 uiInterface.NotifyBlocksChanged();
2126 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2128 // These are checks that are independent of context
2129 // that can be verified before saving an orphan block.
2132 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2133 return DoS(100, error("CheckBlock() : size limits failed"));
2135 // Check proof of work matches claimed amount
2136 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2137 return DoS(50, error("CheckBlock() : proof of work failed"));
2140 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2141 return error("CheckBlock() : block timestamp too far in the future");
2143 // First transaction must be coinbase, the rest must not be
2144 if (vtx.empty() || !vtx[0].IsCoinBase())
2145 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2146 for (unsigned int i = 1; i < vtx.size(); i++)
2147 if (vtx[i].IsCoinBase())
2148 return DoS(100, error("CheckBlock() : more than one coinbase"));
2150 // Check coinbase timestamp
2151 if (GetBlockTime() > FutureDrift((int64)vtx[0].nTime))
2152 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2154 if (IsProofOfStake())
2156 // Coinbase output should be empty if proof-of-stake block
2157 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2158 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2160 // Second transaction must be coinstake, the rest must not be
2161 if (vtx.empty() || !vtx[1].IsCoinStake())
2162 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2163 for (unsigned int i = 2; i < vtx.size(); i++)
2164 if (vtx[i].IsCoinStake())
2165 return DoS(100, error("CheckBlock() : more than one coinstake"));
2167 // Check coinstake timestamp
2168 if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2169 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2171 // NovaCoin: check proof-of-stake block signature
2172 if (fCheckSig && !CheckBlockSignature(true))
2173 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2177 int64 nReward = GetProofOfWorkReward(nBits);
2178 // Check coinbase reward
2179 if (vtx[0].GetValueOut() > nReward)
2180 return DoS(50, error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
2181 vtx[0].GetValueOut(),
2184 // Should we check proof-of-work block signature or not?
2186 // * Always skip on TestNet
2187 // * Perform checking for the first 9689 blocks
2188 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2190 if(!fTestNet && fCheckSig)
2192 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2194 // NovaCoin: check proof-of-work block signature
2195 if (checkEntropySig && !CheckBlockSignature(false))
2196 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2200 // Check transactions
2201 BOOST_FOREACH(const CTransaction& tx, vtx)
2203 if (!tx.CheckTransaction())
2204 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2206 // ppcoin: check transaction timestamp
2207 if (GetBlockTime() < (int64)tx.nTime)
2208 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2211 // Check for duplicate txids. This is caught by ConnectInputs(),
2212 // but catching it earlier avoids a potential DoS attack:
2213 set<uint256> uniqueTx;
2214 BOOST_FOREACH(const CTransaction& tx, vtx)
2216 uniqueTx.insert(tx.GetHash());
2218 if (uniqueTx.size() != vtx.size())
2219 return DoS(100, error("CheckBlock() : duplicate transaction"));
2221 unsigned int nSigOps = 0;
2222 BOOST_FOREACH(const CTransaction& tx, vtx)
2224 nSigOps += tx.GetLegacySigOpCount();
2226 if (nSigOps > MAX_BLOCK_SIGOPS)
2227 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2229 // Check merkle root
2230 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2231 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2237 bool CBlock::AcceptBlock()
2239 // Check for duplicate
2240 uint256 hash = GetHash();
2241 if (mapBlockIndex.count(hash))
2242 return error("AcceptBlock() : block already in mapBlockIndex");
2244 // Get prev block index
2245 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2246 if (mi == mapBlockIndex.end())
2247 return DoS(10, error("AcceptBlock() : prev block not found"));
2248 CBlockIndex* pindexPrev = (*mi).second;
2249 int nHeight = pindexPrev->nHeight+1;
2251 // Check proof-of-work or proof-of-stake
2252 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2253 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2255 // Check timestamp against prev
2256 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2257 return error("AcceptBlock() : block's timestamp is too early");
2259 // Check that all transactions are finalized
2260 BOOST_FOREACH(const CTransaction& tx, vtx)
2261 if (!tx.IsFinal(nHeight, GetBlockTime()))
2262 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2264 // Check that the block chain matches the known block chain up to a checkpoint
2265 if (!Checkpoints::CheckHardened(nHeight, hash))
2266 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2268 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2270 // Check that the block satisfies synchronized checkpoint
2271 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2272 return error("AcceptBlock() : rejected by synchronized checkpoint");
2274 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2275 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2277 // Enforce rule that the coinbase starts with serialized block height
2278 CScript expect = CScript() << nHeight;
2279 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2280 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2281 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2283 // Write block to history file
2284 CDiskBlockPos blockPos = CDiskBlockPos(nHeight);
2285 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2286 return error("AcceptBlock() : out of disk space");
2287 if (!WriteToDisk(blockPos))
2288 return error("AcceptBlock() : WriteToDisk failed");
2289 if (!AddToBlockIndex(blockPos))
2290 return error("AcceptBlock() : AddToBlockIndex failed");
2292 // Relay inventory, but don't relay old inventory during initial block download
2293 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2294 if (hashBestChain == hash)
2297 BOOST_FOREACH(CNode* pnode, vNodes)
2298 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2299 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2302 // ppcoin: check pending sync-checkpoint
2303 Checkpoints::AcceptPendingSyncCheckpoint();
2308 uint256 CBlockIndex::GetBlockTrust() const
2311 bnTarget.SetCompact(nBits);
2317 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2318 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2322 // Calculate work amount for block
2323 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2325 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2326 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2328 // Return nPoWTrust for the first 12 blocks
2329 if (pprev == NULL || pprev->nHeight < 12)
2332 const CBlockIndex* currentIndex = pprev;
2334 if(IsProofOfStake())
2336 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2338 // Return 1/3 of score if parent block is not the PoW block
2339 if (!pprev->IsProofOfWork())
2340 return (bnNewTrust / 3).getuint256();
2344 // Check last 12 blocks type
2345 while (pprev->nHeight - currentIndex->nHeight < 12)
2347 if (currentIndex->IsProofOfWork())
2349 currentIndex = currentIndex->pprev;
2352 // Return 1/3 of score if less than 3 PoW blocks found
2354 return (bnNewTrust / 3).getuint256();
2356 return bnNewTrust.getuint256();
2360 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2362 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2363 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2364 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2368 // Check last 12 blocks type
2369 while (pprev->nHeight - currentIndex->nHeight < 12)
2371 if (currentIndex->IsProofOfStake())
2373 currentIndex = currentIndex->pprev;
2376 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2378 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2380 bnTarget.SetCompact(pprev->nBits);
2385 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2387 // Return nPoWTrust + full trust score for previous block nBits
2388 return nPoWTrust + bnNewTrust.getuint256();
2392 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2394 unsigned int nFound = 0;
2395 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2397 if (pstart->nVersion >= minVersion)
2399 pstart = pstart->pprev;
2401 return (nFound >= nRequired);
2404 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2406 // Check for duplicate
2407 uint256 hash = pblock->GetHash();
2408 if (mapBlockIndex.count(hash))
2409 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2410 if (mapOrphanBlocks.count(hash))
2411 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2413 // ppcoin: check proof-of-stake
2414 // Limited duplicity on stake: prevents block flood attack
2415 // Duplicate stake allowed only when there is orphan child block
2416 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2417 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());
2419 // Preliminary checks
2420 if (!pblock->CheckBlock())
2421 return error("ProcessBlock() : CheckBlock FAILED");
2423 // ppcoin: verify hash target and signature of coinstake tx
2424 if (pblock->IsProofOfStake())
2426 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2427 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2429 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2430 return false; // do not error here as we expect this during initial block download
2432 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2433 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2436 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2437 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2439 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2440 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2442 bnNewBlock.SetCompact(pblock->nBits);
2445 if (pblock->IsProofOfStake())
2446 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2448 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2450 if (bnNewBlock > bnRequired)
2453 pfrom->Misbehaving(100);
2454 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2458 // ppcoin: ask for pending sync-checkpoint if any
2459 if (!IsInitialBlockDownload())
2460 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2462 // If don't already have its previous block, shunt it off to holding area until we get it
2463 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2465 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2466 CBlock* pblock2 = new CBlock(*pblock);
2467 // ppcoin: check proof-of-stake
2468 if (pblock2->IsProofOfStake())
2470 // Limited duplicity on stake: prevents block flood attack
2471 // Duplicate stake allowed only when there is orphan child block
2472 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2473 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());
2475 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2477 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2478 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2480 // Ask this guy to fill in what we're missing
2483 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2484 // ppcoin: getblocks may not obtain the ancestor block rejected
2485 // earlier by duplicate-stake check so we ask for it again directly
2486 if (!IsInitialBlockDownload())
2487 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2493 if (!pblock->AcceptBlock())
2494 return error("ProcessBlock() : AcceptBlock FAILED");
2496 // Recursively process any orphan blocks that depended on this one
2497 vector<uint256> vWorkQueue;
2498 vWorkQueue.push_back(hash);
2499 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2501 uint256 hashPrev = vWorkQueue[i];
2502 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2503 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2506 CBlock* pblockOrphan = (*mi).second;
2507 if (pblockOrphan->AcceptBlock())
2508 vWorkQueue.push_back(pblockOrphan->GetHash());
2509 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2510 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2511 delete pblockOrphan;
2513 mapOrphanBlocksByPrev.erase(hashPrev);
2516 printf("ProcessBlock: ACCEPTED\n");
2518 // ppcoin: if responsible for sync-checkpoint send it
2519 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2520 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2525 // novacoin: attempt to generate suitable proof-of-stake
2526 bool CBlock::SignBlock(CWallet& wallet)
2528 // if we are trying to sign
2529 // something except proof-of-stake block template
2530 if (!vtx[0].vout[0].IsEmpty())
2533 // if we are trying to sign
2534 // a complete proof-of-stake block
2535 if (IsProofOfStake())
2538 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2541 CTransaction txCoinStake;
2542 int64 nSearchTime = txCoinStake.nTime; // search to current time
2544 if (nSearchTime > nLastCoinStakeSearchTime)
2546 if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2548 if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2550 // make sure coinstake would meet timestamp protocol
2551 // as it would be the same as the block timestamp
2552 vtx[0].nTime = nTime = txCoinStake.nTime;
2553 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2554 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2556 // we have to make sure that we have no future timestamps in
2557 // our transactions set
2558 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2559 if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2561 vtx.insert(vtx.begin() + 1, txCoinStake);
2562 hashMerkleRoot = BuildMerkleTree();
2564 // append a signature to our block
2565 return key.Sign(GetHash(), vchBlockSig);
2568 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2569 nLastCoinStakeSearchTime = nSearchTime;
2575 // ppcoin: check block signature
2576 bool CBlock::CheckBlockSignature(bool fProofOfStake) const
2578 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2579 return vchBlockSig.empty();
2581 vector<valtype> vSolutions;
2582 txnouttype whichType;
2586 const CTxOut& txout = vtx[1].vout[1];
2588 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2590 if (whichType == TX_PUBKEY)
2592 valtype& vchPubKey = vSolutions[0];
2594 if (!key.SetPubKey(vchPubKey))
2596 if (vchBlockSig.empty())
2598 return key.Verify(GetHash(), vchBlockSig);
2603 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2605 const CTxOut& txout = vtx[0].vout[i];
2607 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2610 if (whichType == TX_PUBKEY)
2613 valtype& vchPubKey = vSolutions[0];
2615 if (!key.SetPubKey(vchPubKey))
2617 if (vchBlockSig.empty())
2619 if(!key.Verify(GetHash(), vchBlockSig))
2629 bool CheckDiskSpace(uint64 nAdditionalBytes)
2631 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2633 // Check for nMinDiskSpace bytes (currently 50MB)
2634 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2637 string strMessage = _("Warning: Disk space is low!");
2638 strMiscWarning = strMessage;
2639 printf("*** %s\n", strMessage.c_str());
2640 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2648 FILE* OpenBlockFile(const CDiskBlockPos &pos, const char* pszMode)
2650 boost::filesystem::path path = pos.GetFileName(GetDataDir());
2651 boost::filesystem::create_directories(path.parent_path());
2652 if (pos.IsNull() || pos.IsMemPool())
2654 FILE* file = fopen(path.string().c_str(), pszMode);
2660 bool LoadBlockIndex(bool fAllowNew)
2662 CBigNum bnTrustedModulus;
2666 pchMessageStart[0] = 0xcd;
2667 pchMessageStart[1] = 0xf2;
2668 pchMessageStart[2] = 0xc0;
2669 pchMessageStart[3] = 0xef;
2671 bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
2672 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2673 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2674 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2675 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2676 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2680 bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
2683 // Set up the Zerocoin Params object
2684 ZCParams = new libzerocoin::Params(bnTrustedModulus);
2690 if (!txdb.LoadBlockIndex())
2694 // Init with genesis block
2696 if (mapBlockIndex.empty())
2705 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2706 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2707 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2709 // vMerkleTree: 4cb33b3b6a
2713 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2714 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2715 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2717 // vMerkleTree: 4cb33b3b6a
2719 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2721 txNew.nTime = 1360105017;
2722 txNew.vin.resize(1);
2723 txNew.vout.resize(1);
2724 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2725 txNew.vout[0].SetEmpty();
2727 block.vtx.push_back(txNew);
2728 block.hashPrevBlock = 0;
2729 block.hashMerkleRoot = block.BuildMerkleTree();
2731 block.nTime = 1360105017;
2732 block.nBits = bnProofOfWorkLimit.GetCompact();
2733 block.nNonce = !fTestNet ? 1575379 : 46534;
2736 uint256 hash = block.GetHash();
2737 printf("%s\n", hash.ToString().c_str());
2738 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2740 assert(hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2741 assert(block.CheckBlock());
2743 // Start new block file
2744 CDiskBlockPos blockPos(0);
2745 if (!block.WriteToDisk(blockPos))
2746 return error("LoadBlockIndex() : writing genesis block to disk failed");
2747 if (!block.AddToBlockIndex(blockPos))
2748 return error("LoadBlockIndex() : genesis block not accepted");
2750 // ppcoin: initialize synchronized checkpoint
2751 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2752 return error("LoadBlockIndex() : failed to init sync checkpoint");
2755 string strPubKey = "";
2757 // if checkpoint master key changed must reset sync-checkpoint
2758 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2760 // write checkpoint master key to db
2762 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2763 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2764 if (!txdb.TxnCommit())
2765 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2766 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2767 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2775 void PrintBlockTree()
2777 // pre-compute tree structure
2778 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2779 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2781 CBlockIndex* pindex = (*mi).second;
2782 mapNext[pindex->pprev].push_back(pindex);
2784 //while (rand() % 3 == 0)
2785 // mapNext[pindex->pprev].push_back(pindex);
2788 vector<pair<int, CBlockIndex*> > vStack;
2789 vStack.push_back(make_pair(0, pindexGenesisBlock));
2792 while (!vStack.empty())
2794 int nCol = vStack.back().first;
2795 CBlockIndex* pindex = vStack.back().second;
2798 // print split or gap
2799 if (nCol > nPrevCol)
2801 for (int i = 0; i < nCol-1; i++)
2805 else if (nCol < nPrevCol)
2807 for (int i = 0; i < nCol; i++)
2814 for (int i = 0; i < nCol; i++)
2819 block.ReadFromDisk(pindex);
2820 printf("%d (%s) %s %08x %s mint %7s tx %"PRIszu"",
2822 pindex->GetBlockPos().GetFileName("").string().c_str(),
2823 block.GetHash().ToString().c_str(),
2825 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2826 FormatMoney(pindex->nMint).c_str(),
2829 PrintWallets(block);
2831 // put the main time-chain first
2832 vector<CBlockIndex*>& vNext = mapNext[pindex];
2833 for (unsigned int i = 0; i < vNext.size(); i++)
2835 if (vNext[i]->pnext)
2837 swap(vNext[0], vNext[i]);
2843 for (unsigned int i = 0; i < vNext.size(); i++)
2844 vStack.push_back(make_pair(nCol+i, vNext[i]));
2848 bool LoadExternalBlockFile(FILE* fileIn)
2850 int64 nStart = GetTimeMillis();
2856 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2857 unsigned int nPos = 0;
2858 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2860 unsigned char pchData[65536];
2862 fseek(blkdat, nPos, SEEK_SET);
2863 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2866 nPos = (unsigned int)-1;
2869 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2872 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2874 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2877 nPos += ((unsigned char*)nFind - pchData) + 1;
2880 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2881 } while(!fRequestShutdown);
2882 if (nPos == (unsigned int)-1)
2884 fseek(blkdat, nPos, SEEK_SET);
2887 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2891 if (ProcessBlock(NULL,&block))
2899 catch (std::exception &e) {
2900 printf("%s() : Deserialize or I/O error caught during load\n",
2901 __PRETTY_FUNCTION__);
2904 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2908 //////////////////////////////////////////////////////////////////////////////
2913 extern map<uint256, CAlert> mapAlerts;
2914 extern CCriticalSection cs_mapAlerts;
2916 extern string strMintMessage;
2917 extern string strMintWarning;
2919 string GetWarnings(string strFor)
2922 string strStatusBar;
2925 if (GetBoolArg("-testsafemode"))
2928 // ppcoin: wallet lock warning for minting
2929 if (strMintWarning != "")
2932 strStatusBar = strMintWarning;
2935 // Misc warnings like out of disk space and clock is wrong
2936 if (strMiscWarning != "")
2939 strStatusBar = strMiscWarning;
2942 // * Should not enter safe mode for longer invalid chain
2943 // * If sync-checkpoint is too old do not enter safe mode
2944 // * Display warning only in the STRICT mode
2945 if (CheckpointsMode == Checkpoints::STRICT && Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) &&
2946 !fTestNet && !IsInitialBlockDownload())
2949 strStatusBar = _("WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.");
2952 // ppcoin: if detected invalid checkpoint enter safe mode
2953 if (Checkpoints::hashInvalidCheckpoint != 0)
2956 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
2962 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2964 const CAlert& alert = item.second;
2965 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2967 nPriority = alert.nPriority;
2968 strStatusBar = alert.strStatusBar;
2969 if (nPriority > 1000)
2970 strRPC = strStatusBar;
2975 if (strFor == "statusbar")
2976 return strStatusBar;
2977 else if (strFor == "rpc")
2979 assert(!"GetWarnings() : invalid parameter");
2990 //////////////////////////////////////////////////////////////////////////////
2996 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3002 bool txInMap = false;
3005 txInMap = (mempool.exists(inv.hash));
3008 mapOrphanTransactions.count(inv.hash) ||
3009 txdb.ContainsTx(inv.hash);
3013 return mapBlockIndex.count(inv.hash) ||
3014 mapOrphanBlocks.count(inv.hash);
3016 // Don't know what it is, just say we already got one
3023 // The message start string is designed to be unlikely to occur in normal data.
3024 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3025 // a large 4-byte int at any alignment.
3026 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3028 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3030 static map<CService, CPubKey> mapReuseKey;
3031 RandAddSeedPerfmon();
3033 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3034 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3036 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3040 if (strCommand == "version")
3042 // Each connection can only send one version message
3043 if (pfrom->nVersion != 0)
3045 pfrom->Misbehaving(1);
3053 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3054 if (pfrom->nVersion < MIN_PROTO_VERSION)
3056 // Since February 20, 2012, the protocol is initiated at version 209,
3057 // and earlier versions are no longer supported
3058 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3059 pfrom->fDisconnect = true;
3063 if (pfrom->nVersion == 10300)
3064 pfrom->nVersion = 300;
3066 vRecv >> addrFrom >> nNonce;
3068 vRecv >> pfrom->strSubVer;
3070 vRecv >> pfrom->nStartingHeight;
3072 if (pfrom->fInbound && addrMe.IsRoutable())
3074 pfrom->addrLocal = addrMe;
3078 // Disconnect if we connected to ourself
3079 if (nNonce == nLocalHostNonce && nNonce > 1)
3081 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3082 pfrom->fDisconnect = true;
3086 // record my external IP reported by peer
3087 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3088 addrSeenByPeer = addrMe;
3090 // Be shy and don't send version until we hear
3091 if (pfrom->fInbound)
3092 pfrom->PushVersion();
3094 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3096 AddTimeData(pfrom->addr, nTime);
3099 pfrom->PushMessage("verack");
3100 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3102 if (!pfrom->fInbound)
3104 // Advertise our address
3105 if (!fNoListen && !IsInitialBlockDownload())
3107 CAddress addr = GetLocalAddress(&pfrom->addr);
3108 if (addr.IsRoutable())
3109 pfrom->PushAddress(addr);
3112 // Get recent addresses
3113 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3115 pfrom->PushMessage("getaddr");
3116 pfrom->fGetAddr = true;
3118 addrman.Good(pfrom->addr);
3120 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3122 addrman.Add(addrFrom, addrFrom);
3123 addrman.Good(addrFrom);
3127 // Ask the first connected node for block updates
3128 static int nAskedForBlocks = 0;
3129 if (!pfrom->fClient && !pfrom->fOneShot &&
3130 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3131 (pfrom->nVersion < NOBLKS_VERSION_START ||
3132 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3133 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3136 pfrom->PushGetBlocks(pindexBest, uint256(0));
3142 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3143 item.second.RelayTo(pfrom);
3146 // Relay sync-checkpoint
3148 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3149 if (!Checkpoints::checkpointMessage.IsNull())
3150 Checkpoints::checkpointMessage.RelayTo(pfrom);
3153 pfrom->fSuccessfullyConnected = true;
3155 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());
3157 cPeerBlockCounts.input(pfrom->nStartingHeight);
3159 // ppcoin: ask for pending sync-checkpoint if any
3160 if (!IsInitialBlockDownload())
3161 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3165 else if (pfrom->nVersion == 0)
3167 // Must have a version message before anything else
3168 pfrom->Misbehaving(1);
3173 else if (strCommand == "verack")
3175 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3179 else if (strCommand == "addr")
3181 vector<CAddress> vAddr;
3184 // Don't want addr from older versions unless seeding
3185 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3187 if (vAddr.size() > 1000)
3189 pfrom->Misbehaving(20);
3190 return error("message addr size() = %"PRIszu"", vAddr.size());
3193 // Store the new addresses
3194 vector<CAddress> vAddrOk;
3195 int64 nNow = GetAdjustedTime();
3196 int64 nSince = nNow - 10 * 60;
3197 BOOST_FOREACH(CAddress& addr, vAddr)
3201 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3202 addr.nTime = nNow - 5 * 24 * 60 * 60;
3203 pfrom->AddAddressKnown(addr);
3204 bool fReachable = IsReachable(addr);
3205 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3207 // Relay to a limited number of other nodes
3210 // Use deterministic randomness to send to the same nodes for 24 hours
3211 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3212 static uint256 hashSalt;
3214 hashSalt = GetRandHash();
3215 uint64 hashAddr = addr.GetHash();
3216 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3217 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3218 multimap<uint256, CNode*> mapMix;
3219 BOOST_FOREACH(CNode* pnode, vNodes)
3221 if (pnode->nVersion < CADDR_TIME_VERSION)
3223 unsigned int nPointer;
3224 memcpy(&nPointer, &pnode, sizeof(nPointer));
3225 uint256 hashKey = hashRand ^ nPointer;
3226 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3227 mapMix.insert(make_pair(hashKey, pnode));
3229 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3230 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3231 ((*mi).second)->PushAddress(addr);
3234 // Do not store addresses outside our network
3236 vAddrOk.push_back(addr);
3238 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3239 if (vAddr.size() < 1000)
3240 pfrom->fGetAddr = false;
3241 if (pfrom->fOneShot)
3242 pfrom->fDisconnect = true;
3245 else if (strCommand == "inv")
3249 if (vInv.size() > MAX_INV_SZ)
3251 pfrom->Misbehaving(20);
3252 return error("message inv size() = %"PRIszu"", vInv.size());
3255 // find last block in inv vector
3256 unsigned int nLastBlock = (unsigned int)(-1);
3257 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3258 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3259 nLastBlock = vInv.size() - 1 - nInv;
3264 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3266 const CInv &inv = vInv[nInv];
3270 pfrom->AddInventoryKnown(inv);
3272 bool fAlreadyHave = AlreadyHave(txdb, inv);
3274 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3278 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3279 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3280 } else if (nInv == nLastBlock) {
3281 // In case we are on a very long side-chain, it is possible that we already have
3282 // the last block in an inv bundle sent in response to getblocks. Try to detect
3283 // this situation and push another getblocks to continue.
3284 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3286 printf("force request: %s\n", inv.ToString().c_str());
3289 // Track requests for our stuff
3290 Inventory(inv.hash);
3295 else if (strCommand == "getdata")
3299 if (vInv.size() > MAX_INV_SZ)
3301 pfrom->Misbehaving(20);
3302 return error("message getdata size() = %"PRIszu"", vInv.size());
3305 if (fDebugNet || (vInv.size() != 1))
3306 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3308 BOOST_FOREACH(const CInv& inv, vInv)
3312 if (fDebugNet || (vInv.size() == 1))
3313 printf("received getdata for: %s\n", inv.ToString().c_str());
3315 if (inv.type == MSG_BLOCK)
3317 // Send block from disk
3318 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3319 if (mi != mapBlockIndex.end())
3322 block.ReadFromDisk((*mi).second);
3323 pfrom->PushMessage("block", block);
3325 // Trigger them to send a getblocks request for the next batch of inventory
3326 if (inv.hash == pfrom->hashContinue)
3328 // ppcoin: send latest proof-of-work block to allow the
3329 // download node to accept as orphan (proof-of-stake
3330 // block might be rejected by stake connection check)
3332 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3333 pfrom->PushMessage("inv", vInv);
3334 pfrom->hashContinue = 0;
3338 else if (inv.IsKnownType())
3340 // Send stream from relay memory
3341 bool pushed = false;
3344 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3345 if (mi != mapRelay.end()) {
3346 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3350 if (!pushed && inv.type == MSG_TX) {
3352 if (mempool.exists(inv.hash)) {
3353 CTransaction tx = mempool.lookup(inv.hash);
3354 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3357 pfrom->PushMessage("tx", ss);
3362 // Track requests for our stuff
3363 Inventory(inv.hash);
3368 else if (strCommand == "getblocks")
3370 CBlockLocator locator;
3372 vRecv >> locator >> hashStop;
3374 // Find the last block the caller has in the main chain
3375 CBlockIndex* pindex = locator.GetBlockIndex();
3377 // Send the rest of the chain
3379 pindex = pindex->pnext;
3381 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3382 for (; pindex; pindex = pindex->pnext)
3384 if (pindex->GetBlockHash() == hashStop)
3386 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3387 // ppcoin: tell downloading node about the latest block if it's
3388 // without risk being rejected due to stake connection check
3389 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3390 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3393 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3396 // When this block is requested, we'll send an inv that'll make them
3397 // getblocks the next batch of inventory.
3398 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3399 pfrom->hashContinue = pindex->GetBlockHash();
3404 else if (strCommand == "checkpoint")
3406 CSyncCheckpoint checkpoint;
3407 vRecv >> checkpoint;
3409 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3412 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3414 BOOST_FOREACH(CNode* pnode, vNodes)
3415 checkpoint.RelayTo(pnode);
3419 else if (strCommand == "getheaders")
3421 CBlockLocator locator;
3423 vRecv >> locator >> hashStop;
3425 CBlockIndex* pindex = NULL;
3426 if (locator.IsNull())
3428 // If locator is null, return the hashStop block
3429 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3430 if (mi == mapBlockIndex.end())
3432 pindex = (*mi).second;
3436 // Find the last block the caller has in the main chain
3437 pindex = locator.GetBlockIndex();
3439 pindex = pindex->pnext;
3442 vector<CBlock> vHeaders;
3444 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3445 for (; pindex; pindex = pindex->pnext)
3447 vHeaders.push_back(pindex->GetBlockHeader());
3448 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3451 pfrom->PushMessage("headers", vHeaders);
3455 else if (strCommand == "tx")
3457 vector<uint256> vWorkQueue;
3458 vector<uint256> vEraseQueue;
3459 CDataStream vMsg(vRecv);
3464 CInv inv(MSG_TX, tx.GetHash());
3465 pfrom->AddInventoryKnown(inv);
3467 bool fMissingInputs = false;
3468 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3470 SyncWithWallets(tx, NULL, true);
3471 RelayTransaction(tx, inv.hash);
3472 mapAlreadyAskedFor.erase(inv);
3473 vWorkQueue.push_back(inv.hash);
3474 vEraseQueue.push_back(inv.hash);
3476 // Recursively process any orphan transactions that depended on this one
3477 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3479 uint256 hashPrev = vWorkQueue[i];
3480 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3481 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3484 const uint256& orphanTxHash = *mi;
3485 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3486 bool fMissingInputs2 = false;
3488 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3490 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3491 SyncWithWallets(tx, NULL, true);
3492 RelayTransaction(orphanTx, orphanTxHash);
3493 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3494 vWorkQueue.push_back(orphanTxHash);
3495 vEraseQueue.push_back(orphanTxHash);
3497 else if (!fMissingInputs2)
3500 vEraseQueue.push_back(orphanTxHash);
3501 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3506 BOOST_FOREACH(uint256 hash, vEraseQueue)
3507 EraseOrphanTx(hash);
3509 else if (fMissingInputs)
3513 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3514 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3516 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3518 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3522 else if (strCommand == "block")
3526 uint256 hashBlock = block.GetHash();
3528 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3531 CInv inv(MSG_BLOCK, hashBlock);
3532 pfrom->AddInventoryKnown(inv);
3534 if (ProcessBlock(pfrom, &block))
3535 mapAlreadyAskedFor.erase(inv);
3536 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3540 else if (strCommand == "getaddr")
3542 // Don't return addresses older than nCutOff timestamp
3543 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3544 pfrom->vAddrToSend.clear();
3545 vector<CAddress> vAddr = addrman.GetAddr();
3546 BOOST_FOREACH(const CAddress &addr, vAddr)
3547 if(addr.nTime > nCutOff)
3548 pfrom->PushAddress(addr);
3552 else if (strCommand == "mempool")
3554 std::vector<uint256> vtxid;
3555 mempool.queryHashes(vtxid);
3557 for (unsigned int i = 0; i < vtxid.size(); i++) {
3558 CInv inv(MSG_TX, vtxid[i]);
3559 vInv.push_back(inv);
3560 if (i == (MAX_INV_SZ - 1))
3563 if (vInv.size() > 0)
3564 pfrom->PushMessage("inv", vInv);
3568 else if (strCommand == "checkorder")
3573 if (!GetBoolArg("-allowreceivebyip"))
3575 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3582 /// we have a chance to check the order here
3584 // Keep giving the same key to the same ip until they use it
3585 if (!mapReuseKey.count(pfrom->addr))
3586 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3588 // Send back approval of order and pubkey to use
3589 CScript scriptPubKey;
3590 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3591 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3595 else if (strCommand == "reply")
3600 CRequestTracker tracker;
3602 LOCK(pfrom->cs_mapRequests);
3603 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3604 if (mi != pfrom->mapRequests.end())
3606 tracker = (*mi).second;
3607 pfrom->mapRequests.erase(mi);
3610 if (!tracker.IsNull())
3611 tracker.fn(tracker.param1, vRecv);
3615 else if (strCommand == "ping")
3617 if (pfrom->nVersion > BIP0031_VERSION)
3621 // Echo the message back with the nonce. This allows for two useful features:
3623 // 1) A remote node can quickly check if the connection is operational
3624 // 2) Remote nodes can measure the latency of the network thread. If this node
3625 // is overloaded it won't respond to pings quickly and the remote node can
3626 // avoid sending us more work, like chain download requests.
3628 // The nonce stops the remote getting confused between different pings: without
3629 // it, if the remote node sends a ping once per second and this node takes 5
3630 // seconds to respond to each, the 5th ping the remote sends would appear to
3631 // return very quickly.
3632 pfrom->PushMessage("pong", nonce);
3637 else if (strCommand == "alert")
3642 uint256 alertHash = alert.GetHash();
3643 if (pfrom->setKnown.count(alertHash) == 0)
3645 if (alert.ProcessAlert())
3648 pfrom->setKnown.insert(alertHash);
3651 BOOST_FOREACH(CNode* pnode, vNodes)
3652 alert.RelayTo(pnode);
3656 // Small DoS penalty so peers that send us lots of
3657 // duplicate/expired/invalid-signature/whatever alerts
3658 // eventually get banned.
3659 // This isn't a Misbehaving(100) (immediate ban) because the
3660 // peer might be an older or different implementation with
3661 // a different signature key, etc.
3662 pfrom->Misbehaving(10);
3670 // Ignore unknown commands for extensibility
3674 // Update the last seen time for this node's address
3675 if (pfrom->fNetworkNode)
3676 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3677 AddressCurrentlyConnected(pfrom->addr);
3683 bool ProcessMessages(CNode* pfrom)
3685 CDataStream& vRecv = pfrom->vRecv;
3689 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3693 // (4) message start
3702 // Don't bother if send buffer is too full to respond anyway
3703 if (pfrom->vSend.size() >= SendBufferSize())
3706 // Scan for message start
3707 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3708 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3709 if (vRecv.end() - pstart < nHeaderSize)
3711 if ((int)vRecv.size() > nHeaderSize)
3713 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3714 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3718 if (pstart - vRecv.begin() > 0)
3719 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3720 vRecv.erase(vRecv.begin(), pstart);
3723 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3728 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3731 string strCommand = hdr.GetCommand();
3734 unsigned int nMessageSize = hdr.nMessageSize;
3735 if (nMessageSize > MAX_SIZE)
3737 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3740 if (nMessageSize > vRecv.size())
3742 // Rewind and wait for rest of message
3743 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3748 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3749 unsigned int nChecksum = 0;
3750 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3751 if (nChecksum != hdr.nChecksum)
3753 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3754 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3758 // Copy message to its own buffer
3759 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3760 vRecv.ignore(nMessageSize);
3768 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3773 catch (std::ios_base::failure& e)
3775 if (strstr(e.what(), "end of data"))
3777 // Allow exceptions from under-length message on vRecv
3778 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());
3780 else if (strstr(e.what(), "size too large"))
3782 // Allow exceptions from over-long size
3783 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3787 PrintExceptionContinue(&e, "ProcessMessages()");
3790 catch (std::exception& e) {
3791 PrintExceptionContinue(&e, "ProcessMessages()");
3793 PrintExceptionContinue(NULL, "ProcessMessages()");
3797 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3805 bool SendMessages(CNode* pto, bool fSendTrickle)
3807 TRY_LOCK(cs_main, lockMain);
3809 // Don't send anything until we get their version message
3810 if (pto->nVersion == 0)
3813 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3815 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3817 if (pto->nVersion > BIP0031_VERSION)
3818 pto->PushMessage("ping", nonce);
3820 pto->PushMessage("ping");
3823 // Resend wallet transactions that haven't gotten in a block yet
3824 ResendWalletTransactions();
3826 // Address refresh broadcast
3827 static int64 nLastRebroadcast;
3828 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3832 BOOST_FOREACH(CNode* pnode, vNodes)
3834 // Periodically clear setAddrKnown to allow refresh broadcasts
3835 if (nLastRebroadcast)
3836 pnode->setAddrKnown.clear();
3838 // Rebroadcast our address
3841 CAddress addr = GetLocalAddress(&pnode->addr);
3842 if (addr.IsRoutable())
3843 pnode->PushAddress(addr);
3847 nLastRebroadcast = GetTime();
3855 vector<CAddress> vAddr;
3856 vAddr.reserve(pto->vAddrToSend.size());
3857 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3859 // returns true if wasn't already contained in the set
3860 if (pto->setAddrKnown.insert(addr).second)
3862 vAddr.push_back(addr);
3863 // receiver rejects addr messages larger than 1000
3864 if (vAddr.size() >= 1000)
3866 pto->PushMessage("addr", vAddr);
3871 pto->vAddrToSend.clear();
3873 pto->PushMessage("addr", vAddr);
3878 // Message: inventory
3881 vector<CInv> vInvWait;
3883 LOCK(pto->cs_inventory);
3884 vInv.reserve(pto->vInventoryToSend.size());
3885 vInvWait.reserve(pto->vInventoryToSend.size());
3886 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3888 if (pto->setInventoryKnown.count(inv))
3891 // trickle out tx inv to protect privacy
3892 if (inv.type == MSG_TX && !fSendTrickle)
3894 // 1/4 of tx invs blast to all immediately
3895 static uint256 hashSalt;
3897 hashSalt = GetRandHash();
3898 uint256 hashRand = inv.hash ^ hashSalt;
3899 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3900 bool fTrickleWait = ((hashRand & 3) != 0);
3902 // always trickle our own transactions
3906 if (GetTransaction(inv.hash, wtx))
3908 fTrickleWait = true;
3913 vInvWait.push_back(inv);
3918 // returns true if wasn't already contained in the set
3919 if (pto->setInventoryKnown.insert(inv).second)
3921 vInv.push_back(inv);
3922 if (vInv.size() >= 1000)
3924 pto->PushMessage("inv", vInv);
3929 pto->vInventoryToSend = vInvWait;
3932 pto->PushMessage("inv", vInv);
3938 vector<CInv> vGetData;
3939 int64 nNow = GetTime() * 1000000;
3941 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3943 const CInv& inv = (*pto->mapAskFor.begin()).second;
3944 if (!AlreadyHave(txdb, inv))
3947 printf("sending getdata: %s\n", inv.ToString().c_str());
3948 vGetData.push_back(inv);
3949 if (vGetData.size() >= 1000)
3951 pto->PushMessage("getdata", vGetData);
3954 mapAlreadyAskedFor[inv] = nNow;
3956 pto->mapAskFor.erase(pto->mapAskFor.begin());
3958 if (!vGetData.empty())
3959 pto->PushMessage("getdata", vGetData);
3965 // Amount compression:
3966 // * If the amount is 0, output 0
3967 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
3968 // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
3969 // * call the result n
3970 // * output 1 + 10*(9*n + d - 1) + e
3971 // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
3972 // (this is decodable, as d is in [1-9] and e is in [0-9])
3974 uint64 CTxOutCompressor::CompressAmount(uint64 n)
3979 while (((n % 10) == 0) && e < 9) {
3985 assert(d >= 1 && d <= 9);
3987 return 1 + (n*9 + d - 1)*10 + e;
3989 return 1 + (n - 1)*10 + 9;
3993 uint64 CTxOutCompressor::DecompressAmount(uint64 x)
3995 // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
3999 // x = 10*(9*n + d - 1) + e
4005 int d = (x % 9) + 1;