1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
11 #include "ui_interface.h"
13 #include "scrypt_mine.h"
14 #include <boost/algorithm/string/replace.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
19 using namespace boost;
25 CCriticalSection cs_setpwalletRegistered;
26 set<CWallet*> setpwalletRegistered;
28 CCriticalSection cs_main;
31 unsigned int nTransactionsUpdated = 0;
33 map<uint256, CBlockIndex*> mapBlockIndex;
34 set<pair<COutPoint, unsigned int> > setStakeSeen;
36 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
37 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
38 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
39 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
40 CBigNum bnPoWBase = CBigNum(uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000")); // difficulty-1 target
42 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
44 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as minimum age for coin age
45 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as stake age of full weight
46 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
47 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
49 int nCoinbaseMaturity = 500;
50 CBlockIndex* pindexGenesisBlock = NULL;
52 CBigNum bnBestChainTrust = 0;
53 CBigNum bnBestInvalidTrust = 0;
54 uint256 hashBestChain = 0;
55 CBlockIndex* pindexBest = NULL;
56 int64 nTimeBestReceived = 0;
58 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
60 map<uint256, CBlock*> mapOrphanBlocks;
61 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
62 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
63 map<uint256, uint256> mapProofOfStake;
65 map<uint256, CDataStream*> mapOrphanTransactions;
66 map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
68 // Constant stuff for coinbase transactions we create:
69 CScript COINBASE_FLAGS;
71 const string strMessageMagic = "NovaCoin Signed Message:\n";
77 int64 nTransactionFee = MIN_TX_FEE;
80 //////////////////////////////////////////////////////////////////////////////
82 // dispatching functions
85 // These functions dispatch to one or all registered wallets
88 void RegisterWallet(CWallet* pwalletIn)
91 LOCK(cs_setpwalletRegistered);
92 setpwalletRegistered.insert(pwalletIn);
96 void UnregisterWallet(CWallet* pwalletIn)
99 LOCK(cs_setpwalletRegistered);
100 setpwalletRegistered.erase(pwalletIn);
104 // check whether the passed transaction is from us
105 bool static IsFromMe(CTransaction& tx)
107 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
108 if (pwallet->IsFromMe(tx))
113 // get the wallet transaction with the given hash (if it exists)
114 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
116 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
117 if (pwallet->GetTransaction(hashTx,wtx))
122 // erases transaction with the given hash from all wallets
123 void static EraseFromWallets(uint256 hash)
125 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
126 pwallet->EraseFromWallet(hash);
129 // make sure all wallets know about the given transaction, in the given block
130 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
134 // ppcoin: wallets need to refund inputs when disconnecting coinstake
135 if (tx.IsCoinStake())
137 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
138 if (pwallet->IsFromMe(tx))
139 pwallet->DisableTransaction(tx);
144 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
145 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
148 // notify wallets about a new best chain
149 void static SetBestChain(const CBlockLocator& loc)
151 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
152 pwallet->SetBestChain(loc);
155 // notify wallets about an updated transaction
156 void static UpdatedTransaction(const uint256& hashTx)
158 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
159 pwallet->UpdatedTransaction(hashTx);
163 void static PrintWallets(const CBlock& block)
165 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
166 pwallet->PrintWallet(block);
169 // notify wallets about an incoming inventory (for request counts)
170 void static Inventory(const uint256& hash)
172 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
173 pwallet->Inventory(hash);
176 // ask wallets to resend their transactions
177 void ResendWalletTransactions()
179 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
180 pwallet->ResendWalletTransactions();
189 //////////////////////////////////////////////////////////////////////////////
191 // mapOrphanTransactions
194 bool AddOrphanTx(const CDataStream& vMsg)
197 CDataStream(vMsg) >> tx;
198 uint256 hash = tx.GetHash();
199 if (mapOrphanTransactions.count(hash))
202 CDataStream* pvMsg = new CDataStream(vMsg);
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:
211 if (pvMsg->size() > 5000)
213 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
218 mapOrphanTransactions[hash] = pvMsg;
219 BOOST_FOREACH(const CTxIn& txin, tx.vin)
220 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
222 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
223 mapOrphanTransactions.size());
227 void static EraseOrphanTx(uint256 hash)
229 if (!mapOrphanTransactions.count(hash))
231 const CDataStream* pvMsg = mapOrphanTransactions[hash];
233 CDataStream(*pvMsg) >> tx;
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);
241 mapOrphanTransactions.erase(hash);
244 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
246 unsigned int nEvicted = 0;
247 while (mapOrphanTransactions.size() > nMaxOrphans)
249 // Evict a random orphan:
250 uint256 randomhash = GetRandHash();
251 map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
252 if (it == mapOrphanTransactions.end())
253 it = mapOrphanTransactions.begin();
254 EraseOrphanTx(it->first);
266 //////////////////////////////////////////////////////////////////////////////
268 // CTransaction and CTxIndex
271 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
274 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
276 if (!ReadFromDisk(txindexRet.pos))
278 if (prevout.n >= vout.size())
286 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
289 return ReadFromDisk(txdb, prevout, txindex);
292 bool CTransaction::ReadFromDisk(COutPoint prevout)
296 return ReadFromDisk(txdb, prevout, txindex);
299 bool CTransaction::IsStandard() const
301 if (nVersion > CTransaction::CURRENT_VERSION)
304 BOOST_FOREACH(const CTxIn& txin, vin)
306 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
307 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
308 // ~65-byte public keys, plus a few script ops.
309 if (txin.scriptSig.size() > 500)
311 if (!txin.scriptSig.IsPushOnly())
314 BOOST_FOREACH(const CTxOut& txout, vout) {
315 if (!::IsStandard(txout.scriptPubKey))
317 if (txout.nValue == 0)
324 // Check transaction inputs, and make sure any
325 // pay-to-script-hash transactions are evaluating IsStandard scripts
327 // Why bother? To avoid denial-of-service attacks; an attacker
328 // can submit a standard HASH... OP_EQUAL transaction,
329 // which will get accepted into blocks. The redemption
330 // script can be anything; an attacker could use a very
331 // expensive-to-check-upon-redemption script like:
332 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
334 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
337 return true; // Coinbases don't use vin normally
339 for (unsigned int i = 0; i < vin.size(); i++)
341 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
343 vector<vector<unsigned char> > vSolutions;
344 txnouttype whichType;
345 // get the scriptPubKey corresponding to this input:
346 const CScript& prevScript = prev.scriptPubKey;
347 if (!Solver(prevScript, whichType, vSolutions))
349 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
350 if (nArgsExpected < 0)
353 // Transactions with extra stuff in their scriptSigs are
354 // non-standard. Note that this EvalScript() call will
355 // be quick, because if there are any operations
356 // beside "push data" in the scriptSig the
357 // IsStandard() call returns false
358 vector<vector<unsigned char> > stack;
359 if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
362 if (whichType == TX_SCRIPTHASH)
366 CScript subscript(stack.back().begin(), stack.back().end());
367 vector<vector<unsigned char> > vSolutions2;
368 txnouttype whichType2;
369 if (!Solver(subscript, whichType2, vSolutions2))
371 if (whichType2 == TX_SCRIPTHASH)
375 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
378 nArgsExpected += tmpExpected;
381 if (stack.size() != (unsigned int)nArgsExpected)
389 CTransaction::GetLegacySigOpCount() const
391 unsigned int nSigOps = 0;
392 BOOST_FOREACH(const CTxIn& txin, vin)
394 nSigOps += txin.scriptSig.GetSigOpCount(false);
396 BOOST_FOREACH(const CTxOut& txout, vout)
398 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
404 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
416 // Load the block this tx is in
418 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
420 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
425 // Update the tx's hashBlock
426 hashBlock = pblock->GetHash();
428 // Locate the transaction
429 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
430 if (pblock->vtx[nIndex] == *(CTransaction*)this)
432 if (nIndex == (int)pblock->vtx.size())
434 vMerkleBranch.clear();
436 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
440 // Fill in merkle branch
441 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
444 // Is the tx in a block that's in the main chain
445 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
446 if (mi == mapBlockIndex.end())
448 CBlockIndex* pindex = (*mi).second;
449 if (!pindex || !pindex->IsInMainChain())
452 return pindexBest->nHeight - pindex->nHeight + 1;
461 bool CTransaction::CheckTransaction() const
463 // Basic checks that don't depend on any context
465 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
467 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
469 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
470 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
472 // Check for negative or overflow output values
474 for (unsigned int i = 0; i < vout.size(); i++)
476 const CTxOut& txout = vout[i];
477 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
478 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
480 // NovaCoin: enforce minimum output amount for user transactions
481 // (and for all transactions until 20 Sep 2013)
482 if ((!IsCoinBase() || nTime < CHAINCHECKS_SWITCH_TIME)
483 && (!txout.IsEmpty()) && txout.nValue < MIN_TXOUT_AMOUNT)
484 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
486 if (txout.nValue > MAX_MONEY)
487 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
488 nValueOut += txout.nValue;
489 if (!MoneyRange(nValueOut))
490 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
493 // Check for duplicate inputs
494 set<COutPoint> vInOutPoints;
495 BOOST_FOREACH(const CTxIn& txin, vin)
497 if (vInOutPoints.count(txin.prevout))
499 vInOutPoints.insert(txin.prevout);
504 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
505 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
509 BOOST_FOREACH(const CTxIn& txin, vin)
510 if (txin.prevout.IsNull())
511 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
517 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
518 enum GetMinFee_mode mode) const
520 // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
521 int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
523 unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION);
524 unsigned int nNewBlockSize = nBlockSize + nBytes;
525 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
527 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
528 if (nMinFee < nBaseFee)
530 BOOST_FOREACH(const CTxOut& txout, vout)
531 if (txout.nValue < CENT)
535 // Raise the price as the block approaches full
536 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
538 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
540 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
543 if (!MoneyRange(nMinFee))
549 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
550 bool* pfMissingInputs)
553 *pfMissingInputs = false;
555 if (!tx.CheckTransaction())
556 return error("CTxMemPool::accept() : CheckTransaction failed");
558 // Coinbase is only valid in a block, not as a loose transaction
560 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
562 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
563 if (tx.IsCoinStake())
564 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
566 // To help v0.1.5 clients who would see it as a negative number
567 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
568 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
570 // Rather not work on nonstandard transactions (unless -testnet)
571 if (!fTestNet && !tx.IsStandard())
572 return error("CTxMemPool::accept() : nonstandard transaction type");
574 // Do we already have it?
575 uint256 hash = tx.GetHash();
578 if (mapTx.count(hash))
582 if (txdb.ContainsTx(hash))
585 // Check for conflicts with in-memory transactions
586 CTransaction* ptxOld = NULL;
587 for (unsigned int i = 0; i < tx.vin.size(); i++)
589 COutPoint outpoint = tx.vin[i].prevout;
590 if (mapNextTx.count(outpoint))
592 // Disable replacement feature for now
595 // Allow replacing with a newer version of the same transaction
598 ptxOld = mapNextTx[outpoint].ptx;
599 if (ptxOld->IsFinal())
601 if (!tx.IsNewerThan(*ptxOld))
603 for (unsigned int i = 0; i < tx.vin.size(); i++)
605 COutPoint outpoint = tx.vin[i].prevout;
606 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
616 map<uint256, CTxIndex> mapUnused;
617 bool fInvalid = false;
618 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
621 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
623 *pfMissingInputs = true;
627 // Check for non-standard pay-to-script-hash in inputs
628 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
629 return error("CTxMemPool::accept() : nonstandard transaction input");
631 // Note: if you modify this code to accept non-standard transactions, then
632 // you should add code here to check that the transaction does a
633 // reasonable number of ECDSA signature verifications.
635 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
636 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
638 // Don't accept it if it can't get into a block
639 int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY);
640 if (nFees < txMinFee)
641 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
642 hash.ToString().c_str(),
645 // Continuously rate-limit free transactions
646 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
647 // be annoying or make others' transactions take longer to confirm.
648 if (nFees < MIN_RELAY_TX_FEE)
650 static CCriticalSection cs;
651 static double dFreeCount;
652 static int64 nLastTime;
653 int64 nNow = GetTime();
657 // Use an exponentially decaying ~10-minute window:
658 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
660 // -limitfreerelay unit is thousand-bytes-per-minute
661 // At default rate it would take over a month to fill 1GB
662 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
663 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
665 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
670 // Check against previous transactions
671 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
672 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
674 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
678 // Store transaction in memory
683 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
686 addUnchecked(hash, tx);
689 ///// are we sure this is ok when loading transactions or restoring block txes
690 // If updated, erase old tx from wallet
692 EraseFromWallets(ptxOld->GetHash());
694 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
695 hash.ToString().substr(0,10).c_str(),
700 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
702 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
705 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
707 // Add to memory pool without checking anything. Don't call this directly,
708 // call CTxMemPool::accept to properly check the transaction first.
711 for (unsigned int i = 0; i < tx.vin.size(); i++)
712 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
713 nTransactionsUpdated++;
719 bool CTxMemPool::remove(CTransaction &tx)
721 // Remove transaction from memory pool
724 uint256 hash = tx.GetHash();
725 if (mapTx.count(hash))
727 BOOST_FOREACH(const CTxIn& txin, tx.vin)
728 mapNextTx.erase(txin.prevout);
730 nTransactionsUpdated++;
736 void CTxMemPool::clear()
741 ++nTransactionsUpdated;
744 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
749 vtxid.reserve(mapTx.size());
750 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
751 vtxid.push_back((*mi).first);
757 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
759 if (hashBlock == 0 || nIndex == -1)
762 // Find the block it claims to be in
763 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
764 if (mi == mapBlockIndex.end())
766 CBlockIndex* pindex = (*mi).second;
767 if (!pindex || !pindex->IsInMainChain())
770 // Make sure the merkle branch connects to this block
771 if (!fMerkleVerified)
773 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
775 fMerkleVerified = true;
779 return pindexBest->nHeight - pindex->nHeight + 1;
783 int CMerkleTx::GetBlocksToMaturity() const
785 if (!(IsCoinBase() || IsCoinStake()))
787 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
791 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
795 if (!IsInMainChain() && !ClientConnectInputs())
797 return CTransaction::AcceptToMemoryPool(txdb, false);
801 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
805 bool CMerkleTx::AcceptToMemoryPool()
808 return AcceptToMemoryPool(txdb);
813 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
818 // Add previous supporting transactions first
819 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
821 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
823 uint256 hash = tx.GetHash();
824 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
825 tx.AcceptToMemoryPool(txdb, fCheckInputs);
828 return AcceptToMemoryPool(txdb, fCheckInputs);
833 bool CWalletTx::AcceptWalletTransaction()
836 return AcceptWalletTransaction(txdb);
839 int CTxIndex::GetDepthInMainChain() const
843 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
845 // Find the block in the index
846 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
847 if (mi == mapBlockIndex.end())
849 CBlockIndex* pindex = (*mi).second;
850 if (!pindex || !pindex->IsInMainChain())
852 return 1 + nBestHeight - pindex->nHeight;
855 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
856 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
862 if (mempool.exists(hash))
864 tx = mempool.lookup(hash);
870 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
873 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
874 hashBlock = block.GetHash();
888 //////////////////////////////////////////////////////////////////////////////
890 // CBlock and CBlockIndex
893 static CBlockIndex* pblockindexFBBHLast;
894 CBlockIndex* FindBlockByHeight(int nHeight)
896 CBlockIndex *pblockindex;
897 if (nHeight < nBestHeight / 2)
898 pblockindex = pindexGenesisBlock;
900 pblockindex = pindexBest;
901 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
902 pblockindex = pblockindexFBBHLast;
903 while (pblockindex->nHeight > nHeight)
904 pblockindex = pblockindex->pprev;
905 while (pblockindex->nHeight < nHeight)
906 pblockindex = pblockindex->pnext;
907 pblockindexFBBHLast = pblockindex;
911 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
913 if (!fReadTransactions)
915 *this = pindex->GetBlockHeader();
918 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
920 if (GetHash() != pindex->GetBlockHash())
921 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
925 uint256 static GetOrphanRoot(const CBlock* pblock)
927 // Work back to the first block in the orphan chain
928 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
929 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
930 return pblock->GetHash();
933 // ppcoin: find block wanted by given orphan block
934 uint256 WantedByOrphan(const CBlock* pblockOrphan)
936 // Work back to the first block in the orphan chain
937 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
938 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
939 return pblockOrphan->hashPrevBlock;
942 // select stake target limit according to hard-coded conditions
943 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
945 if(fTestNet) // separate proof of stake target limit for testnet
946 return bnProofOfStakeLimit;
947 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
948 return bnProofOfStakeLimit;
949 if(nHeight + 1 > 15000) // 24 bits since block 15000
950 return bnProofOfStakeLegacyLimit;
951 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
952 return bnProofOfStakeHardLimit;
954 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
957 // miner's coin base reward based on nBits
958 int64 GetProofOfWorkReward(unsigned int nBits)
960 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
963 bnTarget.SetCompact(nBits);
964 CBigNum bnTargetLimit = bnProofOfWorkLimit;
965 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
967 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
968 // A reasonably continuous curve is used to avoid shock to market
969 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
971 // Human readable form:
973 // nSubsidy = 100 / (diff ^ 1/6)
974 CBigNum bnLowerBound = CENT;
975 CBigNum bnUpperBound = bnSubsidyLimit;
976 while (bnLowerBound + CENT <= bnUpperBound)
978 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
979 if (fDebug && GetBoolArg("-printcreation"))
980 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
981 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
982 bnUpperBound = bnMidValue;
984 bnLowerBound = bnMidValue;
987 int64 nSubsidy = bnUpperBound.getuint64();
989 nSubsidy = (nSubsidy / CENT) * CENT;
990 if (fDebug && GetBoolArg("-printcreation"))
991 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
993 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK);
996 // miner's coin stake reward based on nBits and coin age spent (coin-days)
997 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
999 int64 nRewardCoinYear, nSubsidy;
1001 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1003 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1005 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1007 bnTarget.SetCompact(nBits);
1008 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1009 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1011 // NovaCoin: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1012 // A reasonably continuous curve is used to avoid shock to market
1013 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1015 // Human readable form:
1017 // nRewardCoinYear = 1 / (posdiff ^ 1/6)
1019 CBigNum bnLowerBound = 1 * CENT; // Lower interest bound is 1% per year
1020 CBigNum bnUpperBound = bnRewardCoinYearLimit;
1021 while (bnLowerBound + CENT <= bnUpperBound)
1023 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1024 if (fDebug && GetBoolArg("-printcreation"))
1025 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1026 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnTarget)
1027 bnUpperBound = bnMidValue;
1029 bnLowerBound = bnMidValue;
1032 nRewardCoinYear = bnUpperBound.getuint64();
1033 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1037 // Old creation amount per coin-year, 5% fixed stake mint rate
1038 nRewardCoinYear = 5 * CENT;
1042 return nRewardCoinYear;
1044 // Fix problem with proof-of-stake rewards calculation since 20 Sep 2013
1045 if(nTime < CHAINCHECKS_SWITCH_TIME)
1046 nSubsidy = nCoinAge * 33 / (365 * 33 + 8) * nRewardCoinYear;
1048 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1050 if (fDebug && GetBoolArg("-printcreation"))
1051 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1055 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1057 // get proof of work blocks max spacing according to hard-coded conditions
1058 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1060 if(nTime > TARGETS_SWITCH_TIME)
1061 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1064 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1066 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1070 // minimum amount of work that could possibly be required nTime after
1071 // minimum work required was nBase
1073 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1075 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1078 bnResult.SetCompact(nBase);
1080 while (nTime > 0 && bnResult < bnTargetLimit)
1082 // Maximum 200% adjustment per day...
1084 nTime -= 24 * 60 * 60;
1086 if (bnResult > bnTargetLimit)
1087 bnResult = bnTargetLimit;
1088 return bnResult.GetCompact();
1091 // ppcoin: find last block index up to pindex
1092 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1094 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1095 pindex = pindex->pprev;
1099 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1101 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1103 if (pindexLast == NULL)
1104 return bnTargetLimit.GetCompact(); // genesis block
1106 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1107 if (pindexPrev->pprev == NULL)
1108 return bnTargetLimit.GetCompact(); // first block
1109 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1110 if (pindexPrevPrev->pprev == NULL)
1111 return bnTargetLimit.GetCompact(); // second block
1113 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1115 // ppcoin: target change every block
1116 // ppcoin: retarget with exponential moving toward target spacing
1118 bnNew.SetCompact(pindexPrev->nBits);
1119 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1120 int64 nInterval = nTargetTimespan / nTargetSpacing;
1121 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1122 bnNew /= ((nInterval + 1) * nTargetSpacing);
1124 if (bnNew > bnTargetLimit)
1125 bnNew = bnTargetLimit;
1127 return bnNew.GetCompact();
1130 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1133 bnTarget.SetCompact(nBits);
1136 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1137 return error("CheckProofOfWork() : nBits below minimum work");
1139 // Check proof of work matches claimed amount
1140 if (hash > bnTarget.getuint256())
1141 return error("CheckProofOfWork() : hash doesn't match nBits");
1146 // Return maximum amount of blocks that other nodes claim to have
1147 int GetNumBlocksOfPeers()
1149 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1152 bool IsInitialBlockDownload()
1154 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1156 static int64 nLastUpdate;
1157 static CBlockIndex* pindexLastBest;
1158 if (pindexBest != pindexLastBest)
1160 pindexLastBest = pindexBest;
1161 nLastUpdate = GetTime();
1163 return (GetTime() - nLastUpdate < 10 &&
1164 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1167 void static InvalidChainFound(CBlockIndex* pindexNew)
1169 if (pindexNew->bnChainTrust > bnBestInvalidTrust)
1171 bnBestInvalidTrust = pindexNew->bnChainTrust;
1172 CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust);
1173 uiInterface.NotifyBlocksChanged();
1176 CBigNum bnBestInvalidBlockTrust = pindexNew->bnChainTrust - pindexNew->pprev->bnChainTrust;
1177 CBigNum bnBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->bnChainTrust - pindexBest->pprev->bnChainTrust) : pindexBest->bnChainTrust;
1179 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%s date=%s\n",
1180 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1181 pindexNew->bnChainTrust.ToString().c_str(), bnBestInvalidBlockTrust.ToString().c_str(),
1182 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1183 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%s date=%s\n",
1184 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1185 bnBestChainTrust.ToString().c_str(),
1186 bnBestBlockTrust.ToString().c_str(),
1187 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1191 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1193 nTime = max(GetBlockTime(), GetAdjustedTime());
1206 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1208 // Relinquish previous transactions' spent pointers
1211 BOOST_FOREACH(const CTxIn& txin, vin)
1213 COutPoint prevout = txin.prevout;
1215 // Get prev txindex from disk
1217 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1218 return error("DisconnectInputs() : ReadTxIndex failed");
1220 if (prevout.n >= txindex.vSpent.size())
1221 return error("DisconnectInputs() : prevout.n out of range");
1223 // Mark outpoint as not spent
1224 txindex.vSpent[prevout.n].SetNull();
1227 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1228 return error("DisconnectInputs() : UpdateTxIndex failed");
1232 // Remove transaction from index
1233 // This can fail if a duplicate of this transaction was in a chain that got
1234 // reorganized away. This is only possible if this transaction was completely
1235 // spent, so erasing it would be a no-op anyway.
1236 txdb.EraseTxIndex(*this);
1242 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1243 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1245 // FetchInputs can return false either because we just haven't seen some inputs
1246 // (in which case the transaction should be stored as an orphan)
1247 // or because the transaction is malformed (in which case the transaction should
1248 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1252 return true; // Coinbase transactions have no inputs to fetch.
1254 for (unsigned int i = 0; i < vin.size(); i++)
1256 COutPoint prevout = vin[i].prevout;
1257 if (inputsRet.count(prevout.hash))
1258 continue; // Got it already
1261 CTxIndex& txindex = inputsRet[prevout.hash].first;
1263 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1265 // Get txindex from current proposed changes
1266 txindex = mapTestPool.find(prevout.hash)->second;
1270 // Read txindex from txdb
1271 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1273 if (!fFound && (fBlock || fMiner))
1274 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());
1277 CTransaction& txPrev = inputsRet[prevout.hash].second;
1278 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1280 // Get prev tx from single transactions in memory
1283 if (!mempool.exists(prevout.hash))
1284 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());
1285 txPrev = mempool.lookup(prevout.hash);
1288 txindex.vSpent.resize(txPrev.vout.size());
1292 // Get prev tx from disk
1293 if (!txPrev.ReadFromDisk(txindex.pos))
1294 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1298 // Make sure all prevout.n indexes are valid:
1299 for (unsigned int i = 0; i < vin.size(); i++)
1301 const COutPoint prevout = vin[i].prevout;
1302 assert(inputsRet.count(prevout.hash) != 0);
1303 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1304 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1305 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1307 // Revisit this if/when transaction replacement is implemented and allows
1310 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()));
1317 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1319 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1320 if (mi == inputs.end())
1321 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1323 const CTransaction& txPrev = (mi->second).second;
1324 if (input.prevout.n >= txPrev.vout.size())
1325 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1327 return txPrev.vout[input.prevout.n];
1330 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1336 for (unsigned int i = 0; i < vin.size(); i++)
1338 nResult += GetOutputFor(vin[i], inputs).nValue;
1344 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1349 unsigned int nSigOps = 0;
1350 for (unsigned int i = 0; i < vin.size(); i++)
1352 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1353 if (prevout.scriptPubKey.IsPayToScriptHash())
1354 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1359 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
1360 map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1361 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
1363 // Take over previous transactions' spent pointers
1364 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1365 // fMiner is true when called from the internal bitcoin miner
1366 // ... both are false when called from CTransaction::AcceptToMemoryPool
1371 for (unsigned int i = 0; i < vin.size(); i++)
1373 COutPoint prevout = vin[i].prevout;
1374 assert(inputs.count(prevout.hash) > 0);
1375 CTxIndex& txindex = inputs[prevout.hash].first;
1376 CTransaction& txPrev = inputs[prevout.hash].second;
1378 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1379 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()));
1381 // If prev is coinbase or coinstake, check that it's matured
1382 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1383 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1384 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1385 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1387 // ppcoin: check transaction timestamp
1388 if (txPrev.nTime > nTime)
1389 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1391 // Check for negative or overflow input values
1392 nValueIn += txPrev.vout[prevout.n].nValue;
1393 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1394 return DoS(100, error("ConnectInputs() : txin values out of range"));
1397 // The first loop above does all the inexpensive checks.
1398 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1399 // Helps prevent CPU exhaustion attacks.
1400 for (unsigned int i = 0; i < vin.size(); i++)
1402 COutPoint prevout = vin[i].prevout;
1403 assert(inputs.count(prevout.hash) > 0);
1404 CTxIndex& txindex = inputs[prevout.hash].first;
1405 CTransaction& txPrev = inputs[prevout.hash].second;
1407 // Check for conflicts (double-spend)
1408 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1409 // for an attacker to attempt to split the network.
1410 if (!txindex.vSpent[prevout.n].IsNull())
1411 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());
1413 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1414 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1415 // still computed and checked, and any change will be caught at the next checkpoint.
1416 if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
1419 if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
1421 // only during transition phase for P2SH: do not invoke anti-DoS code for
1422 // potentially old clients relaying bad P2SH transactions
1423 if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
1424 return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1426 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1430 // Mark outpoints as spent
1431 txindex.vSpent[prevout.n] = posThisTx;
1434 if (fBlock || fMiner)
1436 mapTestPool[prevout.hash] = txindex;
1442 // ppcoin: coin stake tx earns reward instead of paying fee
1444 if (!GetCoinAge(txdb, nCoinAge))
1445 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1446 int64 nStakeReward = GetValueOut() - nValueIn;
1447 if (nStakeReward > GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee() + MIN_TX_FEE)
1448 return DoS(100, error("ConnectInputs() : %s stake reward exceeded", GetHash().ToString().substr(0,10).c_str()));
1452 if (nValueIn < GetValueOut())
1453 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1455 // Tally transaction fees
1456 int64 nTxFee = nValueIn - GetValueOut();
1458 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1459 // ppcoin: enforce transaction fees for every block
1460 if (nTxFee < GetMinFee())
1461 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;
1464 if (!MoneyRange(nFees))
1465 return DoS(100, error("ConnectInputs() : nFees out of range"));
1473 bool CTransaction::ClientConnectInputs()
1478 // Take over previous transactions' spent pointers
1482 for (unsigned int i = 0; i < vin.size(); i++)
1484 // Get prev tx from single transactions in memory
1485 COutPoint prevout = vin[i].prevout;
1486 if (!mempool.exists(prevout.hash))
1488 CTransaction& txPrev = mempool.lookup(prevout.hash);
1490 if (prevout.n >= txPrev.vout.size())
1494 if (!VerifySignature(txPrev, *this, i, true, 0))
1495 return error("ConnectInputs() : VerifySignature failed");
1497 ///// this is redundant with the mempool.mapNextTx stuff,
1498 ///// not sure which I want to get rid of
1499 ///// this has to go away now that posNext is gone
1500 // // Check for conflicts
1501 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1502 // return error("ConnectInputs() : prev tx already used");
1504 // // Flag outpoints as used
1505 // txPrev.vout[prevout.n].posNext = posThisTx;
1507 nValueIn += txPrev.vout[prevout.n].nValue;
1509 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1510 return error("ClientConnectInputs() : txin values out of range");
1512 if (GetValueOut() > nValueIn)
1522 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1524 // Disconnect in reverse order
1525 for (int i = vtx.size()-1; i >= 0; i--)
1526 if (!vtx[i].DisconnectInputs(txdb))
1529 // Update block index on disk without changing it in memory.
1530 // The memory index structure will be changed after the db commits.
1533 CDiskBlockIndex blockindexPrev(pindex->pprev);
1534 blockindexPrev.hashNext = 0;
1535 if (!txdb.WriteBlockIndex(blockindexPrev))
1536 return error("DisconnectBlock() : WriteBlockIndex failed");
1539 // ppcoin: clean up wallet after disconnecting coinstake
1540 BOOST_FOREACH(CTransaction& tx, vtx)
1541 SyncWithWallets(tx, this, false, false);
1546 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1548 // Check it again in case a previous version let a bad block in
1549 if (!CheckBlock(!fJustCheck, !fJustCheck))
1552 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1553 // unless those are already completely spent.
1554 // If such overwrites are allowed, coinbases and transactions depending upon those
1555 // can be duplicated to remove the ability to spend the first instance -- even after
1556 // being sent to another address.
1557 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1558 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1559 // already refuses previously-known transaction ids entirely.
1560 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1561 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1562 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1563 // initial block download.
1564 bool fEnforceBIP30 = true; // Always active in NovaCoin
1565 bool fStrictPayToScriptHash = true; // Always active in NovaCoin
1567 //// issue here: it doesn't know the version
1568 unsigned int nTxPos;
1570 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1571 // 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
1574 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1576 map<uint256, CTxIndex> mapQueuedChanges;
1579 int64 nValueOut = 0;
1580 unsigned int nSigOps = 0;
1581 BOOST_FOREACH(CTransaction& tx, vtx)
1583 uint256 hashTx = tx.GetHash();
1585 if (fEnforceBIP30) {
1586 CTxIndex txindexOld;
1587 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1588 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1594 nSigOps += tx.GetLegacySigOpCount();
1595 if (nSigOps > MAX_BLOCK_SIGOPS)
1596 return DoS(100, error("ConnectBlock() : too many sigops"));
1598 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1600 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1602 MapPrevTx mapInputs;
1603 if (tx.IsCoinBase())
1604 nValueOut += tx.GetValueOut();
1608 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1611 if (fStrictPayToScriptHash)
1613 // Add in sigops done by pay-to-script-hash inputs;
1614 // this is to prevent a "rogue miner" from creating
1615 // an incredibly-expensive-to-validate block.
1616 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1617 if (nSigOps > MAX_BLOCK_SIGOPS)
1618 return DoS(100, error("ConnectBlock() : too many sigops"));
1621 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1622 int64 nTxValueOut = tx.GetValueOut();
1623 nValueIn += nTxValueIn;
1624 nValueOut += nTxValueOut;
1625 if (!tx.IsCoinStake())
1626 nFees += nTxValueIn - nTxValueOut;
1628 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
1632 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1635 // ppcoin: track money supply and mint amount info
1636 pindex->nMint = nValueOut - nValueIn + nFees;
1637 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1638 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1639 return error("Connect() : WriteBlockIndex for pindex failed");
1641 // ppcoin: fees are not collected by miners as in bitcoin
1642 // ppcoin: fees are destroyed to compensate the entire network
1643 if (fDebug && GetBoolArg("-printcreation"))
1644 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1649 // Write queued txindex changes
1650 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1652 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1653 return error("ConnectBlock() : UpdateTxIndex failed");
1656 // Update block index on disk without changing it in memory.
1657 // The memory index structure will be changed after the db commits.
1660 CDiskBlockIndex blockindexPrev(pindex->pprev);
1661 blockindexPrev.hashNext = pindex->GetBlockHash();
1662 if (!txdb.WriteBlockIndex(blockindexPrev))
1663 return error("ConnectBlock() : WriteBlockIndex failed");
1666 // Watch for transactions paying to me
1667 BOOST_FOREACH(CTransaction& tx, vtx)
1668 SyncWithWallets(tx, this, true);
1673 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1675 printf("REORGANIZE\n");
1678 CBlockIndex* pfork = pindexBest;
1679 CBlockIndex* plonger = pindexNew;
1680 while (pfork != plonger)
1682 while (plonger->nHeight > pfork->nHeight)
1683 if (!(plonger = plonger->pprev))
1684 return error("Reorganize() : plonger->pprev is null");
1685 if (pfork == plonger)
1687 if (!(pfork = pfork->pprev))
1688 return error("Reorganize() : pfork->pprev is null");
1691 // List of what to disconnect
1692 vector<CBlockIndex*> vDisconnect;
1693 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1694 vDisconnect.push_back(pindex);
1696 // List of what to connect
1697 vector<CBlockIndex*> vConnect;
1698 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1699 vConnect.push_back(pindex);
1700 reverse(vConnect.begin(), vConnect.end());
1702 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());
1703 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());
1705 // Disconnect shorter branch
1706 vector<CTransaction> vResurrect;
1707 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1710 if (!block.ReadFromDisk(pindex))
1711 return error("Reorganize() : ReadFromDisk for disconnect failed");
1712 if (!block.DisconnectBlock(txdb, pindex))
1713 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1715 // Queue memory transactions to resurrect
1716 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1717 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1718 vResurrect.push_back(tx);
1721 // Connect longer branch
1722 vector<CTransaction> vDelete;
1723 for (unsigned int i = 0; i < vConnect.size(); i++)
1725 CBlockIndex* pindex = vConnect[i];
1727 if (!block.ReadFromDisk(pindex))
1728 return error("Reorganize() : ReadFromDisk for connect failed");
1729 if (!block.ConnectBlock(txdb, pindex))
1732 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1735 // Queue memory transactions to delete
1736 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1737 vDelete.push_back(tx);
1739 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1740 return error("Reorganize() : WriteHashBestChain failed");
1742 // Make sure it's successfully written to disk before changing memory structure
1743 if (!txdb.TxnCommit())
1744 return error("Reorganize() : TxnCommit failed");
1746 // Disconnect shorter branch
1747 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1749 pindex->pprev->pnext = NULL;
1751 // Connect longer branch
1752 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1754 pindex->pprev->pnext = pindex;
1756 // Resurrect memory transactions that were in the disconnected branch
1757 BOOST_FOREACH(CTransaction& tx, vResurrect)
1758 tx.AcceptToMemoryPool(txdb, false);
1760 // Delete redundant memory transactions that are in the connected branch
1761 BOOST_FOREACH(CTransaction& tx, vDelete)
1764 printf("REORGANIZE: done\n");
1770 // Called from inside SetBestChain: attaches a block to the new best chain being built
1771 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1773 uint256 hash = GetHash();
1775 // Adding to current best branch
1776 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1779 InvalidChainFound(pindexNew);
1782 if (!txdb.TxnCommit())
1783 return error("SetBestChain() : TxnCommit failed");
1785 // Add to current best branch
1786 pindexNew->pprev->pnext = pindexNew;
1788 // Delete redundant memory transactions
1789 BOOST_FOREACH(CTransaction& tx, vtx)
1795 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1797 uint256 hash = GetHash();
1799 if (!txdb.TxnBegin())
1800 return error("SetBestChain() : TxnBegin failed");
1802 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1804 txdb.WriteHashBestChain(hash);
1805 if (!txdb.TxnCommit())
1806 return error("SetBestChain() : TxnCommit failed");
1807 pindexGenesisBlock = pindexNew;
1809 else if (hashPrevBlock == hashBestChain)
1811 if (!SetBestChainInner(txdb, pindexNew))
1812 return error("SetBestChain() : SetBestChainInner failed");
1816 // the first block in the new chain that will cause it to become the new best chain
1817 CBlockIndex *pindexIntermediate = pindexNew;
1819 // list of blocks that need to be connected afterwards
1820 std::vector<CBlockIndex*> vpindexSecondary;
1822 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1823 // Try to limit how much needs to be done inside
1824 while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust)
1826 vpindexSecondary.push_back(pindexIntermediate);
1827 pindexIntermediate = pindexIntermediate->pprev;
1830 if (!vpindexSecondary.empty())
1831 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1833 // Switch to new best branch
1834 if (!Reorganize(txdb, pindexIntermediate))
1837 InvalidChainFound(pindexNew);
1838 return error("SetBestChain() : Reorganize failed");
1841 // Connect further blocks
1842 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
1845 if (!block.ReadFromDisk(pindex))
1847 printf("SetBestChain() : ReadFromDisk failed\n");
1850 if (!txdb.TxnBegin()) {
1851 printf("SetBestChain() : TxnBegin 2 failed\n");
1854 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
1855 if (!block.SetBestChainInner(txdb, pindex))
1860 // Update best block in wallet (so we can detect restored wallets)
1861 bool fIsInitialDownload = IsInitialBlockDownload();
1862 if (!fIsInitialDownload)
1864 const CBlockLocator locator(pindexNew);
1865 ::SetBestChain(locator);
1869 hashBestChain = hash;
1870 pindexBest = pindexNew;
1871 pblockindexFBBHLast = NULL;
1872 nBestHeight = pindexBest->nHeight;
1873 bnBestChainTrust = pindexNew->bnChainTrust;
1874 nTimeBestReceived = GetTime();
1875 nTransactionsUpdated++;
1877 CBigNum bnBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->bnChainTrust - pindexBest->pprev->bnChainTrust) : pindexBest->bnChainTrust;
1879 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%s date=%s\n",
1880 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(),
1881 bnBestBlockTrust.ToString().c_str(),
1882 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1884 // Check the version of the last 100 blocks to see if we need to upgrade:
1885 if (!fIsInitialDownload)
1888 const CBlockIndex* pindex = pindexBest;
1889 for (int i = 0; i < 100 && pindex != NULL; i++)
1891 if (pindex->nVersion > CBlock::CURRENT_VERSION)
1893 pindex = pindex->pprev;
1896 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
1897 if (nUpgraded > 100/2)
1898 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
1899 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
1902 std::string strCmd = GetArg("-blocknotify", "");
1904 if (!fIsInitialDownload && !strCmd.empty())
1906 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
1907 boost::thread t(runCommand, strCmd); // thread runs free
1913 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
1914 // Only those coins meeting minimum age requirement counts. As those
1915 // transactions not in main chain are not currently indexed so we
1916 // might not find out about their coin age. Older transactions are
1917 // guaranteed to be in main chain by sync-checkpoint. This rule is
1918 // introduced to help nodes establish a consistent view of the coin
1919 // age (trust score) of competing branches.
1920 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
1922 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
1928 BOOST_FOREACH(const CTxIn& txin, vin)
1930 // First try finding the previous transaction in database
1931 CTransaction txPrev;
1933 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
1934 continue; // previous transaction not in main chain
1935 if (nTime < txPrev.nTime)
1936 return false; // Transaction timestamp violation
1938 // Read block header
1940 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1941 return false; // unable to read block of previous transaction
1942 if (block.GetBlockTime() + nStakeMinAge > nTime)
1943 continue; // only count coins meeting min age requirement
1945 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
1946 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
1948 if (fDebug && GetBoolArg("-printcoinage"))
1949 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
1952 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
1953 if (fDebug && GetBoolArg("-printcoinage"))
1954 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
1955 nCoinAge = bnCoinDay.getuint64();
1959 // ppcoin: total coin age spent in block, in the unit of coin-days.
1960 bool CBlock::GetCoinAge(uint64& nCoinAge) const
1965 BOOST_FOREACH(const CTransaction& tx, vtx)
1968 if (tx.GetCoinAge(txdb, nTxCoinAge))
1969 nCoinAge += nTxCoinAge;
1974 if (nCoinAge == 0) // block coin age minimum 1 coin-day
1976 if (fDebug && GetBoolArg("-printcoinage"))
1977 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
1981 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1983 // Check for duplicate
1984 uint256 hash = GetHash();
1985 if (mapBlockIndex.count(hash))
1986 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1988 // Construct new block index object
1989 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1991 return error("AddToBlockIndex() : new CBlockIndex failed");
1992 pindexNew->phashBlock = &hash;
1993 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1994 if (miPrev != mapBlockIndex.end())
1996 pindexNew->pprev = (*miPrev).second;
1997 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2000 // ppcoin: compute chain trust score
2001 pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
2003 // ppcoin: compute stake entropy bit for stake modifier
2004 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nHeight)))
2005 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2007 // ppcoin: record proof-of-stake hash value
2008 if (pindexNew->IsProofOfStake())
2010 if (!mapProofOfStake.count(hash))
2011 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2012 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2015 // ppcoin: compute stake modifier
2016 uint64 nStakeModifier = 0;
2017 bool fGeneratedStakeModifier = false;
2018 if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
2019 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2020 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2021 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2022 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2023 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2025 // Add to mapBlockIndex
2026 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2027 if (pindexNew->IsProofOfStake())
2028 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2029 pindexNew->phashBlock = &((*mi).first);
2031 // Write to disk block index
2033 if (!txdb.TxnBegin())
2035 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2036 if (!txdb.TxnCommit())
2040 if (pindexNew->bnChainTrust > bnBestChainTrust)
2041 if (!SetBestChain(txdb, pindexNew))
2046 if (pindexNew == pindexBest)
2048 // Notify UI to display prev block's coinbase if it was ours
2049 static uint256 hashPrevBestCoinBase;
2050 UpdatedTransaction(hashPrevBestCoinBase);
2051 hashPrevBestCoinBase = vtx[0].GetHash();
2054 uiInterface.NotifyBlocksChanged();
2061 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
2063 // These are checks that are independent of context
2064 // that can be verified before saving an orphan block.
2067 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2068 return DoS(100, error("CheckBlock() : size limits failed"));
2070 // Special short-term limits to avoid 10,000 BDB lock limit:
2071 if (GetBlockTime() < LOCKS_SWITCH_TIME)
2073 // Rule is: #unique txids referenced <= 4,500
2074 // ... to prevent 10,000 BDB lock exhaustion on old clients
2075 set<uint256> setTxIn;
2076 for (size_t i = 0; i < vtx.size(); i++)
2078 setTxIn.insert(vtx[i].GetHash());
2079 if (i == 0) continue; // skip coinbase txin
2080 BOOST_FOREACH(const CTxIn& txin, vtx[i].vin)
2081 setTxIn.insert(txin.prevout.hash);
2083 size_t nTxids = setTxIn.size();
2085 return error("CheckBlock() : maxlocks violation");
2088 // Check proof of work matches claimed amount
2089 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2090 return DoS(50, error("CheckBlock() : proof of work failed"));
2093 if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
2094 return error("CheckBlock() : block timestamp too far in the future");
2096 // First transaction must be coinbase, the rest must not be
2097 if (vtx.empty() || !vtx[0].IsCoinBase())
2098 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2099 for (unsigned int i = 1; i < vtx.size(); i++)
2100 if (vtx[i].IsCoinBase())
2101 return DoS(100, error("CheckBlock() : more than one coinbase"));
2103 // Check coinbase timestamp
2104 if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
2105 return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
2107 if (IsProofOfStake())
2109 // ppcoin: coinbase output should be empty if proof-of-stake block
2110 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2111 return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
2113 // Second transaction must be coinstake, the rest must not be
2114 if (vtx.empty() || !vtx[1].IsCoinStake())
2115 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2116 for (unsigned int i = 2; i < vtx.size(); i++)
2117 if (vtx[i].IsCoinStake())
2118 return DoS(100, error("CheckBlock() : more than one coinstake"));
2120 // Check coinstake timestamp
2121 if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
2122 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2126 // Coinbase fee paid until 20 Sep 2013
2127 int64 nFee = GetBlockTime() < CHAINCHECKS_SWITCH_TIME ? vtx[0].GetMinFee() - MIN_TX_FEE : 0;
2129 // Check coinbase reward
2130 if (vtx[0].GetValueOut() > (GetProofOfWorkReward(nBits) - nFee))
2131 return DoS(50, error("CheckBlock() : coinbase reward exceeded %s > %s",
2132 FormatMoney(vtx[0].GetValueOut()).c_str(),
2133 FormatMoney(GetProofOfWorkReward(nBits) - nFee).c_str()));
2136 // Check transactions
2137 BOOST_FOREACH(const CTransaction& tx, vtx)
2139 if (!tx.CheckTransaction())
2140 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2142 // ppcoin: check transaction timestamp
2143 if (GetBlockTime() < (int64)tx.nTime)
2144 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2147 // Check for duplicate txids. This is caught by ConnectInputs(),
2148 // but catching it earlier avoids a potential DoS attack:
2149 set<uint256> uniqueTx;
2150 BOOST_FOREACH(const CTransaction& tx, vtx)
2152 uniqueTx.insert(tx.GetHash());
2154 if (uniqueTx.size() != vtx.size())
2155 return DoS(100, error("CheckBlock() : duplicate transaction"));
2157 unsigned int nSigOps = 0;
2158 BOOST_FOREACH(const CTransaction& tx, vtx)
2160 nSigOps += tx.GetLegacySigOpCount();
2162 if (nSigOps > MAX_BLOCK_SIGOPS)
2163 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2165 // Check merkle root
2166 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2167 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2169 // NovaCoin: check proof-of-stake block signature
2170 if (IsProofOfStake() || (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME))
2172 if (!CheckBlockSignature())
2173 return DoS(100, error("CheckBlock() : bad block signature"));
2179 bool CBlock::AcceptBlock()
2181 // Check for duplicate
2182 uint256 hash = GetHash();
2183 if (mapBlockIndex.count(hash))
2184 return error("AcceptBlock() : block already in mapBlockIndex");
2186 // Get prev block index
2187 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2188 if (mi == mapBlockIndex.end())
2189 return DoS(10, error("AcceptBlock() : prev block not found"));
2190 CBlockIndex* pindexPrev = (*mi).second;
2191 int nHeight = pindexPrev->nHeight+1;
2193 // Check proof-of-work or proof-of-stake
2194 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2195 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2197 // Check timestamp against prev
2198 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
2199 return error("AcceptBlock() : block's timestamp is too early");
2201 // Check that all transactions are finalized
2202 BOOST_FOREACH(const CTransaction& tx, vtx)
2203 if (!tx.IsFinal(nHeight, GetBlockTime()))
2204 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2206 // Check that the block chain matches the known block chain up to a checkpoint
2207 if (!Checkpoints::CheckHardened(nHeight, hash))
2208 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2210 // ppcoin: check that the block satisfies synchronized checkpoint
2211 if (!Checkpoints::CheckSync(hash, pindexPrev))
2213 if(!GetBoolArg("-nosynccheckpoints", false))
2215 return error("AcceptBlock() : rejected by synchronized checkpoint");
2219 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2223 // Reject block.nVersion < 3 blocks since 95% threshold on mainNet and always on testNet:
2224 if (nVersion < 3 && ((!fTestNet && nHeight > 14060) || (fTestNet && nHeight > 0)))
2225 return error("CheckBlock() : rejected nVersion < 3 block");
2227 // Enforce rule that the coinbase starts with serialized block height
2228 CScript expect = CScript() << nHeight;
2229 if (!std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2230 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2232 // Write block to history file
2233 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2234 return error("AcceptBlock() : out of disk space");
2235 unsigned int nFile = -1;
2236 unsigned int nBlockPos = 0;
2237 if (!WriteToDisk(nFile, nBlockPos))
2238 return error("AcceptBlock() : WriteToDisk failed");
2239 if (!AddToBlockIndex(nFile, nBlockPos))
2240 return error("AcceptBlock() : AddToBlockIndex failed");
2242 // Relay inventory, but don't relay old inventory during initial block download
2243 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2244 if (hashBestChain == hash)
2247 BOOST_FOREACH(CNode* pnode, vNodes)
2248 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2249 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2252 // ppcoin: check pending sync-checkpoint
2253 Checkpoints::AcceptPendingSyncCheckpoint();
2258 CBigNum CBlockIndex::GetBlockTrust() const
2261 bnTarget.SetCompact(nBits);
2266 /* Old protocol, will be removed later */
2267 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2268 return (IsProofOfStake()? (CBigNum(1)<<256) / (bnTarget+1) : 1);
2272 // Calculate work amount for block
2273 CBigNum bnPoWTrust = bnPoWBase / (bnTarget+1);
2275 // Set bnPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2276 bnPoWTrust = (IsProofOfStake() || bnPoWTrust < 1) ? 1 : bnPoWTrust;
2278 // Return bnPoWTrust for the first 12 blocks
2279 if (pprev == NULL || pprev->nHeight < 12)
2282 const CBlockIndex* currentIndex = pprev;
2284 if(IsProofOfStake())
2286 // Return 1/3 of score if parent block is not the PoW block
2287 if (!pprev->IsProofOfWork())
2288 return (CBigNum(1)<<256) / (3 * (bnTarget+1));
2292 // Check last 12 blocks type
2293 while (pprev->nHeight - currentIndex->nHeight < 12)
2295 if (currentIndex->IsProofOfWork())
2297 currentIndex = currentIndex->pprev;
2300 // Return 1/3 of score if less than 3 PoW blocks found
2302 return (CBigNum(1)<<256) / (3 * (bnTarget+1));
2304 return (CBigNum(1)<<256) / (bnTarget+1);
2308 // Return bnPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2309 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2310 return bnPoWTrust + (2 * (pprev->bnChainTrust - pprev->pprev->bnChainTrust) / 3);
2314 // Check last 12 blocks type
2315 while (pprev->nHeight - currentIndex->nHeight < 12)
2317 if (currentIndex->IsProofOfStake())
2319 currentIndex = currentIndex->pprev;
2322 // Return bnPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2324 return bnPoWTrust + (2 * (pprev->bnChainTrust - pprev->pprev->bnChainTrust) / 3);
2326 bnTarget.SetCompact(pprev->nBits);
2331 // Return bnPoWTrust + full trust score for previous block nBits
2332 return bnPoWTrust + (CBigNum(1)<<256) / (bnTarget+1);
2336 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2338 unsigned int nFound = 0;
2339 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2341 if (pstart->nVersion >= minVersion)
2343 pstart = pstart->pprev;
2345 return (nFound >= nRequired);
2348 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2350 // Check for duplicate
2351 uint256 hash = pblock->GetHash();
2352 if (mapBlockIndex.count(hash))
2353 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2354 if (mapOrphanBlocks.count(hash))
2355 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2357 // ppcoin: check proof-of-stake
2358 // Limited duplicity on stake: prevents block flood attack
2359 // Duplicate stake allowed only when there is orphan child block
2360 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2361 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());
2363 // Preliminary checks
2364 if (!pblock->CheckBlock())
2365 return error("ProcessBlock() : CheckBlock FAILED");
2367 // ppcoin: verify hash target and signature of coinstake tx
2368 if (pblock->IsProofOfStake())
2370 uint256 hashProofOfStake = 0;
2371 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake))
2373 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2374 return false; // do not error here as we expect this during initial block download
2376 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2377 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2380 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2381 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2383 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2384 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2386 bnNewBlock.SetCompact(pblock->nBits);
2388 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime));
2389 if (bnNewBlock > bnRequired)
2392 pfrom->Misbehaving(100);
2393 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2397 // ppcoin: ask for pending sync-checkpoint if any
2398 if (!IsInitialBlockDownload())
2399 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2401 // If don't already have its previous block, shunt it off to holding area until we get it
2402 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2404 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2405 CBlock* pblock2 = new CBlock(*pblock);
2406 // ppcoin: check proof-of-stake
2407 if (pblock2->IsProofOfStake())
2409 // Limited duplicity on stake: prevents block flood attack
2410 // Duplicate stake allowed only when there is orphan child block
2411 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2412 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());
2414 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2416 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2417 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2419 // Ask this guy to fill in what we're missing
2422 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2423 // ppcoin: getblocks may not obtain the ancestor block rejected
2424 // earlier by duplicate-stake check so we ask for it again directly
2425 if (!IsInitialBlockDownload())
2426 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2432 if (!pblock->AcceptBlock())
2433 return error("ProcessBlock() : AcceptBlock FAILED");
2435 // Recursively process any orphan blocks that depended on this one
2436 vector<uint256> vWorkQueue;
2437 vWorkQueue.push_back(hash);
2438 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2440 uint256 hashPrev = vWorkQueue[i];
2441 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2442 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2445 CBlock* pblockOrphan = (*mi).second;
2446 if (pblockOrphan->AcceptBlock())
2447 vWorkQueue.push_back(pblockOrphan->GetHash());
2448 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2449 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2450 delete pblockOrphan;
2452 mapOrphanBlocksByPrev.erase(hashPrev);
2455 printf("ProcessBlock: ACCEPTED\n");
2457 // ppcoin: if responsible for sync-checkpoint send it
2458 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2459 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2464 // ppcoin: sign block
2465 bool CBlock::SignBlock(const CKeyStore& keystore)
2467 vector<valtype> vSolutions;
2468 txnouttype whichType;
2470 if(!IsProofOfStake())
2472 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2474 const CTxOut& txout = vtx[0].vout[i];
2476 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2479 if (whichType == TX_PUBKEY)
2482 valtype& vchPubKey = vSolutions[0];
2485 if (!keystore.GetKey(Hash160(vchPubKey), key))
2487 if (key.GetPubKey() != vchPubKey)
2489 if(!key.Sign(GetHash(), vchBlockSig))
2498 const CTxOut& txout = vtx[1].vout[1];
2500 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2503 if (whichType == TX_PUBKEY)
2506 valtype& vchPubKey = vSolutions[0];
2509 if (!keystore.GetKey(Hash160(vchPubKey), key))
2511 if (key.GetPubKey() != vchPubKey)
2514 return key.Sign(GetHash(), vchBlockSig);
2518 printf("Sign failed\n");
2522 // ppcoin: check block signature
2523 bool CBlock::CheckBlockSignature() const
2525 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2526 return vchBlockSig.empty();
2528 vector<valtype> vSolutions;
2529 txnouttype whichType;
2531 if(IsProofOfStake())
2533 const CTxOut& txout = vtx[1].vout[1];
2535 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2537 if (whichType == TX_PUBKEY)
2539 valtype& vchPubKey = vSolutions[0];
2541 if (!key.SetPubKey(vchPubKey))
2543 if (vchBlockSig.empty())
2545 return key.Verify(GetHash(), vchBlockSig);
2550 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2552 const CTxOut& txout = vtx[0].vout[i];
2554 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2557 if (whichType == TX_PUBKEY)
2560 valtype& vchPubKey = vSolutions[0];
2562 if (!key.SetPubKey(vchPubKey))
2564 if (vchBlockSig.empty())
2566 if(!key.Verify(GetHash(), vchBlockSig))
2576 bool CheckDiskSpace(uint64 nAdditionalBytes)
2578 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2580 // Check for nMinDiskSpace bytes (currently 50MB)
2581 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2584 string strMessage = _("Warning: Disk space is low!");
2585 strMiscWarning = strMessage;
2586 printf("*** %s\n", strMessage.c_str());
2587 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2594 static filesystem::path BlockFilePath(unsigned int nFile)
2596 string strBlockFn = strprintf("blk%04u.dat", nFile);
2597 return GetDataDir() / strBlockFn;
2600 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2602 if ((nFile < 1) || (nFile == (unsigned int) -1))
2604 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2607 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2609 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2618 static unsigned int nCurrentBlockFile = 1;
2620 FILE* AppendBlockFile(unsigned int& nFileRet)
2625 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2628 if (fseek(file, 0, SEEK_END) != 0)
2630 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2631 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2633 nFileRet = nCurrentBlockFile;
2637 nCurrentBlockFile++;
2641 bool LoadBlockIndex(bool fAllowNew)
2645 pchMessageStart[0] = 0xcd;
2646 pchMessageStart[1] = 0xf2;
2647 pchMessageStart[2] = 0xc0;
2648 pchMessageStart[3] = 0xef;
2650 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2651 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2652 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2653 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2654 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2661 if (!txdb.LoadBlockIndex())
2666 // Init with genesis block
2668 if (mapBlockIndex.empty())
2677 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2678 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2679 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2681 // vMerkleTree: 4cb33b3b6a
2685 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2686 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2687 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2689 // vMerkleTree: 4cb33b3b6a
2691 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2693 txNew.nTime = 1360105017;
2694 txNew.vin.resize(1);
2695 txNew.vout.resize(1);
2696 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2697 txNew.vout[0].SetEmpty();
2699 block.vtx.push_back(txNew);
2700 block.hashPrevBlock = 0;
2701 block.hashMerkleRoot = block.BuildMerkleTree();
2703 block.nTime = 1360105017;
2704 block.nBits = bnProofOfWorkLimit.GetCompact();
2705 block.nNonce = !fTestNet ? 1575379 : 46534;
2708 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2710 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2711 assert(block.CheckBlock());
2713 // Start new block file
2715 unsigned int nBlockPos;
2716 if (!block.WriteToDisk(nFile, nBlockPos))
2717 return error("LoadBlockIndex() : writing genesis block to disk failed");
2718 if (!block.AddToBlockIndex(nFile, nBlockPos))
2719 return error("LoadBlockIndex() : genesis block not accepted");
2721 // ppcoin: initialize synchronized checkpoint
2722 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2723 return error("LoadBlockIndex() : failed to init sync checkpoint");
2726 // ppcoin: if checkpoint master key changed must reset sync-checkpoint
2729 string strPubKey = "";
2730 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2732 // write checkpoint master key to db
2734 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2735 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2736 if (!txdb.TxnCommit())
2737 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2738 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2739 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2749 void PrintBlockTree()
2751 // pre-compute tree structure
2752 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2753 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2755 CBlockIndex* pindex = (*mi).second;
2756 mapNext[pindex->pprev].push_back(pindex);
2758 //while (rand() % 3 == 0)
2759 // mapNext[pindex->pprev].push_back(pindex);
2762 vector<pair<int, CBlockIndex*> > vStack;
2763 vStack.push_back(make_pair(0, pindexGenesisBlock));
2766 while (!vStack.empty())
2768 int nCol = vStack.back().first;
2769 CBlockIndex* pindex = vStack.back().second;
2772 // print split or gap
2773 if (nCol > nPrevCol)
2775 for (int i = 0; i < nCol-1; i++)
2779 else if (nCol < nPrevCol)
2781 for (int i = 0; i < nCol; i++)
2788 for (int i = 0; i < nCol; i++)
2793 block.ReadFromDisk(pindex);
2794 printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
2798 block.GetHash().ToString().c_str(),
2800 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2801 FormatMoney(pindex->nMint).c_str(),
2804 PrintWallets(block);
2806 // put the main time-chain first
2807 vector<CBlockIndex*>& vNext = mapNext[pindex];
2808 for (unsigned int i = 0; i < vNext.size(); i++)
2810 if (vNext[i]->pnext)
2812 swap(vNext[0], vNext[i]);
2818 for (unsigned int i = 0; i < vNext.size(); i++)
2819 vStack.push_back(make_pair(nCol+i, vNext[i]));
2823 bool LoadExternalBlockFile(FILE* fileIn)
2825 int64 nStart = GetTimeMillis();
2831 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
2832 unsigned int nPos = 0;
2833 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
2835 unsigned char pchData[65536];
2837 fseek(blkdat, nPos, SEEK_SET);
2838 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
2841 nPos = (unsigned int)-1;
2844 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
2847 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
2849 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
2852 nPos += ((unsigned char*)nFind - pchData) + 1;
2855 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
2856 } while(!fRequestShutdown);
2857 if (nPos == (unsigned int)-1)
2859 fseek(blkdat, nPos, SEEK_SET);
2862 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
2866 if (ProcessBlock(NULL,&block))
2874 catch (std::exception &e) {
2875 printf("%s() : Deserialize or I/O error caught during load\n",
2876 __PRETTY_FUNCTION__);
2879 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
2891 //////////////////////////////////////////////////////////////////////////////
2896 extern map<uint256, CAlert> mapAlerts;
2897 extern CCriticalSection cs_mapAlerts;
2899 static string strMintMessage = "Info: Minting suspended due to locked wallet.";
2900 static string strMintWarning;
2902 string GetWarnings(string strFor)
2905 string strStatusBar;
2908 if (GetBoolArg("-testsafemode"))
2911 // ppcoin: wallet lock warning for minting
2912 if (strMintWarning != "")
2915 strStatusBar = strMintWarning;
2918 // Misc warnings like out of disk space and clock is wrong
2919 if (strMiscWarning != "")
2922 strStatusBar = strMiscWarning;
2925 // ppcoin: should not enter safe mode for longer invalid chain
2926 // ppcoin: if sync-checkpoint is too old do not enter safe mode
2927 if (Checkpoints::IsSyncCheckpointTooOld(60 * 60 * 24 * 10) && !fTestNet && !IsInitialBlockDownload())
2930 strStatusBar = "WARNING: Checkpoint is too old. Wait for block chain to download, or notify developers.";
2933 // ppcoin: if detected invalid checkpoint enter safe mode
2934 if (Checkpoints::hashInvalidCheckpoint != 0)
2937 strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.";
2943 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2945 const CAlert& alert = item.second;
2946 if (alert.AppliesToMe() && alert.nPriority > nPriority)
2948 nPriority = alert.nPriority;
2949 strStatusBar = alert.strStatusBar;
2950 if (nPriority > 1000)
2951 strRPC = strStatusBar; // ppcoin: safe mode for high alert
2956 if (strFor == "statusbar")
2957 return strStatusBar;
2958 else if (strFor == "rpc")
2960 assert(!"GetWarnings() : invalid parameter");
2971 //////////////////////////////////////////////////////////////////////////////
2977 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
2983 bool txInMap = false;
2986 txInMap = (mempool.exists(inv.hash));
2989 mapOrphanTransactions.count(inv.hash) ||
2990 txdb.ContainsTx(inv.hash);
2994 return mapBlockIndex.count(inv.hash) ||
2995 mapOrphanBlocks.count(inv.hash);
2997 // Don't know what it is, just say we already got one
3004 // The message start string is designed to be unlikely to occur in normal data.
3005 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3006 // a large 4-byte int at any alignment.
3007 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3009 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3011 static map<CService, CPubKey> mapReuseKey;
3012 RandAddSeedPerfmon();
3014 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3015 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3017 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3025 if (strCommand == "version")
3027 // Each connection can only send one version message
3028 if (pfrom->nVersion != 0)
3030 pfrom->Misbehaving(1);
3038 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3039 if (pfrom->nVersion < MIN_PROTO_VERSION)
3041 // Since February 20, 2012, the protocol is initiated at version 209,
3042 // and earlier versions are no longer supported
3043 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3044 pfrom->fDisconnect = true;
3048 if (pfrom->nVersion == 10300)
3049 pfrom->nVersion = 300;
3051 vRecv >> addrFrom >> nNonce;
3053 vRecv >> pfrom->strSubVer;
3055 vRecv >> pfrom->nStartingHeight;
3057 if (pfrom->fInbound && addrMe.IsRoutable())
3059 pfrom->addrLocal = addrMe;
3063 // Disconnect if we connected to ourself
3064 if (nNonce == nLocalHostNonce && nNonce > 1)
3066 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3067 pfrom->fDisconnect = true;
3071 // ppcoin: record my external IP reported by peer
3072 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3073 addrSeenByPeer = addrMe;
3075 // Be shy and don't send version until we hear
3076 if (pfrom->fInbound)
3077 pfrom->PushVersion();
3079 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3081 AddTimeData(pfrom->addr, nTime);
3084 pfrom->PushMessage("verack");
3085 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3087 if (!pfrom->fInbound)
3089 // Advertise our address
3090 if (!fNoListen && !IsInitialBlockDownload())
3092 CAddress addr = GetLocalAddress(&pfrom->addr);
3093 if (addr.IsRoutable())
3094 pfrom->PushAddress(addr);
3097 // Get recent addresses
3098 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3100 pfrom->PushMessage("getaddr");
3101 pfrom->fGetAddr = true;
3103 addrman.Good(pfrom->addr);
3105 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3107 addrman.Add(addrFrom, addrFrom);
3108 addrman.Good(addrFrom);
3112 // Ask the first connected node for block updates
3113 static int nAskedForBlocks = 0;
3114 if (!pfrom->fClient && !pfrom->fOneShot &&
3115 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3116 (pfrom->nVersion < NOBLKS_VERSION_START ||
3117 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3118 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3121 pfrom->PushGetBlocks(pindexBest, uint256(0));
3127 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3128 item.second.RelayTo(pfrom);
3131 // ppcoin: relay sync-checkpoint
3133 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3134 if (!Checkpoints::checkpointMessage.IsNull())
3135 Checkpoints::checkpointMessage.RelayTo(pfrom);
3138 pfrom->fSuccessfullyConnected = true;
3140 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());
3142 cPeerBlockCounts.input(pfrom->nStartingHeight);
3144 // ppcoin: ask for pending sync-checkpoint if any
3145 if (!IsInitialBlockDownload())
3146 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3150 else if (pfrom->nVersion == 0)
3152 // Must have a version message before anything else
3153 pfrom->Misbehaving(1);
3158 else if (strCommand == "verack")
3160 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3164 else if (strCommand == "addr")
3166 vector<CAddress> vAddr;
3169 // Don't want addr from older versions unless seeding
3170 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3172 if (vAddr.size() > 1000)
3174 pfrom->Misbehaving(20);
3175 return error("message addr size() = %"PRIszu"", vAddr.size());
3178 // Store the new addresses
3179 vector<CAddress> vAddrOk;
3180 int64 nNow = GetAdjustedTime();
3181 int64 nSince = nNow - 10 * 60;
3182 BOOST_FOREACH(CAddress& addr, vAddr)
3186 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3187 addr.nTime = nNow - 5 * 24 * 60 * 60;
3188 pfrom->AddAddressKnown(addr);
3189 bool fReachable = IsReachable(addr);
3190 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3192 // Relay to a limited number of other nodes
3195 // Use deterministic randomness to send to the same nodes for 24 hours
3196 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3197 static uint256 hashSalt;
3199 hashSalt = GetRandHash();
3200 uint64 hashAddr = addr.GetHash();
3201 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3202 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3203 multimap<uint256, CNode*> mapMix;
3204 BOOST_FOREACH(CNode* pnode, vNodes)
3206 if (pnode->nVersion < CADDR_TIME_VERSION)
3208 unsigned int nPointer;
3209 memcpy(&nPointer, &pnode, sizeof(nPointer));
3210 uint256 hashKey = hashRand ^ nPointer;
3211 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3212 mapMix.insert(make_pair(hashKey, pnode));
3214 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3215 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3216 ((*mi).second)->PushAddress(addr);
3219 // Do not store addresses outside our network
3221 vAddrOk.push_back(addr);
3223 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3224 if (vAddr.size() < 1000)
3225 pfrom->fGetAddr = false;
3226 if (pfrom->fOneShot)
3227 pfrom->fDisconnect = true;
3231 else if (strCommand == "inv")
3235 if (vInv.size() > MAX_INV_SZ)
3237 pfrom->Misbehaving(20);
3238 return error("message inv size() = %"PRIszu"", vInv.size());
3241 // find last block in inv vector
3242 unsigned int nLastBlock = (unsigned int)(-1);
3243 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3244 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3245 nLastBlock = vInv.size() - 1 - nInv;
3250 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3252 const CInv &inv = vInv[nInv];
3256 pfrom->AddInventoryKnown(inv);
3258 bool fAlreadyHave = AlreadyHave(txdb, inv);
3260 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3264 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3265 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3266 } else if (nInv == nLastBlock) {
3267 // In case we are on a very long side-chain, it is possible that we already have
3268 // the last block in an inv bundle sent in response to getblocks. Try to detect
3269 // this situation and push another getblocks to continue.
3270 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3272 printf("force request: %s\n", inv.ToString().c_str());
3275 // Track requests for our stuff
3276 Inventory(inv.hash);
3281 else if (strCommand == "getdata")
3285 if (vInv.size() > MAX_INV_SZ)
3287 pfrom->Misbehaving(20);
3288 return error("message getdata size() = %"PRIszu"", vInv.size());
3291 if (fDebugNet || (vInv.size() != 1))
3292 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3294 BOOST_FOREACH(const CInv& inv, vInv)
3298 if (fDebugNet || (vInv.size() == 1))
3299 printf("received getdata for: %s\n", inv.ToString().c_str());
3301 if (inv.type == MSG_BLOCK)
3303 // Send block from disk
3304 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3305 if (mi != mapBlockIndex.end())
3308 block.ReadFromDisk((*mi).second);
3309 pfrom->PushMessage("block", block);
3311 // Trigger them to send a getblocks request for the next batch of inventory
3312 if (inv.hash == pfrom->hashContinue)
3314 // ppcoin: send latest proof-of-work block to allow the
3315 // download node to accept as orphan (proof-of-stake
3316 // block might be rejected by stake connection check)
3318 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3319 pfrom->PushMessage("inv", vInv);
3320 pfrom->hashContinue = 0;
3324 else if (inv.IsKnownType())
3326 // Send stream from relay memory
3327 bool pushed = false;
3330 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3331 if (mi != mapRelay.end()) {
3332 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3336 if (!pushed && inv.type == MSG_TX) {
3338 if (mempool.exists(inv.hash)) {
3339 CTransaction tx = mempool.lookup(inv.hash);
3340 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3343 pfrom->PushMessage("tx", ss);
3348 // Track requests for our stuff
3349 Inventory(inv.hash);
3354 else if (strCommand == "getblocks")
3356 CBlockLocator locator;
3358 vRecv >> locator >> hashStop;
3360 // Find the last block the caller has in the main chain
3361 CBlockIndex* pindex = locator.GetBlockIndex();
3363 // Send the rest of the chain
3365 pindex = pindex->pnext;
3367 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3368 for (; pindex; pindex = pindex->pnext)
3370 if (pindex->GetBlockHash() == hashStop)
3372 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3373 // ppcoin: tell downloading node about the latest block if it's
3374 // without risk being rejected due to stake connection check
3375 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3376 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3379 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3382 // When this block is requested, we'll send an inv that'll make them
3383 // getblocks the next batch of inventory.
3384 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3385 pfrom->hashContinue = pindex->GetBlockHash();
3390 else if (strCommand == "checkpoint")
3392 CSyncCheckpoint checkpoint;
3393 vRecv >> checkpoint;
3395 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3398 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3400 BOOST_FOREACH(CNode* pnode, vNodes)
3401 checkpoint.RelayTo(pnode);
3405 else if (strCommand == "getheaders")
3407 CBlockLocator locator;
3409 vRecv >> locator >> hashStop;
3411 CBlockIndex* pindex = NULL;
3412 if (locator.IsNull())
3414 // If locator is null, return the hashStop block
3415 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3416 if (mi == mapBlockIndex.end())
3418 pindex = (*mi).second;
3422 // Find the last block the caller has in the main chain
3423 pindex = locator.GetBlockIndex();
3425 pindex = pindex->pnext;
3428 vector<CBlock> vHeaders;
3430 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3431 for (; pindex; pindex = pindex->pnext)
3433 vHeaders.push_back(pindex->GetBlockHeader());
3434 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3437 pfrom->PushMessage("headers", vHeaders);
3441 else if (strCommand == "tx")
3443 vector<uint256> vWorkQueue;
3444 vector<uint256> vEraseQueue;
3445 CDataStream vMsg(vRecv);
3450 CInv inv(MSG_TX, tx.GetHash());
3451 pfrom->AddInventoryKnown(inv);
3453 // Truncate messages to the size of the tx in them
3454 unsigned int nSize = ::GetSerializeSize(tx,SER_NETWORK, PROTOCOL_VERSION);
3455 if (nSize < vMsg.size()){
3459 bool fMissingInputs = false;
3460 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3462 SyncWithWallets(tx, NULL, true);
3463 RelayMessage(inv, vMsg);
3464 mapAlreadyAskedFor.erase(inv);
3465 vWorkQueue.push_back(inv.hash);
3466 vEraseQueue.push_back(inv.hash);
3468 // Recursively process any orphan transactions that depended on this one
3469 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3471 uint256 hashPrev = vWorkQueue[i];
3472 for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3473 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3476 const CDataStream& vMsg = *((*mi).second);
3478 CDataStream(vMsg) >> tx;
3479 CInv inv(MSG_TX, tx.GetHash());
3480 bool fMissingInputs2 = false;
3482 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3484 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3485 SyncWithWallets(tx, NULL, true);
3486 RelayMessage(inv, vMsg);
3487 mapAlreadyAskedFor.erase(inv);
3488 vWorkQueue.push_back(inv.hash);
3489 vEraseQueue.push_back(inv.hash);
3491 else if (!fMissingInputs2)
3494 vEraseQueue.push_back(inv.hash);
3495 printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
3500 BOOST_FOREACH(uint256 hash, vEraseQueue)
3501 EraseOrphanTx(hash);
3503 else if (fMissingInputs)
3507 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3508 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3510 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3512 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3516 else if (strCommand == "block")
3521 printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
3524 CInv inv(MSG_BLOCK, block.GetHash());
3525 pfrom->AddInventoryKnown(inv);
3527 if (ProcessBlock(pfrom, &block))
3528 mapAlreadyAskedFor.erase(inv);
3529 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3533 else if (strCommand == "getaddr")
3535 pfrom->vAddrToSend.clear();
3536 vector<CAddress> vAddr = addrman.GetAddr();
3537 BOOST_FOREACH(const CAddress &addr, vAddr)
3538 pfrom->PushAddress(addr);
3542 else if (strCommand == "mempool")
3544 std::vector<uint256> vtxid;
3545 mempool.queryHashes(vtxid);
3547 for (unsigned int i = 0; i < vtxid.size(); i++) {
3548 CInv inv(MSG_TX, vtxid[i]);
3549 vInv.push_back(inv);
3550 if (i == (MAX_INV_SZ - 1))
3553 if (vInv.size() > 0)
3554 pfrom->PushMessage("inv", vInv);
3558 else if (strCommand == "checkorder")
3563 if (!GetBoolArg("-allowreceivebyip"))
3565 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3572 /// we have a chance to check the order here
3574 // Keep giving the same key to the same ip until they use it
3575 if (!mapReuseKey.count(pfrom->addr))
3576 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3578 // Send back approval of order and pubkey to use
3579 CScript scriptPubKey;
3580 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3581 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3585 else if (strCommand == "reply")
3590 CRequestTracker tracker;
3592 LOCK(pfrom->cs_mapRequests);
3593 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3594 if (mi != pfrom->mapRequests.end())
3596 tracker = (*mi).second;
3597 pfrom->mapRequests.erase(mi);
3600 if (!tracker.IsNull())
3601 tracker.fn(tracker.param1, vRecv);
3605 else if (strCommand == "ping")
3607 if (pfrom->nVersion > BIP0031_VERSION)
3611 // Echo the message back with the nonce. This allows for two useful features:
3613 // 1) A remote node can quickly check if the connection is operational
3614 // 2) Remote nodes can measure the latency of the network thread. If this node
3615 // is overloaded it won't respond to pings quickly and the remote node can
3616 // avoid sending us more work, like chain download requests.
3618 // The nonce stops the remote getting confused between different pings: without
3619 // it, if the remote node sends a ping once per second and this node takes 5
3620 // seconds to respond to each, the 5th ping the remote sends would appear to
3621 // return very quickly.
3622 pfrom->PushMessage("pong", nonce);
3627 else if (strCommand == "alert")
3632 uint256 alertHash = alert.GetHash();
3633 if (pfrom->setKnown.count(alertHash) == 0)
3635 if (alert.ProcessAlert())
3638 pfrom->setKnown.insert(alertHash);
3641 BOOST_FOREACH(CNode* pnode, vNodes)
3642 alert.RelayTo(pnode);
3646 // Small DoS penalty so peers that send us lots of
3647 // duplicate/expired/invalid-signature/whatever alerts
3648 // eventually get banned.
3649 // This isn't a Misbehaving(100) (immediate ban) because the
3650 // peer might be an older or different implementation with
3651 // a different signature key, etc.
3652 pfrom->Misbehaving(10);
3660 // Ignore unknown commands for extensibility
3664 // Update the last seen time for this node's address
3665 if (pfrom->fNetworkNode)
3666 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3667 AddressCurrentlyConnected(pfrom->addr);
3673 bool ProcessMessages(CNode* pfrom)
3675 CDataStream& vRecv = pfrom->vRecv;
3679 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3683 // (4) message start
3692 // Don't bother if send buffer is too full to respond anyway
3693 if (pfrom->vSend.size() >= SendBufferSize())
3696 // Scan for message start
3697 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3698 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3699 if (vRecv.end() - pstart < nHeaderSize)
3701 if ((int)vRecv.size() > nHeaderSize)
3703 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3704 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3708 if (pstart - vRecv.begin() > 0)
3709 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3710 vRecv.erase(vRecv.begin(), pstart);
3713 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3718 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3721 string strCommand = hdr.GetCommand();
3724 unsigned int nMessageSize = hdr.nMessageSize;
3725 if (nMessageSize > MAX_SIZE)
3727 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3730 if (nMessageSize > vRecv.size())
3732 // Rewind and wait for rest of message
3733 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3738 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3739 unsigned int nChecksum = 0;
3740 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3741 if (nChecksum != hdr.nChecksum)
3743 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3744 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3748 // Copy message to its own buffer
3749 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3750 vRecv.ignore(nMessageSize);
3758 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3763 catch (std::ios_base::failure& e)
3765 if (strstr(e.what(), "end of data"))
3767 // Allow exceptions from under-length message on vRecv
3768 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());
3770 else if (strstr(e.what(), "size too large"))
3772 // Allow exceptions from over-long size
3773 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3777 PrintExceptionContinue(&e, "ProcessMessages()");
3780 catch (std::exception& e) {
3781 PrintExceptionContinue(&e, "ProcessMessages()");
3783 PrintExceptionContinue(NULL, "ProcessMessages()");
3787 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3795 bool SendMessages(CNode* pto, bool fSendTrickle)
3797 TRY_LOCK(cs_main, lockMain);
3799 // Don't send anything until we get their version message
3800 if (pto->nVersion == 0)
3803 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3805 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3807 if (pto->nVersion > BIP0031_VERSION)
3808 pto->PushMessage("ping", nonce);
3810 pto->PushMessage("ping");
3813 // Resend wallet transactions that haven't gotten in a block yet
3814 ResendWalletTransactions();
3816 // Address refresh broadcast
3817 static int64 nLastRebroadcast;
3818 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3822 BOOST_FOREACH(CNode* pnode, vNodes)
3824 // Periodically clear setAddrKnown to allow refresh broadcasts
3825 if (nLastRebroadcast)
3826 pnode->setAddrKnown.clear();
3828 // Rebroadcast our address
3831 CAddress addr = GetLocalAddress(&pnode->addr);
3832 if (addr.IsRoutable())
3833 pnode->PushAddress(addr);
3837 nLastRebroadcast = GetTime();
3845 vector<CAddress> vAddr;
3846 vAddr.reserve(pto->vAddrToSend.size());
3847 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
3849 // returns true if wasn't already contained in the set
3850 if (pto->setAddrKnown.insert(addr).second)
3852 vAddr.push_back(addr);
3853 // receiver rejects addr messages larger than 1000
3854 if (vAddr.size() >= 1000)
3856 pto->PushMessage("addr", vAddr);
3861 pto->vAddrToSend.clear();
3863 pto->PushMessage("addr", vAddr);
3868 // Message: inventory
3871 vector<CInv> vInvWait;
3873 LOCK(pto->cs_inventory);
3874 vInv.reserve(pto->vInventoryToSend.size());
3875 vInvWait.reserve(pto->vInventoryToSend.size());
3876 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
3878 if (pto->setInventoryKnown.count(inv))
3881 // trickle out tx inv to protect privacy
3882 if (inv.type == MSG_TX && !fSendTrickle)
3884 // 1/4 of tx invs blast to all immediately
3885 static uint256 hashSalt;
3887 hashSalt = GetRandHash();
3888 uint256 hashRand = inv.hash ^ hashSalt;
3889 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3890 bool fTrickleWait = ((hashRand & 3) != 0);
3892 // always trickle our own transactions
3896 if (GetTransaction(inv.hash, wtx))
3898 fTrickleWait = true;
3903 vInvWait.push_back(inv);
3908 // returns true if wasn't already contained in the set
3909 if (pto->setInventoryKnown.insert(inv).second)
3911 vInv.push_back(inv);
3912 if (vInv.size() >= 1000)
3914 pto->PushMessage("inv", vInv);
3919 pto->vInventoryToSend = vInvWait;
3922 pto->PushMessage("inv", vInv);
3928 vector<CInv> vGetData;
3929 int64 nNow = GetTime() * 1000000;
3931 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
3933 const CInv& inv = (*pto->mapAskFor.begin()).second;
3934 if (!AlreadyHave(txdb, inv))
3937 printf("sending getdata: %s\n", inv.ToString().c_str());
3938 vGetData.push_back(inv);
3939 if (vGetData.size() >= 1000)
3941 pto->PushMessage("getdata", vGetData);
3944 mapAlreadyAskedFor[inv] = nNow;
3946 pto->mapAskFor.erase(pto->mapAskFor.begin());
3948 if (!vGetData.empty())
3949 pto->PushMessage("getdata", vGetData);
3968 //////////////////////////////////////////////////////////////////////////////
3973 int static FormatHashBlocks(void* pbuffer, unsigned int len)
3975 unsigned char* pdata = (unsigned char*)pbuffer;
3976 unsigned int blocks = 1 + ((len + 8) / 64);
3977 unsigned char* pend = pdata + 64 * blocks;
3978 memset(pdata + len, 0, 64 * blocks - len);
3980 unsigned int bits = len * 8;
3981 pend[-1] = (bits >> 0) & 0xff;
3982 pend[-2] = (bits >> 8) & 0xff;
3983 pend[-3] = (bits >> 16) & 0xff;
3984 pend[-4] = (bits >> 24) & 0xff;
3988 static const unsigned int pSHA256InitState[8] =
3989 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
3991 void SHA256Transform(void* pstate, void* pinput, const void* pinit)
3994 unsigned char data[64];
3998 for (int i = 0; i < 16; i++)
3999 ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
4001 for (int i = 0; i < 8; i++)
4002 ctx.h[i] = ((uint32_t*)pinit)[i];
4004 SHA256_Update(&ctx, data, sizeof(data));
4005 for (int i = 0; i < 8; i++)
4006 ((uint32_t*)pstate)[i] = ctx.h[i];
4009 // Some explaining would be appreciated
4014 set<uint256> setDependsOn;
4018 COrphan(CTransaction* ptxIn)
4021 dPriority = dFeePerKb = 0;
4026 printf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
4027 ptx->GetHash().ToString().substr(0,10).c_str(), dPriority, dFeePerKb);
4028 BOOST_FOREACH(uint256 hash, setDependsOn)
4029 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
4034 uint64 nLastBlockTx = 0;
4035 uint64 nLastBlockSize = 0;
4036 int64 nLastCoinStakeSearchInterval = 0;
4038 // We want to sort transactions by priority and fee, so:
4039 typedef boost::tuple<double, double, CTransaction*> TxPriority;
4040 class TxPriorityCompare
4044 TxPriorityCompare(bool _byFee) : byFee(_byFee) { }
4045 bool operator()(const TxPriority& a, const TxPriority& b)
4049 if (a.get<1>() == b.get<1>())
4050 return a.get<0>() < b.get<0>();
4051 return a.get<1>() < b.get<1>();
4055 if (a.get<0>() == b.get<0>())
4056 return a.get<1>() < b.get<1>();
4057 return a.get<0>() < b.get<0>();
4063 // fProofOfStake: try (best effort) to make a proof-of-stake block
4064 CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
4066 CReserveKey reservekey(pwallet);
4069 auto_ptr<CBlock> pblock(new CBlock());
4073 // Create coinbase tx
4075 txNew.vin.resize(1);
4076 txNew.vin[0].prevout.SetNull();
4077 txNew.vout.resize(1);
4078 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
4080 // Add our coinbase tx as first transaction
4081 pblock->vtx.push_back(txNew);
4083 // Largest block you're willing to create:
4084 unsigned int nBlockMaxSize = GetArg("-blockmaxsize", MAX_BLOCK_SIZE_GEN/2);
4085 // Limit to betweeen 1K and MAX_BLOCK_SIZE-1K for sanity:
4086 nBlockMaxSize = std::max((unsigned int)1000, std::min((unsigned int)(MAX_BLOCK_SIZE-1000), nBlockMaxSize));
4088 // Special compatibility rule before 20 Aug: limit size to 500,000 bytes:
4089 if (GetAdjustedTime() < LOCKS_SWITCH_TIME)
4090 nBlockMaxSize = std::min(nBlockMaxSize, (unsigned int)(MAX_BLOCK_SIZE_GEN));
4092 // How much of the block should be dedicated to high-priority transactions,
4093 // included regardless of the fees they pay
4094 unsigned int nBlockPrioritySize = GetArg("-blockprioritysize", 27000);
4095 nBlockPrioritySize = std::min(nBlockMaxSize, nBlockPrioritySize);
4097 // Minimum block size you want to create; block will be filled with free transactions
4098 // until there are no more or the block reaches this size:
4099 unsigned int nBlockMinSize = GetArg("-blockminsize", 0);
4100 nBlockMinSize = std::min(nBlockMaxSize, nBlockMinSize);
4102 // Fee-per-kilobyte amount considered the same as "free"
4103 // Be careful setting this: if you set it to zero then
4104 // a transaction spammer can cheaply fill blocks using
4105 // 1-satoshi-fee transactions. It should be set above the real
4106 // cost to you of processing a transaction.
4107 int64 nMinTxFee = MIN_TX_FEE;
4108 if (mapArgs.count("-mintxfee"))
4109 ParseMoney(mapArgs["-mintxfee"], nMinTxFee);
4111 // ppcoin: if coinstake available add coinstake tx
4112 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
4113 CBlockIndex* pindexPrev = pindexBest;
4115 if (fProofOfStake) // attempt to find a coinstake
4117 pblock->nBits = GetNextTargetRequired(pindexPrev, true);
4118 CTransaction txCoinStake;
4119 int64 nSearchTime = txCoinStake.nTime; // search to current time
4120 if (nSearchTime > nLastCoinStakeSearchTime)
4122 if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
4124 if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
4125 { // make sure coinstake would meet timestamp protocol
4126 // as it would be the same as the block timestamp
4127 pblock->vtx[0].vout[0].SetEmpty();
4128 pblock->vtx[0].nTime = txCoinStake.nTime;
4129 pblock->vtx.push_back(txCoinStake);
4132 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
4133 nLastCoinStakeSearchTime = nSearchTime;
4137 pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
4139 // Collect memory pool transactions into the block
4142 LOCK2(cs_main, mempool.cs);
4143 CBlockIndex* pindexPrev = pindexBest;
4146 // Priority order to process transactions
4147 list<COrphan> vOrphan; // list memory doesn't move
4148 map<uint256, vector<COrphan*> > mapDependers;
4150 // This vector will be sorted into a priority queue:
4151 vector<TxPriority> vecPriority;
4152 vecPriority.reserve(mempool.mapTx.size());
4153 for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
4155 CTransaction& tx = (*mi).second;
4156 if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
4159 COrphan* porphan = NULL;
4160 double dPriority = 0;
4162 bool fMissingInputs = false;
4163 BOOST_FOREACH(const CTxIn& txin, tx.vin)
4165 // Read prev transaction
4166 CTransaction txPrev;
4168 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
4170 // This should never happen; all transactions in the memory
4171 // pool should connect to either transactions in the chain
4172 // or other transactions in the memory pool.
4173 if (!mempool.mapTx.count(txin.prevout.hash))
4175 printf("ERROR: mempool transaction missing input\n");
4176 if (fDebug) assert("mempool transaction missing input" == 0);
4177 fMissingInputs = true;
4183 // Has to wait for dependencies
4186 // Use list for automatic deletion
4187 vOrphan.push_back(COrphan(&tx));
4188 porphan = &vOrphan.back();
4190 mapDependers[txin.prevout.hash].push_back(porphan);
4191 porphan->setDependsOn.insert(txin.prevout.hash);
4192 nTotalIn += mempool.mapTx[txin.prevout.hash].vout[txin.prevout.n].nValue;
4195 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
4196 nTotalIn += nValueIn;
4198 int nConf = txindex.GetDepthInMainChain();
4199 dPriority += (double)nValueIn * nConf;
4201 if (fMissingInputs) continue;
4203 // Priority is sum(valuein * age) / txsize
4204 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4205 dPriority /= nTxSize;
4207 // This is a more accurate fee-per-kilobyte than is used by the client code, because the
4208 // client code rounds up the size to the nearest 1K. That's good, because it gives an
4209 // incentive to create smaller transactions.
4210 double dFeePerKb = double(nTotalIn-tx.GetValueOut()) / (double(nTxSize)/1000.0);
4214 porphan->dPriority = dPriority;
4215 porphan->dFeePerKb = dFeePerKb;
4218 vecPriority.push_back(TxPriority(dPriority, dFeePerKb, &(*mi).second));
4221 // Collect transactions into block
4222 map<uint256, CTxIndex> mapTestPool;
4223 uint64 nBlockSize = 1000;
4224 uint64 nBlockTx = 0;
4225 int nBlockSigOps = 100;
4226 bool fSortedByFee = (nBlockPrioritySize <= 0);
4228 TxPriorityCompare comparer(fSortedByFee);
4229 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4231 while (!vecPriority.empty())
4233 // Take highest priority transaction off the priority queue:
4234 double dPriority = vecPriority.front().get<0>();
4235 double dFeePerKb = vecPriority.front().get<1>();
4236 CTransaction& tx = *(vecPriority.front().get<2>());
4238 std::pop_heap(vecPriority.begin(), vecPriority.end(), comparer);
4239 vecPriority.pop_back();
4242 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
4243 if (nBlockSize + nTxSize >= nBlockMaxSize)
4246 // Legacy limits on sigOps:
4247 unsigned int nTxSigOps = tx.GetLegacySigOpCount();
4248 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4252 if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
4255 // ppcoin: simplify transaction fee - allow free = false
4256 int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
4258 // Skip free transactions if we're past the minimum block size:
4259 if (fSortedByFee && (dFeePerKb < nMinTxFee) && (nBlockSize + nTxSize >= nBlockMinSize))
4262 // Prioritize by fee once past the priority size or we run out of high-priority
4264 if (!fSortedByFee &&
4265 ((nBlockSize + nTxSize >= nBlockPrioritySize) || (dPriority < COIN * 144 / 250)))
4267 fSortedByFee = true;
4268 comparer = TxPriorityCompare(fSortedByFee);
4269 std::make_heap(vecPriority.begin(), vecPriority.end(), comparer);
4272 // Connecting shouldn't fail due to dependency on other memory pool transactions
4273 // because we're already processing them in order of dependency
4274 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
4275 MapPrevTx mapInputs;
4277 if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
4280 int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
4281 if (nTxFees < nMinFee)
4284 nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
4285 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
4288 if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
4290 mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
4291 swap(mapTestPool, mapTestPoolTmp);
4294 pblock->vtx.push_back(tx);
4295 nBlockSize += nTxSize;
4297 nBlockSigOps += nTxSigOps;
4300 if (fDebug && GetBoolArg("-printpriority"))
4302 printf("priority %.1f feeperkb %.1f txid %s\n",
4303 dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
4306 // Add transactions that depend on this one to the priority queue
4307 uint256 hash = tx.GetHash();
4308 if (mapDependers.count(hash))
4310 BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
4312 if (!porphan->setDependsOn.empty())
4314 porphan->setDependsOn.erase(hash);
4315 if (porphan->setDependsOn.empty())
4317 vecPriority.push_back(TxPriority(porphan->dPriority, porphan->dFeePerKb, porphan->ptx));
4318 std::push_heap(vecPriority.begin(), vecPriority.end(), comparer);
4325 nLastBlockTx = nBlockTx;
4326 nLastBlockSize = nBlockSize;
4328 if (fDebug && GetBoolArg("-printpriority"))
4329 printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
4331 if (pblock->IsProofOfWork())
4332 pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pblock->nBits);
4335 pblock->hashPrevBlock = pindexPrev->GetBlockHash();
4336 if (pblock->IsProofOfStake())
4337 pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
4338 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
4339 pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
4340 if (pblock->IsProofOfWork())
4341 pblock->UpdateTime(pindexPrev);
4345 return pblock.release();
4349 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
4351 // Update nExtraNonce
4352 static uint256 hashPrevBlock;
4353 if (hashPrevBlock != pblock->hashPrevBlock)
4356 hashPrevBlock = pblock->hashPrevBlock;
4359 unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2
4360 pblock->vtx[0].vin[0].scriptSig = (CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
4361 assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
4363 pblock->hashMerkleRoot = pblock->BuildMerkleTree();
4367 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
4370 // Pre-build hash buffers
4377 uint256 hashPrevBlock;
4378 uint256 hashMerkleRoot;
4381 unsigned int nNonce;
4384 unsigned char pchPadding0[64];
4386 unsigned char pchPadding1[64];
4389 memset(&tmp, 0, sizeof(tmp));
4391 tmp.block.nVersion = pblock->nVersion;
4392 tmp.block.hashPrevBlock = pblock->hashPrevBlock;
4393 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
4394 tmp.block.nTime = pblock->nTime;
4395 tmp.block.nBits = pblock->nBits;
4396 tmp.block.nNonce = pblock->nNonce;
4398 FormatHashBlocks(&tmp.block, sizeof(tmp.block));
4399 FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
4401 // Byte swap all the input buffer
4402 for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
4403 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
4405 // Precalc the first half of the first hash, which stays constant
4406 SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
4408 memcpy(pdata, &tmp.block, 128);
4409 memcpy(phash1, &tmp.hash1, 64);
4413 bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
4415 uint256 hash = pblock->GetHash();
4416 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
4418 if (hash > hashTarget && pblock->IsProofOfWork())
4419 return error("BitcoinMiner : proof-of-work not meeting target");
4422 printf("BitcoinMiner:\n");
4423 printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
4425 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
4430 if (pblock->hashPrevBlock != hashBestChain)
4431 return error("BitcoinMiner : generated block is stale");
4433 // Remove key from key pool
4434 reservekey.KeepKey();
4436 // Track how many getdata requests this block gets
4438 LOCK(wallet.cs_wallet);
4439 wallet.mapRequestCount[pblock->GetHash()] = 0;
4442 // Process this block the same as if we had received it from another node
4443 if (!ProcessBlock(NULL, pblock))
4444 return error("BitcoinMiner : ProcessBlock, block not accepted");
4450 void BitcoinMiner(CWallet *pwallet, bool fProofOfStake)
4452 SetThreadPriority(THREAD_PRIORITY_LOWEST);
4454 // Make this thread recognisable as the mining thread
4455 RenameThread("bitcoin-miner");
4457 // Each thread has its own key and counter
4458 CReserveKey reservekey(pwallet);
4459 unsigned int nExtraNonce = 0;
4461 while (fProofOfStake)
4465 while (vNodes.empty() || IsInitialBlockDownload())
4474 while (pwallet->IsLocked())
4476 strMintWarning = strMintMessage;
4479 strMintWarning = "";
4484 CBlockIndex* pindexPrev = pindexBest;
4486 auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
4489 IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
4493 // ppcoin: if proof-of-stake block found then process block
4494 if (pblock->IsProofOfStake())
4496 if (!pblock->SignBlock(*pwalletMain))
4498 strMintWarning = strMintMessage;
4501 strMintWarning = "";
4502 printf("StakeMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
4503 SetThreadPriority(THREAD_PRIORITY_NORMAL);
4504 CheckWork(pblock.get(), *pwalletMain, reservekey);
4505 SetThreadPriority(THREAD_PRIORITY_LOWEST);