1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
12 #include "ui_interface.h"
13 #include "checkqueue.h"
15 #include <boost/algorithm/string/replace.hpp>
16 #include <boost/filesystem.hpp>
17 #include <boost/filesystem/fstream.hpp>
22 using namespace boost;
26 CCriticalSection cs_setpwalletRegistered;
27 set<CWallet*> setpwalletRegistered;
29 CCriticalSection cs_main;
32 unsigned int nTransactionsUpdated = 0;
34 map<uint256, CBlockIndex*> mapBlockIndex;
35 set<pair<COutPoint, unsigned int> > setStakeSeen;
37 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
38 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
39 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
40 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
41 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
43 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
46 CBlockIndex* pindexGenesisBlock = NULL;
49 uint256 nBestChainTrust = 0;
50 uint256 nBestInvalidTrust = 0;
52 uint256 hashBestChain = 0;
53 CBlockIndex* pindexBest = NULL;
54 int64 nTimeBestReceived = 0;
55 int nScriptCheckThreads = 0;
57 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
59 map<uint256, CBlock*> mapOrphanBlocks;
60 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
61 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
62 map<uint256, uint256> mapProofOfStake;
64 map<uint256, CTransaction> mapOrphanTransactions;
65 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
67 // Constant stuff for coinbase transactions we create:
68 CScript COINBASE_FLAGS;
70 const string strMessageMagic = "NovaCoin Signed Message:\n";
73 int64 nTransactionFee = MIN_TX_FEE;
74 int64 nMinimumInputValue = MIN_TX_FEE;
76 extern enum Checkpoints::CPMode CheckpointsMode;
78 //////////////////////////////////////////////////////////////////////////////
80 // dispatching functions
83 // These functions dispatch to one or all registered wallets
86 void RegisterWallet(CWallet* pwalletIn)
89 LOCK(cs_setpwalletRegistered);
90 setpwalletRegistered.insert(pwalletIn);
94 void UnregisterWallet(CWallet* pwalletIn)
97 LOCK(cs_setpwalletRegistered);
98 setpwalletRegistered.erase(pwalletIn);
102 // check whether the passed transaction is from us
103 bool static IsFromMe(CTransaction& tx)
105 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
106 if (pwallet->IsFromMe(tx))
111 // get the wallet transaction with the given hash (if it exists)
112 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
114 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
115 if (pwallet->GetTransaction(hashTx,wtx))
120 // erases transaction with the given hash from all wallets
121 void static EraseFromWallets(uint256 hash)
123 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
124 pwallet->EraseFromWallet(hash);
127 // make sure all wallets know about the given transaction, in the given block
128 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
132 // ppcoin: wallets need to refund inputs when disconnecting coinstake
133 if (tx.IsCoinStake())
135 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
136 if (pwallet->IsFromMe(tx))
137 pwallet->DisableTransaction(tx);
142 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
143 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
144 // Preloaded coins cache invalidation
145 fCoinsDataActual = false;
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 CTransaction& tx)
196 uint256 hash = tx.GetHash();
197 if (mapOrphanTransactions.count(hash))
200 // Ignore big transactions, to avoid a
201 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
202 // large transaction with a missing parent then we assume
203 // it will rebroadcast it later, after the parent transaction(s)
204 // have been mined or received.
205 // 10,000 orphans, each of which is at most 5,000 bytes big is
206 // at most 500 megabytes of orphans:
208 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
212 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
216 mapOrphanTransactions[hash] = tx;
217 BOOST_FOREACH(const CTxIn& txin, tx.vin)
218 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
220 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
221 mapOrphanTransactions.size());
225 void static EraseOrphanTx(uint256 hash)
227 if (!mapOrphanTransactions.count(hash))
229 const CTransaction& tx = mapOrphanTransactions[hash];
230 BOOST_FOREACH(const CTxIn& txin, tx.vin)
232 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
233 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
234 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
236 mapOrphanTransactions.erase(hash);
239 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
241 unsigned int nEvicted = 0;
242 while (mapOrphanTransactions.size() > nMaxOrphans)
244 // Evict a random orphan:
245 uint256 randomhash = GetRandHash();
246 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
247 if (it == mapOrphanTransactions.end())
248 it = mapOrphanTransactions.begin();
249 EraseOrphanTx(it->first);
261 //////////////////////////////////////////////////////////////////////////////
263 // CTransaction and CTxIndex
266 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
269 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
271 if (!ReadFromDisk(txindexRet.pos))
273 if (prevout.n >= vout.size())
281 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
284 return ReadFromDisk(txdb, prevout, txindex);
287 bool CTransaction::ReadFromDisk(COutPoint prevout)
291 return ReadFromDisk(txdb, prevout, txindex);
294 bool CTransaction::IsStandard() const
296 if (nVersion > CTransaction::CURRENT_VERSION)
299 unsigned int nDataOut = 0;
300 txnouttype whichType;
301 BOOST_FOREACH(const CTxIn& txin, vin)
303 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
304 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
305 // ~65-byte public keys, plus a few script ops.
306 if (txin.scriptSig.size() > 500)
308 if (!txin.scriptSig.IsPushOnly())
310 if (!txin.scriptSig.HasCanonicalPushes()) {
314 BOOST_FOREACH(const CTxOut& txout, vout) {
315 if (!::IsStandard(txout.scriptPubKey, whichType)) {
318 if (whichType == TX_NULL_DATA)
321 if (txout.nValue == 0) {
324 if (!txout.scriptPubKey.HasCanonicalPushes()) {
330 // only one OP_RETURN txout is permitted
339 // Check transaction inputs, and make sure any
340 // pay-to-script-hash transactions are evaluating IsStandard scripts
342 // Why bother? To avoid denial-of-service attacks; an attacker
343 // can submit a standard HASH... OP_EQUAL transaction,
344 // which will get accepted into blocks. The redemption
345 // script can be anything; an attacker could use a very
346 // expensive-to-check-upon-redemption script like:
347 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
349 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
352 return true; // Coinbases don't use vin normally
354 for (unsigned int i = 0; i < vin.size(); i++)
356 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
358 vector<vector<unsigned char> > vSolutions;
359 txnouttype whichType;
360 // get the scriptPubKey corresponding to this input:
361 const CScript& prevScript = prev.scriptPubKey;
362 if (!Solver(prevScript, whichType, vSolutions))
364 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
365 if (nArgsExpected < 0)
368 // Transactions with extra stuff in their scriptSigs are
369 // non-standard. Note that this EvalScript() call will
370 // be quick, because if there are any operations
371 // beside "push data" in the scriptSig the
372 // IsStandard() call returns false
373 vector<vector<unsigned char> > stack;
374 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
377 if (whichType == TX_SCRIPTHASH)
381 CScript subscript(stack.back().begin(), stack.back().end());
382 vector<vector<unsigned char> > vSolutions2;
383 txnouttype whichType2;
384 if (!Solver(subscript, whichType2, vSolutions2))
386 if (whichType2 == TX_SCRIPTHASH)
390 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
393 nArgsExpected += tmpExpected;
396 if (stack.size() != (unsigned int)nArgsExpected)
404 CTransaction::GetLegacySigOpCount() const
406 unsigned int nSigOps = 0;
407 BOOST_FOREACH(const CTxIn& txin, vin)
409 nSigOps += txin.scriptSig.GetSigOpCount(false);
411 BOOST_FOREACH(const CTxOut& txout, vout)
413 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
419 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
431 // Load the block this tx is in
433 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
435 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
440 // Update the tx's hashBlock
441 hashBlock = pblock->GetHash();
443 // Locate the transaction
444 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
445 if (pblock->vtx[nIndex] == *(CTransaction*)this)
447 if (nIndex == (int)pblock->vtx.size())
449 vMerkleBranch.clear();
451 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
455 // Fill in merkle branch
456 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
459 // Is the tx in a block that's in the main chain
460 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
461 if (mi == mapBlockIndex.end())
463 CBlockIndex* pindex = (*mi).second;
464 if (!pindex || !pindex->IsInMainChain())
467 return pindexBest->nHeight - pindex->nHeight + 1;
476 bool CTransaction::CheckTransaction() const
478 // Basic checks that don't depend on any context
480 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
482 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
484 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
485 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
487 // Check for negative or overflow output values
489 for (unsigned int i = 0; i < vout.size(); i++)
491 const CTxOut& txout = vout[i];
492 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
493 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
495 if (txout.nValue < 0)
496 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
497 if (txout.nValue > MAX_MONEY)
498 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
499 nValueOut += txout.nValue;
500 if (!MoneyRange(nValueOut))
501 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
504 // Check for duplicate inputs
505 set<COutPoint> vInOutPoints;
506 BOOST_FOREACH(const CTxIn& txin, vin)
508 if (vInOutPoints.count(txin.prevout))
510 vInOutPoints.insert(txin.prevout);
515 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
516 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
520 BOOST_FOREACH(const CTxIn& txin, vin)
521 if (txin.prevout.IsNull())
522 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
528 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
530 // Use new fees approach if we are on test network or
531 // switch date has been reached
532 bool fNewApproach = fTestNet || nTime > FEE_SWITCH_TIME;
534 int64 nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
536 if(!fNewApproach || IsCoinStake())
538 // Enforce 0.01 as minimum fee for old approach or coinstake
540 nMinRelayTxFee = CENT;
543 // Base fee is either nMinTxFee or nMinRelayTxFee
544 int64 nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
546 unsigned int nNewBlockSize = nBlockSize + nBytes;
547 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
555 // Transactions under 1K are free
561 // Free transaction area
562 if (nNewBlockSize < 27000)
567 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
568 // each non empty output which is less than 0.01
570 // It's safe to ignore empty outputs here, because these inputs are allowed
571 // only for coinbase and coinstake transactions.
572 BOOST_FOREACH(const CTxOut& txout, vout)
573 if (txout.nValue < CENT && !txout.IsEmpty())
576 else if (nMinFee < nBaseFee)
578 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if
579 // any output is less than 0.01
580 BOOST_FOREACH(const CTxOut& txout, vout)
581 if (txout.nValue < CENT)
585 // Raise the price as the block approaches full
586 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
588 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
590 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
593 if (!MoneyRange(nMinFee))
600 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
601 bool* pfMissingInputs)
604 *pfMissingInputs = false;
606 if (!tx.CheckTransaction())
607 return error("CTxMemPool::accept() : CheckTransaction failed");
609 // Coinbase is only valid in a block, not as a loose transaction
611 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
613 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
614 if (tx.IsCoinStake())
615 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
617 // To help v0.1.5 clients who would see it as a negative number
618 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
619 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
621 // Rather not work on nonstandard transactions (unless -testnet)
622 if (!fTestNet && !tx.IsStandard())
623 return error("CTxMemPool::accept() : nonstandard transaction type");
625 // Do we already have it?
626 uint256 hash = tx.GetHash();
629 if (mapTx.count(hash))
633 if (txdb.ContainsTx(hash))
636 // Check for conflicts with in-memory transactions
637 CTransaction* ptxOld = NULL;
638 for (unsigned int i = 0; i < tx.vin.size(); i++)
640 COutPoint outpoint = tx.vin[i].prevout;
641 if (mapNextTx.count(outpoint))
643 // Disable replacement feature for now
646 // Allow replacing with a newer version of the same transaction
649 ptxOld = mapNextTx[outpoint].ptx;
650 if (ptxOld->IsFinal())
652 if (!tx.IsNewerThan(*ptxOld))
654 for (unsigned int i = 0; i < tx.vin.size(); i++)
656 COutPoint outpoint = tx.vin[i].prevout;
657 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
667 map<uint256, CTxIndex> mapUnused;
668 bool fInvalid = false;
669 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
672 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
674 *pfMissingInputs = true;
678 // Check for non-standard pay-to-script-hash in inputs
679 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
680 return error("CTxMemPool::accept() : nonstandard transaction input");
682 // Note: if you modify this code to accept non-standard transactions, then
683 // you should add code here to check that the transaction does a
684 // reasonable number of ECDSA signature verifications.
686 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
687 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
689 // Don't accept it if it can't get into a block
690 int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
691 if (nFees < txMinFee)
692 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
693 hash.ToString().c_str(),
696 // Continuously rate-limit free transactions
697 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
698 // be annoying or make others' transactions take longer to confirm.
699 if (nFees < MIN_RELAY_TX_FEE)
701 static CCriticalSection cs;
702 static double dFreeCount;
703 static int64 nLastTime;
704 int64 nNow = GetTime();
708 // Use an exponentially decaying ~10-minute window:
709 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
711 // -limitfreerelay unit is thousand-bytes-per-minute
712 // At default rate it would take over a month to fill 1GB
713 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
714 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
716 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
721 // Check against previous transactions
722 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
723 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, SIG_SWITCH_TIME < tx.nTime ? STRICT_FLAGS : SOFT_FLAGS))
725 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
729 // Store transaction in memory
734 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
737 addUnchecked(hash, tx);
740 ///// are we sure this is ok when loading transactions or restoring block txes
741 // If updated, erase old tx from wallet
743 EraseFromWallets(ptxOld->GetHash());
745 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
746 hash.ToString().substr(0,10).c_str(),
751 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
753 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
756 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
758 // Add to memory pool without checking anything. Don't call this directly,
759 // call CTxMemPool::accept to properly check the transaction first.
762 for (unsigned int i = 0; i < tx.vin.size(); i++)
763 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
764 nTransactionsUpdated++;
770 bool CTxMemPool::remove(CTransaction &tx)
772 // Remove transaction from memory pool
775 uint256 hash = tx.GetHash();
776 if (mapTx.count(hash))
778 BOOST_FOREACH(const CTxIn& txin, tx.vin)
779 mapNextTx.erase(txin.prevout);
781 nTransactionsUpdated++;
787 void CTxMemPool::clear()
792 ++nTransactionsUpdated;
795 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
800 vtxid.reserve(mapTx.size());
801 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
802 vtxid.push_back((*mi).first);
808 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
810 if (hashBlock == 0 || nIndex == -1)
813 // Find the block it claims to be in
814 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
815 if (mi == mapBlockIndex.end())
817 CBlockIndex* pindex = (*mi).second;
818 if (!pindex || !pindex->IsInMainChain())
821 // Make sure the merkle branch connects to this block
822 if (!fMerkleVerified)
824 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
826 fMerkleVerified = true;
830 return pindexBest->nHeight - pindex->nHeight + 1;
834 int CMerkleTx::GetBlocksToMaturity() const
836 if (!(IsCoinBase() || IsCoinStake()))
838 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
842 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
846 if (!IsInMainChain() && !ClientConnectInputs())
848 return CTransaction::AcceptToMemoryPool(txdb, false);
852 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
856 bool CMerkleTx::AcceptToMemoryPool()
859 return AcceptToMemoryPool(txdb);
864 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
869 // Add previous supporting transactions first
870 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
872 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
874 uint256 hash = tx.GetHash();
875 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
876 tx.AcceptToMemoryPool(txdb, fCheckInputs);
879 return AcceptToMemoryPool(txdb, fCheckInputs);
884 bool CWalletTx::AcceptWalletTransaction()
887 return AcceptWalletTransaction(txdb);
890 int CTxIndex::GetDepthInMainChain() const
894 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
896 // Find the block in the index
897 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
898 if (mi == mapBlockIndex.end())
900 CBlockIndex* pindex = (*mi).second;
901 if (!pindex || !pindex->IsInMainChain())
903 return 1 + nBestHeight - pindex->nHeight;
906 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
907 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
913 if (mempool.exists(hash))
915 tx = mempool.lookup(hash);
921 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
924 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
925 hashBlock = block.GetHash();
939 //////////////////////////////////////////////////////////////////////////////
941 // CBlock and CBlockIndex
944 static CBlockIndex* pblockindexFBBHLast;
945 CBlockIndex* FindBlockByHeight(int nHeight)
947 CBlockIndex *pblockindex;
948 if (nHeight < nBestHeight / 2)
949 pblockindex = pindexGenesisBlock;
951 pblockindex = pindexBest;
952 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
953 pblockindex = pblockindexFBBHLast;
954 while (pblockindex->nHeight > nHeight)
955 pblockindex = pblockindex->pprev;
956 while (pblockindex->nHeight < nHeight)
957 pblockindex = pblockindex->pnext;
958 pblockindexFBBHLast = pblockindex;
962 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
964 if (!fReadTransactions)
966 *this = pindex->GetBlockHeader();
969 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
971 if (GetHash() != pindex->GetBlockHash())
972 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
976 uint256 static GetOrphanRoot(const CBlock* pblock)
978 // Work back to the first block in the orphan chain
979 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
980 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
981 return pblock->GetHash();
984 // ppcoin: find block wanted by given orphan block
985 uint256 WantedByOrphan(const CBlock* pblockOrphan)
987 // Work back to the first block in the orphan chain
988 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
989 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
990 return pblockOrphan->hashPrevBlock;
993 // select stake target limit according to hard-coded conditions
994 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
996 if(fTestNet) // separate proof of stake target limit for testnet
997 return bnProofOfStakeLimit;
998 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
999 return bnProofOfStakeLimit;
1000 if(nHeight + 1 > 15000) // 24 bits since block 15000
1001 return bnProofOfStakeLegacyLimit;
1002 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1003 return bnProofOfStakeHardLimit;
1005 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1008 // miner's coin base reward based on nBits
1009 int64 GetProofOfWorkReward(unsigned int nBits, int64 nFees)
1011 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1014 bnTarget.SetCompact(nBits);
1015 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1016 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1018 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1019 // A reasonably continuous curve is used to avoid shock to market
1020 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1022 // Human readable form:
1024 // nSubsidy = 100 / (diff ^ 1/6)
1025 CBigNum bnLowerBound = CENT;
1026 CBigNum bnUpperBound = bnSubsidyLimit;
1027 while (bnLowerBound + CENT <= bnUpperBound)
1029 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1030 if (fDebug && GetBoolArg("-printcreation"))
1031 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1032 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1033 bnUpperBound = bnMidValue;
1035 bnLowerBound = bnMidValue;
1038 int64 nSubsidy = bnUpperBound.getuint64();
1040 nSubsidy = (nSubsidy / CENT) * CENT;
1041 if (fDebug && GetBoolArg("-printcreation"))
1042 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1044 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1047 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1048 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
1050 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1052 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1054 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1056 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1058 bnTarget.SetCompact(nBits);
1059 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1060 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1062 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1064 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1065 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1066 bnMidPart, bnRewardPart;
1068 while (bnLowerBound + CENT <= bnUpperBound)
1070 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1071 if (fDebug && GetBoolArg("-printcreation"))
1072 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1074 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1077 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1079 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1081 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1084 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1085 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1090 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1092 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1094 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1097 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1098 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1101 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1102 bnUpperBound = bnMidValue;
1104 bnLowerBound = bnMidValue;
1107 nRewardCoinYear = bnUpperBound.getuint64();
1108 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1112 // Old creation amount per coin-year, 5% fixed stake mint rate
1113 nRewardCoinYear = 5 * CENT;
1117 return nRewardCoinYear;
1119 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1121 // Set reasonable reward limit for large inputs since 20 Oct 2013
1123 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1124 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1126 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1127 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1129 nSubsidy = min(nSubsidy, nSubsidyLimit);
1132 if (fDebug && GetBoolArg("-printcreation"))
1133 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1137 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1139 // get proof of work blocks max spacing according to hard-coded conditions
1140 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1142 if(nTime > TARGETS_SWITCH_TIME)
1143 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1146 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1148 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1152 // maximum nBits value could possible be required nTime after
1154 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1157 bnResult.SetCompact(nBase);
1159 while (nTime > 0 && bnResult < bnTargetLimit)
1161 // Maximum 200% adjustment per day...
1163 nTime -= 24 * 60 * 60;
1165 if (bnResult > bnTargetLimit)
1166 bnResult = bnTargetLimit;
1167 return bnResult.GetCompact();
1171 // minimum amount of work that could possibly be required nTime after
1172 // minimum proof-of-work required was nBase
1174 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1176 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1180 // minimum amount of stake that could possibly be required nTime after
1181 // minimum proof-of-stake required was nBase
1183 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1185 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1189 // ppcoin: find last block index up to pindex
1190 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1192 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1193 pindex = pindex->pprev;
1197 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1199 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1201 if (pindexLast == NULL)
1202 return bnTargetLimit.GetCompact(); // genesis block
1204 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1205 if (pindexPrev->pprev == NULL)
1206 return bnTargetLimit.GetCompact(); // first block
1207 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1208 if (pindexPrevPrev->pprev == NULL)
1209 return bnTargetLimit.GetCompact(); // second block
1211 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1213 // ppcoin: target change every block
1214 // ppcoin: retarget with exponential moving toward target spacing
1216 bnNew.SetCompact(pindexPrev->nBits);
1217 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1218 int64 nInterval = nTargetTimespan / nTargetSpacing;
1219 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1220 bnNew /= ((nInterval + 1) * nTargetSpacing);
1222 if (bnNew > bnTargetLimit)
1223 bnNew = bnTargetLimit;
1225 return bnNew.GetCompact();
1228 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1231 bnTarget.SetCompact(nBits);
1234 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1235 return error("CheckProofOfWork() : nBits below minimum work");
1237 // Check proof of work matches claimed amount
1238 if (hash > bnTarget.getuint256())
1239 return error("CheckProofOfWork() : hash doesn't match nBits");
1244 // Return maximum amount of blocks that other nodes claim to have
1245 int GetNumBlocksOfPeers()
1247 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1250 bool IsInitialBlockDownload()
1252 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1254 static int64 nLastUpdate;
1255 static CBlockIndex* pindexLastBest;
1256 if (pindexBest != pindexLastBest)
1258 pindexLastBest = pindexBest;
1259 nLastUpdate = GetTime();
1261 return (GetTime() - nLastUpdate < 10 &&
1262 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1265 void static InvalidChainFound(CBlockIndex* pindexNew)
1267 if (pindexNew->nChainTrust > nBestInvalidTrust)
1269 nBestInvalidTrust = pindexNew->nChainTrust;
1270 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1271 uiInterface.NotifyBlocksChanged();
1274 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1275 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1277 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1278 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1279 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1280 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1281 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1282 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1283 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1284 nBestBlockTrust.Get64(),
1285 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1289 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1291 nTime = max(GetBlockTime(), GetAdjustedTime());
1304 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1306 // Relinquish previous transactions' spent pointers
1309 BOOST_FOREACH(const CTxIn& txin, vin)
1311 COutPoint prevout = txin.prevout;
1313 // Get prev txindex from disk
1315 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1316 return error("DisconnectInputs() : ReadTxIndex failed");
1318 if (prevout.n >= txindex.vSpent.size())
1319 return error("DisconnectInputs() : prevout.n out of range");
1321 // Mark outpoint as not spent
1322 txindex.vSpent[prevout.n].SetNull();
1325 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1326 return error("DisconnectInputs() : UpdateTxIndex failed");
1330 // Remove transaction from index
1331 // This can fail if a duplicate of this transaction was in a chain that got
1332 // reorganized away. This is only possible if this transaction was completely
1333 // spent, so erasing it would be a no-op anyway.
1334 txdb.EraseTxIndex(*this);
1340 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1341 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1343 // FetchInputs can return false either because we just haven't seen some inputs
1344 // (in which case the transaction should be stored as an orphan)
1345 // or because the transaction is malformed (in which case the transaction should
1346 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1350 return true; // Coinbase transactions have no inputs to fetch.
1352 for (unsigned int i = 0; i < vin.size(); i++)
1354 COutPoint prevout = vin[i].prevout;
1355 if (inputsRet.count(prevout.hash))
1356 continue; // Got it already
1359 CTxIndex& txindex = inputsRet[prevout.hash].first;
1361 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1363 // Get txindex from current proposed changes
1364 txindex = mapTestPool.find(prevout.hash)->second;
1368 // Read txindex from txdb
1369 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1371 if (!fFound && (fBlock || fMiner))
1372 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());
1375 CTransaction& txPrev = inputsRet[prevout.hash].second;
1376 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1378 // Get prev tx from single transactions in memory
1381 if (!mempool.exists(prevout.hash))
1382 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());
1383 txPrev = mempool.lookup(prevout.hash);
1386 txindex.vSpent.resize(txPrev.vout.size());
1390 // Get prev tx from disk
1391 if (!txPrev.ReadFromDisk(txindex.pos))
1392 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1396 // Make sure all prevout.n indexes are valid:
1397 for (unsigned int i = 0; i < vin.size(); i++)
1399 const COutPoint prevout = vin[i].prevout;
1400 assert(inputsRet.count(prevout.hash) != 0);
1401 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1402 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1403 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1405 // Revisit this if/when transaction replacement is implemented and allows
1408 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()));
1415 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1417 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1418 if (mi == inputs.end())
1419 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1421 const CTransaction& txPrev = (mi->second).second;
1422 if (input.prevout.n >= txPrev.vout.size())
1423 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1425 return txPrev.vout[input.prevout.n];
1428 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1434 for (unsigned int i = 0; i < vin.size(); i++)
1436 nResult += GetOutputFor(vin[i], inputs).nValue;
1442 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1447 unsigned int nSigOps = 0;
1448 for (unsigned int i = 0; i < vin.size(); i++)
1450 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1451 if (prevout.scriptPubKey.IsPayToScriptHash())
1452 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1457 bool CScriptCheck::operator()() const {
1458 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1459 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1460 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1464 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1466 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1469 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1470 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1472 // Take over previous transactions' spent pointers
1473 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1474 // fMiner is true when called from the internal bitcoin miner
1475 // ... both are false when called from CTransaction::AcceptToMemoryPool
1481 for (unsigned int i = 0; i < vin.size(); i++)
1483 COutPoint prevout = vin[i].prevout;
1484 assert(inputs.count(prevout.hash) > 0);
1485 CTxIndex& txindex = inputs[prevout.hash].first;
1486 CTransaction& txPrev = inputs[prevout.hash].second;
1488 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1489 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()));
1491 // If prev is coinbase or coinstake, check that it's matured
1492 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1493 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1494 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1495 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1497 // ppcoin: check transaction timestamp
1498 if (txPrev.nTime > nTime)
1499 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1501 // Check for negative or overflow input values
1502 nValueIn += txPrev.vout[prevout.n].nValue;
1503 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1504 return DoS(100, error("ConnectInputs() : txin values out of range"));
1509 pvChecks->reserve(vin.size());
1511 // The first loop above does all the inexpensive checks.
1512 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1513 // Helps prevent CPU exhaustion attacks.
1514 for (unsigned int i = 0; i < vin.size(); i++)
1516 COutPoint prevout = vin[i].prevout;
1517 assert(inputs.count(prevout.hash) > 0);
1518 CTxIndex& txindex = inputs[prevout.hash].first;
1519 CTransaction& txPrev = inputs[prevout.hash].second;
1521 // Check for conflicts (double-spend)
1522 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1523 // for an attacker to attempt to split the network.
1524 if (!txindex.vSpent[prevout.n].IsNull())
1525 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());
1527 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1528 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1529 // still computed and checked, and any change will be caught at the next checkpoint.
1533 CScriptCheck check(txPrev, *this, i, flags, 0);
1536 pvChecks->push_back(CScriptCheck());
1537 check.swap(pvChecks->back());
1541 if (flags & STRICT_FLAGS)
1543 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1544 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1546 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1548 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1552 // Mark outpoints as spent
1553 txindex.vSpent[prevout.n] = posThisTx;
1556 if (fBlock || fMiner)
1558 mapTestPool[prevout.hash] = txindex;
1564 // ppcoin: coin stake tx earns reward instead of paying fee
1566 if (!GetCoinAge(txdb, nCoinAge))
1567 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1569 unsigned int nTxSize = (nTime > VALIDATION_SWITCH_TIME || fTestNet) ? GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION) : 0;
1571 int64 nReward = GetValueOut() - nValueIn;
1572 int64 nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1574 if (nReward > nCalculatedReward)
1575 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nReward, nCalculatedReward));
1579 if (nValueIn < GetValueOut())
1580 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1582 // Tally transaction fees
1583 int64 nTxFee = nValueIn - GetValueOut();
1585 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1588 if (!MoneyRange(nFees))
1589 return DoS(100, error("ConnectInputs() : nFees out of range"));
1597 bool CTransaction::ClientConnectInputs()
1602 // Take over previous transactions' spent pointers
1606 for (unsigned int i = 0; i < vin.size(); i++)
1608 // Get prev tx from single transactions in memory
1609 COutPoint prevout = vin[i].prevout;
1610 if (!mempool.exists(prevout.hash))
1612 CTransaction& txPrev = mempool.lookup(prevout.hash);
1614 if (prevout.n >= txPrev.vout.size())
1618 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1619 return error("ClientConnectInputs() : VerifySignature failed");
1621 ///// this is redundant with the mempool.mapNextTx stuff,
1622 ///// not sure which I want to get rid of
1623 ///// this has to go away now that posNext is gone
1624 // // Check for conflicts
1625 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1626 // return error("ConnectInputs() : prev tx already used");
1628 // // Flag outpoints as used
1629 // txPrev.vout[prevout.n].posNext = posThisTx;
1631 nValueIn += txPrev.vout[prevout.n].nValue;
1633 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1634 return error("ClientConnectInputs() : txin values out of range");
1636 if (GetValueOut() > nValueIn)
1646 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1648 // Disconnect in reverse order
1649 for (int i = vtx.size()-1; i >= 0; i--)
1650 if (!vtx[i].DisconnectInputs(txdb))
1653 // Update block index on disk without changing it in memory.
1654 // The memory index structure will be changed after the db commits.
1657 CDiskBlockIndex blockindexPrev(pindex->pprev);
1658 blockindexPrev.hashNext = 0;
1659 if (!txdb.WriteBlockIndex(blockindexPrev))
1660 return error("DisconnectBlock() : WriteBlockIndex failed");
1663 // ppcoin: clean up wallet after disconnecting coinstake
1664 BOOST_FOREACH(CTransaction& tx, vtx)
1665 SyncWithWallets(tx, this, false, false);
1670 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1672 void ThreadScriptCheck(void*) {
1673 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1674 RenameThread("novacoin-scriptch");
1675 scriptcheckqueue.Thread();
1676 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1679 void ThreadScriptCheckQuit() {
1680 scriptcheckqueue.Quit();
1683 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1685 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1686 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1689 bool fProtocol048 = fTestNet || VALIDATION_SWITCH_TIME < nTime;
1691 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1692 // unless those are already completely spent.
1693 // If such overwrites are allowed, coinbases and transactions depending upon those
1694 // can be duplicated to remove the ability to spend the first instance -- even after
1695 // being sent to another address.
1696 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1697 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1698 // already refuses previously-known transaction ids entirely.
1699 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1700 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1701 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1702 // initial block download.
1703 bool fEnforceBIP30 = true; // Always active in NovaCoin
1704 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1706 //// issue here: it doesn't know the version
1707 unsigned int nTxPos;
1709 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1710 // 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
1713 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1715 map<uint256, CTxIndex> mapQueuedChanges;
1716 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1720 int64 nValueOut = 0;
1721 unsigned int nSigOps = 0;
1722 BOOST_FOREACH(CTransaction& tx, vtx)
1724 uint256 hashTx = tx.GetHash();
1726 if (fEnforceBIP30) {
1727 CTxIndex txindexOld;
1728 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1729 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1735 nSigOps += tx.GetLegacySigOpCount();
1736 if (nSigOps > MAX_BLOCK_SIGOPS)
1737 return DoS(100, error("ConnectBlock() : too many sigops"));
1739 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1741 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1743 MapPrevTx mapInputs;
1744 if (tx.IsCoinBase())
1745 nValueOut += tx.GetValueOut();
1749 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1752 // Add in sigops done by pay-to-script-hash inputs;
1753 // this is to prevent a "rogue miner" from creating
1754 // an incredibly-expensive-to-validate block.
1755 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1756 if (nSigOps > MAX_BLOCK_SIGOPS)
1757 return DoS(100, error("ConnectBlock() : too many sigops"));
1759 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1760 int64 nTxValueOut = tx.GetValueOut();
1761 nValueIn += nTxValueIn;
1762 nValueOut += nTxValueOut;
1763 if (!tx.IsCoinStake())
1764 nFees += nTxValueIn - nTxValueOut;
1766 std::vector<CScriptCheck> vChecks;
1767 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, nScriptCheckThreads ? &vChecks : NULL))
1769 control.Add(vChecks);
1772 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1775 if (!control.Wait())
1776 return DoS(100, false);
1778 if (IsProofOfWork())
1780 int64 nBlockReward = GetProofOfWorkReward(nBits, fProtocol048 ? nFees : 0);
1782 // Check coinbase reward
1783 if (vtx[0].GetValueOut() > nBlockReward)
1784 return error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
1785 vtx[0].GetValueOut(),
1789 // track money supply and mint amount info
1790 pindex->nMint = nValueOut - nValueIn + nFees;
1791 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1792 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1793 return error("Connect() : WriteBlockIndex for pindex failed");
1795 // fees are not collected by proof-of-stake miners
1796 // fees are destroyed to compensate the entire network
1797 if (fProtocol048 && fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1798 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1803 // Write queued txindex changes
1804 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1806 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1807 return error("ConnectBlock() : UpdateTxIndex failed");
1810 // Update block index on disk without changing it in memory.
1811 // The memory index structure will be changed after the db commits.
1814 CDiskBlockIndex blockindexPrev(pindex->pprev);
1815 blockindexPrev.hashNext = pindex->GetBlockHash();
1816 if (!txdb.WriteBlockIndex(blockindexPrev))
1817 return error("ConnectBlock() : WriteBlockIndex failed");
1820 // Watch for transactions paying to me
1821 BOOST_FOREACH(CTransaction& tx, vtx)
1822 SyncWithWallets(tx, this, true);
1828 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1830 printf("REORGANIZE\n");
1833 CBlockIndex* pfork = pindexBest;
1834 CBlockIndex* plonger = pindexNew;
1835 while (pfork != plonger)
1837 while (plonger->nHeight > pfork->nHeight)
1838 if (!(plonger = plonger->pprev))
1839 return error("Reorganize() : plonger->pprev is null");
1840 if (pfork == plonger)
1842 if (!(pfork = pfork->pprev))
1843 return error("Reorganize() : pfork->pprev is null");
1846 // List of what to disconnect
1847 vector<CBlockIndex*> vDisconnect;
1848 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1849 vDisconnect.push_back(pindex);
1851 // List of what to connect
1852 vector<CBlockIndex*> vConnect;
1853 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1854 vConnect.push_back(pindex);
1855 reverse(vConnect.begin(), vConnect.end());
1857 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());
1858 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());
1860 // Disconnect shorter branch
1861 vector<CTransaction> vResurrect;
1862 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1865 if (!block.ReadFromDisk(pindex))
1866 return error("Reorganize() : ReadFromDisk for disconnect failed");
1867 if (!block.DisconnectBlock(txdb, pindex))
1868 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1870 // Queue memory transactions to resurrect
1871 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1872 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1873 vResurrect.push_back(tx);
1876 // Connect longer branch
1877 vector<CTransaction> vDelete;
1878 for (unsigned int i = 0; i < vConnect.size(); i++)
1880 CBlockIndex* pindex = vConnect[i];
1882 if (!block.ReadFromDisk(pindex))
1883 return error("Reorganize() : ReadFromDisk for connect failed");
1884 if (!block.ConnectBlock(txdb, pindex))
1887 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1890 // Queue memory transactions to delete
1891 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1892 vDelete.push_back(tx);
1894 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1895 return error("Reorganize() : WriteHashBestChain failed");
1897 // Make sure it's successfully written to disk before changing memory structure
1898 if (!txdb.TxnCommit())
1899 return error("Reorganize() : TxnCommit failed");
1901 // Disconnect shorter branch
1902 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1904 pindex->pprev->pnext = NULL;
1906 // Connect longer branch
1907 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1909 pindex->pprev->pnext = pindex;
1911 // Resurrect memory transactions that were in the disconnected branch
1912 BOOST_FOREACH(CTransaction& tx, vResurrect)
1913 tx.AcceptToMemoryPool(txdb, false);
1915 // Delete redundant memory transactions that are in the connected branch
1916 BOOST_FOREACH(CTransaction& tx, vDelete)
1919 printf("REORGANIZE: done\n");
1925 // Called from inside SetBestChain: attaches a block to the new best chain being built
1926 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1928 uint256 hash = GetHash();
1930 // Adding to current best branch
1931 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1934 InvalidChainFound(pindexNew);
1937 if (!txdb.TxnCommit())
1938 return error("SetBestChain() : TxnCommit failed");
1940 // Add to current best branch
1941 pindexNew->pprev->pnext = pindexNew;
1943 // Delete redundant memory transactions
1944 BOOST_FOREACH(CTransaction& tx, vtx)
1950 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1952 uint256 hash = GetHash();
1954 if (!txdb.TxnBegin())
1955 return error("SetBestChain() : TxnBegin failed");
1957 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1959 txdb.WriteHashBestChain(hash);
1960 if (!txdb.TxnCommit())
1961 return error("SetBestChain() : TxnCommit failed");
1962 pindexGenesisBlock = pindexNew;
1964 else if (hashPrevBlock == hashBestChain)
1966 if (!SetBestChainInner(txdb, pindexNew))
1967 return error("SetBestChain() : SetBestChainInner failed");
1971 // the first block in the new chain that will cause it to become the new best chain
1972 CBlockIndex *pindexIntermediate = pindexNew;
1974 // list of blocks that need to be connected afterwards
1975 std::vector<CBlockIndex*> vpindexSecondary;
1977 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1978 // Try to limit how much needs to be done inside
1979 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1981 vpindexSecondary.push_back(pindexIntermediate);
1982 pindexIntermediate = pindexIntermediate->pprev;
1985 if (!vpindexSecondary.empty())
1986 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1988 // Switch to new best branch
1989 if (!Reorganize(txdb, pindexIntermediate))
1992 InvalidChainFound(pindexNew);
1993 return error("SetBestChain() : Reorganize failed");
1996 // Connect further blocks
1997 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
2000 if (!block.ReadFromDisk(pindex))
2002 printf("SetBestChain() : ReadFromDisk failed\n");
2005 if (!txdb.TxnBegin()) {
2006 printf("SetBestChain() : TxnBegin 2 failed\n");
2009 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
2010 if (!block.SetBestChainInner(txdb, pindex))
2015 // Update best block in wallet (so we can detect restored wallets)
2016 bool fIsInitialDownload = IsInitialBlockDownload();
2017 if (!fIsInitialDownload)
2019 const CBlockLocator locator(pindexNew);
2020 ::SetBestChain(locator);
2024 hashBestChain = hash;
2025 pindexBest = pindexNew;
2026 pblockindexFBBHLast = NULL;
2027 nBestHeight = pindexBest->nHeight;
2028 nBestChainTrust = pindexNew->nChainTrust;
2029 nTimeBestReceived = GetTime();
2030 nTransactionsUpdated++;
2032 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2034 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
2035 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2036 CBigNum(nBestChainTrust).ToString().c_str(),
2037 nBestBlockTrust.Get64(),
2038 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2040 // Check the version of the last 100 blocks to see if we need to upgrade:
2041 if (!fIsInitialDownload)
2044 const CBlockIndex* pindex = pindexBest;
2045 for (int i = 0; i < 100 && pindex != NULL; i++)
2047 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2049 pindex = pindex->pprev;
2052 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2053 if (nUpgraded > 100/2)
2054 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2055 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2058 std::string strCmd = GetArg("-blocknotify", "");
2060 if (!fIsInitialDownload && !strCmd.empty())
2062 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
2063 boost::thread t(runCommand, strCmd); // thread runs free
2069 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2070 // Only those coins meeting minimum age requirement counts. As those
2071 // transactions not in main chain are not currently indexed so we
2072 // might not find out about their coin age. Older transactions are
2073 // guaranteed to be in main chain by sync-checkpoint. This rule is
2074 // introduced to help nodes establish a consistent view of the coin
2075 // age (trust score) of competing branches.
2076 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
2078 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2084 BOOST_FOREACH(const CTxIn& txin, vin)
2086 // First try finding the previous transaction in database
2087 CTransaction txPrev;
2089 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2090 continue; // previous transaction not in main chain
2091 if (nTime < txPrev.nTime)
2092 return false; // Transaction timestamp violation
2094 // Read block header
2096 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2097 return false; // unable to read block of previous transaction
2098 if (block.GetBlockTime() + nStakeMinAge > nTime)
2099 continue; // only count coins meeting min age requirement
2101 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2102 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2104 if (fDebug && GetBoolArg("-printcoinage"))
2105 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2108 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
2109 if (fDebug && GetBoolArg("-printcoinage"))
2110 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2111 nCoinAge = bnCoinDay.getuint64();
2115 // ppcoin: total coin age spent in block, in the unit of coin-days.
2116 bool CBlock::GetCoinAge(uint64& nCoinAge) const
2121 BOOST_FOREACH(const CTransaction& tx, vtx)
2124 if (tx.GetCoinAge(txdb, nTxCoinAge))
2125 nCoinAge += nTxCoinAge;
2130 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2132 if (fDebug && GetBoolArg("-printcoinage"))
2133 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
2137 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2139 // Check for duplicate
2140 uint256 hash = GetHash();
2141 if (mapBlockIndex.count(hash))
2142 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2144 // Construct new block index object
2145 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
2147 return error("AddToBlockIndex() : new CBlockIndex failed");
2148 pindexNew->phashBlock = &hash;
2149 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2150 if (miPrev != mapBlockIndex.end())
2152 pindexNew->pprev = (*miPrev).second;
2153 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2156 // ppcoin: compute chain trust score
2157 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2159 // ppcoin: compute stake entropy bit for stake modifier
2160 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2161 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2163 // ppcoin: record proof-of-stake hash value
2164 if (pindexNew->IsProofOfStake())
2166 if (!mapProofOfStake.count(hash))
2167 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2168 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2171 // ppcoin: compute stake modifier
2172 uint64 nStakeModifier = 0;
2173 bool fGeneratedStakeModifier = false;
2174 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2175 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2176 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2177 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2178 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2179 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2181 // Add to mapBlockIndex
2182 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2183 if (pindexNew->IsProofOfStake())
2184 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2185 pindexNew->phashBlock = &((*mi).first);
2187 // Write to disk block index
2189 if (!txdb.TxnBegin())
2191 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2192 if (!txdb.TxnCommit())
2196 if (pindexNew->nChainTrust > nBestChainTrust)
2197 if (!SetBestChain(txdb, pindexNew))
2200 if (pindexNew == pindexBest)
2202 // Notify UI to display prev block's coinbase if it was ours
2203 static uint256 hashPrevBestCoinBase;
2204 UpdatedTransaction(hashPrevBestCoinBase);
2205 hashPrevBestCoinBase = vtx[0].GetHash();
2208 uiInterface.NotifyBlocksChanged();
2215 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2217 // These are checks that are independent of context
2218 // that can be verified before saving an orphan block.
2221 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2222 return DoS(100, error("CheckBlock() : size limits failed"));
2224 bool fProtocol048 = fTestNet || VALIDATION_SWITCH_TIME < nTime;
2226 // Check proof of work matches claimed amount
2227 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2228 return DoS(50, error("CheckBlock() : proof of work failed"));
2231 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2232 return error("CheckBlock() : block timestamp too far in the future");
2234 // First transaction must be coinbase, the rest must not be
2235 if (vtx.empty() || !vtx[0].IsCoinBase())
2236 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2240 // Check coinbase timestamp
2241 if (GetBlockTime() < (int64)vtx[0].nTime)
2242 return DoS(100, error("CheckBlock() : coinbase timestamp violation"));
2246 // Check coinbase timestamp
2247 if (GetBlockTime() < PastDrift((int64)vtx[0].nTime))
2248 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2251 for (unsigned int i = 1; i < vtx.size(); i++)
2253 if (vtx[i].IsCoinBase())
2254 return DoS(100, error("CheckBlock() : more than one coinbase"));
2256 // Check transaction timestamp
2257 if (GetBlockTime() < (int64)vtx[i].nTime)
2258 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2261 if (IsProofOfStake())
2266 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2269 // Coinbase output should be empty if proof-of-stake block
2270 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2271 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2273 // Second transaction must be coinstake, the rest must not be
2274 if (vtx.empty() || !vtx[1].IsCoinStake())
2275 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2276 for (unsigned int i = 2; i < vtx.size(); i++)
2277 if (vtx[i].IsCoinStake())
2278 return DoS(100, error("CheckBlock() : more than one coinstake"));
2280 // Check coinstake timestamp
2281 if (GetBlockTime() != (int64)vtx[1].nTime)
2282 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2284 // NovaCoin: check proof-of-stake block signature
2285 if (fCheckSig && !CheckBlockSignature(true))
2286 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2290 // Should we check proof-of-work block signature or not?
2292 // * Always skip on TestNet
2293 // * Perform checking for the first 9689 blocks
2294 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2296 if(!fTestNet && fCheckSig)
2298 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2300 // NovaCoin: check proof-of-work block signature
2301 if (checkEntropySig && !CheckBlockSignature(false))
2302 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2306 // Check transactions
2307 BOOST_FOREACH(const CTransaction& tx, vtx)
2309 if (!tx.CheckTransaction())
2310 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2313 // Check for duplicate txids. This is caught by ConnectInputs(),
2314 // but catching it earlier avoids a potential DoS attack:
2315 set<uint256> uniqueTx;
2316 BOOST_FOREACH(const CTransaction& tx, vtx)
2318 uniqueTx.insert(tx.GetHash());
2320 if (uniqueTx.size() != vtx.size())
2321 return DoS(100, error("CheckBlock() : duplicate transaction"));
2323 unsigned int nSigOps = 0;
2324 BOOST_FOREACH(const CTransaction& tx, vtx)
2326 nSigOps += tx.GetLegacySigOpCount();
2328 if (nSigOps > MAX_BLOCK_SIGOPS)
2329 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2331 // Check merkle root
2332 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2333 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2339 bool CBlock::AcceptBlock()
2341 // Check for duplicate
2342 uint256 hash = GetHash();
2343 if (mapBlockIndex.count(hash))
2344 return error("AcceptBlock() : block already in mapBlockIndex");
2346 // Get prev block index
2347 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2348 if (mi == mapBlockIndex.end())
2349 return DoS(10, error("AcceptBlock() : prev block not found"));
2350 CBlockIndex* pindexPrev = (*mi).second;
2351 int nHeight = pindexPrev->nHeight+1;
2353 // Check proof-of-work or proof-of-stake
2354 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2355 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2357 // Check timestamp against prev
2358 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2359 return error("AcceptBlock() : block's timestamp is too early");
2361 // Check that all transactions are finalized
2362 BOOST_FOREACH(const CTransaction& tx, vtx)
2363 if (!tx.IsFinal(nHeight, GetBlockTime()))
2364 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2366 // Check that the block chain matches the known block chain up to a checkpoint
2367 if (!Checkpoints::CheckHardened(nHeight, hash))
2368 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2370 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2372 // Check that the block satisfies synchronized checkpoint
2373 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2374 return error("AcceptBlock() : rejected by synchronized checkpoint");
2376 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2377 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2379 // Enforce rule that the coinbase starts with serialized block height
2380 CScript expect = CScript() << nHeight;
2381 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2382 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2383 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2385 // Write block to history file
2386 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2387 return error("AcceptBlock() : out of disk space");
2388 unsigned int nFile = -1;
2389 unsigned int nBlockPos = 0;
2390 if (!WriteToDisk(nFile, nBlockPos))
2391 return error("AcceptBlock() : WriteToDisk failed");
2392 if (!AddToBlockIndex(nFile, nBlockPos))
2393 return error("AcceptBlock() : AddToBlockIndex failed");
2395 // Relay inventory, but don't relay old inventory during initial block download
2396 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2397 if (hashBestChain == hash)
2400 BOOST_FOREACH(CNode* pnode, vNodes)
2401 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2402 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2405 // ppcoin: check pending sync-checkpoint
2406 Checkpoints::AcceptPendingSyncCheckpoint();
2411 uint256 CBlockIndex::GetBlockTrust() const
2414 bnTarget.SetCompact(nBits);
2420 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2421 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2425 // Calculate work amount for block
2426 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2428 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2429 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2431 // Return nPoWTrust for the first 12 blocks
2432 if (pprev == NULL || pprev->nHeight < 12)
2435 const CBlockIndex* currentIndex = pprev;
2437 if(IsProofOfStake())
2439 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2441 // Return 1/3 of score if parent block is not the PoW block
2442 if (!pprev->IsProofOfWork())
2443 return (bnNewTrust / 3).getuint256();
2447 // Check last 12 blocks type
2448 while (pprev->nHeight - currentIndex->nHeight < 12)
2450 if (currentIndex->IsProofOfWork())
2452 currentIndex = currentIndex->pprev;
2455 // Return 1/3 of score if less than 3 PoW blocks found
2457 return (bnNewTrust / 3).getuint256();
2459 return bnNewTrust.getuint256();
2463 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2465 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2466 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2467 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2471 // Check last 12 blocks type
2472 while (pprev->nHeight - currentIndex->nHeight < 12)
2474 if (currentIndex->IsProofOfStake())
2476 currentIndex = currentIndex->pprev;
2479 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2481 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2483 bnTarget.SetCompact(pprev->nBits);
2488 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2490 // Return nPoWTrust + full trust score for previous block nBits
2491 return nPoWTrust + bnNewTrust.getuint256();
2495 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2497 unsigned int nFound = 0;
2498 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2500 if (pstart->nVersion >= minVersion)
2502 pstart = pstart->pprev;
2504 return (nFound >= nRequired);
2507 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2509 // Check for duplicate
2510 uint256 hash = pblock->GetHash();
2511 if (mapBlockIndex.count(hash))
2512 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2513 if (mapOrphanBlocks.count(hash))
2514 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2516 // ppcoin: check proof-of-stake
2517 // Limited duplicity on stake: prevents block flood attack
2518 // Duplicate stake allowed only when there is orphan child block
2519 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2520 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());
2522 // Preliminary checks
2523 if (!pblock->CheckBlock())
2524 return error("ProcessBlock() : CheckBlock FAILED");
2526 // ppcoin: verify hash target and signature of coinstake tx
2527 if (pblock->IsProofOfStake())
2529 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2530 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2532 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2533 return false; // do not error here as we expect this during initial block download
2535 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2536 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2539 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2540 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2542 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2543 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2545 bnNewBlock.SetCompact(pblock->nBits);
2548 if (pblock->IsProofOfStake())
2549 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2551 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2553 if (bnNewBlock > bnRequired)
2556 pfrom->Misbehaving(100);
2557 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2561 // ppcoin: ask for pending sync-checkpoint if any
2562 if (!IsInitialBlockDownload())
2563 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2565 // If don't already have its previous block, shunt it off to holding area until we get it
2566 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2568 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2569 CBlock* pblock2 = new CBlock(*pblock);
2570 // ppcoin: check proof-of-stake
2571 if (pblock2->IsProofOfStake())
2573 // Limited duplicity on stake: prevents block flood attack
2574 // Duplicate stake allowed only when there is orphan child block
2575 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2576 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());
2578 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2580 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2581 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2583 // Ask this guy to fill in what we're missing
2586 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2587 // ppcoin: getblocks may not obtain the ancestor block rejected
2588 // earlier by duplicate-stake check so we ask for it again directly
2589 if (!IsInitialBlockDownload())
2590 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2596 if (!pblock->AcceptBlock())
2597 return error("ProcessBlock() : AcceptBlock FAILED");
2599 // Recursively process any orphan blocks that depended on this one
2600 vector<uint256> vWorkQueue;
2601 vWorkQueue.push_back(hash);
2602 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2604 uint256 hashPrev = vWorkQueue[i];
2605 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2606 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2609 CBlock* pblockOrphan = (*mi).second;
2610 if (pblockOrphan->AcceptBlock())
2611 vWorkQueue.push_back(pblockOrphan->GetHash());
2612 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2613 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2614 delete pblockOrphan;
2616 mapOrphanBlocksByPrev.erase(hashPrev);
2619 printf("ProcessBlock: ACCEPTED\n");
2621 // ppcoin: if responsible for sync-checkpoint send it
2622 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2623 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2628 // novacoin: attempt to generate suitable proof-of-stake
2629 bool CBlock::SignBlock(CWallet& wallet)
2631 // if we are trying to sign
2632 // something except proof-of-stake block template
2633 if (!vtx[0].vout[0].IsEmpty())
2636 // if we are trying to sign
2637 // a complete proof-of-stake block
2638 if (IsProofOfStake())
2641 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2644 CTransaction txCoinStake;
2645 int64 nSearchTime = txCoinStake.nTime; // search to current time
2647 if (nSearchTime > nLastCoinStakeSearchTime)
2649 if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2651 if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2653 // make sure coinstake would meet timestamp protocol
2654 // as it would be the same as the block timestamp
2655 vtx[0].nTime = nTime = txCoinStake.nTime;
2656 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2657 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2659 // we have to make sure that we have no future timestamps in
2660 // our transactions set
2661 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2662 if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2664 vtx.insert(vtx.begin() + 1, txCoinStake);
2665 hashMerkleRoot = BuildMerkleTree();
2667 // append a signature to our block
2668 return key.Sign(GetHash(), vchBlockSig);
2671 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2672 nLastCoinStakeSearchTime = nSearchTime;
2678 // ppcoin: check block signature
2679 bool CBlock::CheckBlockSignature(bool fProofOfStake) const
2681 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2682 return vchBlockSig.empty();
2684 vector<valtype> vSolutions;
2685 txnouttype whichType;
2689 const CTxOut& txout = vtx[1].vout[1];
2691 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2693 if (whichType == TX_PUBKEY)
2695 valtype& vchPubKey = vSolutions[0];
2697 if (!key.SetPubKey(vchPubKey))
2699 if (vchBlockSig.empty())
2701 return key.Verify(GetHash(), vchBlockSig);
2706 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2708 const CTxOut& txout = vtx[0].vout[i];
2710 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2713 if (whichType == TX_PUBKEY)
2716 valtype& vchPubKey = vSolutions[0];
2718 if (!key.SetPubKey(vchPubKey))
2720 if (vchBlockSig.empty())
2722 if(!key.Verify(GetHash(), vchBlockSig))
2732 bool CheckDiskSpace(uint64 nAdditionalBytes)
2734 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2736 // Check for nMinDiskSpace bytes (currently 50MB)
2737 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2740 string strMessage = _("Warning: Disk space is low!");
2741 strMiscWarning = strMessage;
2742 printf("*** %s\n", strMessage.c_str());
2743 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2750 static filesystem::path BlockFilePath(unsigned int nFile)
2752 string strBlockFn = strprintf("blk%04u.dat", nFile);
2753 return GetDataDir() / strBlockFn;
2756 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2758 if ((nFile < 1) || (nFile == (unsigned int) -1))
2760 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2763 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2765 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2774 static unsigned int nCurrentBlockFile = 1;
2776 FILE* AppendBlockFile(unsigned int& nFileRet)
2781 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2784 if (fseek(file, 0, SEEK_END) != 0)
2786 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2787 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2789 nFileRet = nCurrentBlockFile;
2793 nCurrentBlockFile++;
2797 bool LoadBlockIndex(bool fAllowNew)
2801 pchMessageStart[0] = 0xcd;
2802 pchMessageStart[1] = 0xf2;
2803 pchMessageStart[2] = 0xc0;
2804 pchMessageStart[3] = 0xef;
2806 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2807 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2808 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2809 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2810 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2817 if (!txdb.LoadBlockIndex())
2821 // Init with genesis block
2823 if (mapBlockIndex.empty())
2832 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2833 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2834 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2836 // vMerkleTree: 4cb33b3b6a
2840 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2841 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2842 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2844 // vMerkleTree: 4cb33b3b6a
2846 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2848 txNew.nTime = 1360105017;
2849 txNew.vin.resize(1);
2850 txNew.vout.resize(1);
2851 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2852 txNew.vout[0].SetEmpty();
2854 block.vtx.push_back(txNew);
2855 block.hashPrevBlock = 0;
2856 block.hashMerkleRoot = block.BuildMerkleTree();
2858 block.nTime = 1360105017;
2859 block.nBits = bnProofOfWorkLimit.GetCompact();
2860 block.nNonce = !fTestNet ? 1575379 : 46534;
2863 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2865 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2866 assert(block.CheckBlock());
2868 // Start new block file
2870 unsigned int nBlockPos;
2871 if (!block.WriteToDisk(nFile, nBlockPos))
2872 return error("LoadBlockIndex() : writing genesis block to disk failed");
2873 if (!block.AddToBlockIndex(nFile, nBlockPos))
2874 return error("LoadBlockIndex() : genesis block not accepted");
2876 // initialize synchronized checkpoint
2877 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2878 return error("LoadBlockIndex() : failed to init sync checkpoint");
2880 // upgrade time set to zero if txdb initialized
2882 if (!txdb.WriteModifierUpgradeTime(0))
2883 return error("LoadBlockIndex() : failed to init upgrade info");
2884 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2890 string strPubKey = "";
2891 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2893 // write checkpoint master key to db
2895 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2896 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2897 if (!txdb.TxnCommit())
2898 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2899 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2900 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2903 // upgrade time set to zero if blocktreedb initialized
2904 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2906 if (nModifierUpgradeTime)
2907 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2909 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2913 nModifierUpgradeTime = GetTime();
2914 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2915 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2916 return error("LoadBlockIndex() : failed to write upgrade info");
2929 void PrintBlockTree()
2931 // pre-compute tree structure
2932 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2933 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2935 CBlockIndex* pindex = (*mi).second;
2936 mapNext[pindex->pprev].push_back(pindex);
2938 //while (rand() % 3 == 0)
2939 // mapNext[pindex->pprev].push_back(pindex);
2942 vector<pair<int, CBlockIndex*> > vStack;
2943 vStack.push_back(make_pair(0, pindexGenesisBlock));
2946 while (!vStack.empty())
2948 int nCol = vStack.back().first;
2949 CBlockIndex* pindex = vStack.back().second;
2952 // print split or gap
2953 if (nCol > nPrevCol)
2955 for (int i = 0; i < nCol-1; i++)
2959 else if (nCol < nPrevCol)
2961 for (int i = 0; i < nCol; i++)
2968 for (int i = 0; i < nCol; i++)
2973 block.ReadFromDisk(pindex);
2974 printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
2978 block.GetHash().ToString().c_str(),
2980 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2981 FormatMoney(pindex->nMint).c_str(),
2984 PrintWallets(block);
2986 // put the main time-chain first
2987 vector<CBlockIndex*>& vNext = mapNext[pindex];
2988 for (unsigned int i = 0; i < vNext.size(); i++)
2990 if (vNext[i]->pnext)
2992 swap(vNext[0], vNext[i]);
2998 for (unsigned int i = 0; i < vNext.size(); i++)
2999 vStack.push_back(make_pair(nCol+i, vNext[i]));
3003 bool LoadExternalBlockFile(FILE* fileIn)
3005 int64 nStart = GetTimeMillis();
3011 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
3012 unsigned int nPos = 0;
3013 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
3015 unsigned char pchData[65536];
3017 fseek(blkdat, nPos, SEEK_SET);
3018 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
3021 nPos = (unsigned int)-1;
3024 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
3027 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
3029 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
3032 nPos += ((unsigned char*)nFind - pchData) + 1;
3035 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
3036 } while(!fRequestShutdown);
3037 if (nPos == (unsigned int)-1)
3039 fseek(blkdat, nPos, SEEK_SET);
3042 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
3046 if (ProcessBlock(NULL,&block))
3054 catch (std::exception &e) {
3055 printf("%s() : Deserialize or I/O error caught during load\n",
3056 BOOST_CURRENT_FUNCTION);
3059 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
3063 //////////////////////////////////////////////////////////////////////////////
3068 extern map<uint256, CAlert> mapAlerts;
3069 extern CCriticalSection cs_mapAlerts;
3071 string GetWarnings(string strFor)
3074 string strStatusBar;
3077 if (GetBoolArg("-testsafemode"))
3080 // Misc warnings like out of disk space and clock is wrong
3081 if (strMiscWarning != "")
3084 strStatusBar = strMiscWarning;
3087 // if detected unmet upgrade requirement enter safe mode
3088 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3089 if (IsFixedModifierInterval(nModifierUpgradeTime + 60*60*24)) // 1 day margin
3092 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3095 // if detected invalid checkpoint enter safe mode
3096 if (Checkpoints::hashInvalidCheckpoint != 0)
3099 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3105 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3107 const CAlert& alert = item.second;
3108 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3110 nPriority = alert.nPriority;
3111 strStatusBar = alert.strStatusBar;
3112 if (nPriority > 1000)
3113 strRPC = strStatusBar;
3118 if (strFor == "statusbar")
3119 return strStatusBar;
3120 else if (strFor == "rpc")
3122 assert(!"GetWarnings() : invalid parameter");
3133 //////////////////////////////////////////////////////////////////////////////
3139 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3145 bool txInMap = false;
3148 txInMap = (mempool.exists(inv.hash));
3151 mapOrphanTransactions.count(inv.hash) ||
3152 txdb.ContainsTx(inv.hash);
3156 return mapBlockIndex.count(inv.hash) ||
3157 mapOrphanBlocks.count(inv.hash);
3159 // Don't know what it is, just say we already got one
3166 // The message start string is designed to be unlikely to occur in normal data.
3167 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3168 // a large 4-byte int at any alignment.
3169 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3171 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3173 static map<CService, CPubKey> mapReuseKey;
3174 RandAddSeedPerfmon();
3176 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3177 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3179 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3183 if (strCommand == "version")
3185 // Each connection can only send one version message
3186 if (pfrom->nVersion != 0)
3188 pfrom->Misbehaving(1);
3196 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3197 if (pfrom->nVersion < MIN_PROTO_VERSION)
3199 // Since February 20, 2012, the protocol is initiated at version 209,
3200 // and earlier versions are no longer supported
3201 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3202 pfrom->fDisconnect = true;
3206 if (pfrom->nVersion == 10300)
3207 pfrom->nVersion = 300;
3209 vRecv >> addrFrom >> nNonce;
3211 vRecv >> pfrom->strSubVer;
3213 vRecv >> pfrom->nStartingHeight;
3215 if (pfrom->fInbound && addrMe.IsRoutable())
3217 pfrom->addrLocal = addrMe;
3221 // Disconnect if we connected to ourself
3222 if (nNonce == nLocalHostNonce && nNonce > 1)
3224 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3225 pfrom->fDisconnect = true;
3229 if (pfrom->nVersion < 60010)
3231 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3232 pfrom->fDisconnect = true;
3236 // record my external IP reported by peer
3237 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3238 addrSeenByPeer = addrMe;
3240 // Be shy and don't send version until we hear
3241 if (pfrom->fInbound)
3242 pfrom->PushVersion();
3244 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3246 AddTimeData(pfrom->addr, nTime);
3249 pfrom->PushMessage("verack");
3250 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3252 if (!pfrom->fInbound)
3254 // Advertise our address
3255 if (!fNoListen && !IsInitialBlockDownload())
3257 CAddress addr = GetLocalAddress(&pfrom->addr);
3258 if (addr.IsRoutable())
3259 pfrom->PushAddress(addr);
3262 // Get recent addresses
3263 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3265 pfrom->PushMessage("getaddr");
3266 pfrom->fGetAddr = true;
3268 addrman.Good(pfrom->addr);
3270 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3272 addrman.Add(addrFrom, addrFrom);
3273 addrman.Good(addrFrom);
3277 // Ask the first connected node for block updates
3278 static int nAskedForBlocks = 0;
3279 if (!pfrom->fClient && !pfrom->fOneShot &&
3280 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3281 (pfrom->nVersion < NOBLKS_VERSION_START ||
3282 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3283 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3286 pfrom->PushGetBlocks(pindexBest, uint256(0));
3292 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3293 item.second.RelayTo(pfrom);
3296 // Relay sync-checkpoint
3298 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3299 if (!Checkpoints::checkpointMessage.IsNull())
3300 Checkpoints::checkpointMessage.RelayTo(pfrom);
3303 pfrom->fSuccessfullyConnected = true;
3305 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());
3307 cPeerBlockCounts.input(pfrom->nStartingHeight);
3309 // ppcoin: ask for pending sync-checkpoint if any
3310 if (!IsInitialBlockDownload())
3311 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3315 else if (pfrom->nVersion == 0)
3317 // Must have a version message before anything else
3318 pfrom->Misbehaving(1);
3323 else if (strCommand == "verack")
3325 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3329 else if (strCommand == "addr")
3331 vector<CAddress> vAddr;
3334 // Don't want addr from older versions unless seeding
3335 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3337 if (vAddr.size() > 1000)
3339 pfrom->Misbehaving(20);
3340 return error("message addr size() = %"PRIszu"", vAddr.size());
3343 // Store the new addresses
3344 vector<CAddress> vAddrOk;
3345 int64 nNow = GetAdjustedTime();
3346 int64 nSince = nNow - 10 * 60;
3347 BOOST_FOREACH(CAddress& addr, vAddr)
3351 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3352 addr.nTime = nNow - 5 * 24 * 60 * 60;
3353 pfrom->AddAddressKnown(addr);
3354 bool fReachable = IsReachable(addr);
3355 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3357 // Relay to a limited number of other nodes
3360 // Use deterministic randomness to send to the same nodes for 24 hours
3361 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3362 static uint256 hashSalt;
3364 hashSalt = GetRandHash();
3365 uint64 hashAddr = addr.GetHash();
3366 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3367 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3368 multimap<uint256, CNode*> mapMix;
3369 BOOST_FOREACH(CNode* pnode, vNodes)
3371 if (pnode->nVersion < CADDR_TIME_VERSION)
3373 unsigned int nPointer;
3374 memcpy(&nPointer, &pnode, sizeof(nPointer));
3375 uint256 hashKey = hashRand ^ nPointer;
3376 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3377 mapMix.insert(make_pair(hashKey, pnode));
3379 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3380 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3381 ((*mi).second)->PushAddress(addr);
3384 // Do not store addresses outside our network
3386 vAddrOk.push_back(addr);
3388 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3389 if (vAddr.size() < 1000)
3390 pfrom->fGetAddr = false;
3391 if (pfrom->fOneShot)
3392 pfrom->fDisconnect = true;
3395 else if (strCommand == "inv")
3399 if (vInv.size() > MAX_INV_SZ)
3401 pfrom->Misbehaving(20);
3402 return error("message inv size() = %"PRIszu"", vInv.size());
3405 // find last block in inv vector
3406 unsigned int nLastBlock = (unsigned int)(-1);
3407 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3408 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3409 nLastBlock = vInv.size() - 1 - nInv;
3414 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3416 const CInv &inv = vInv[nInv];
3420 pfrom->AddInventoryKnown(inv);
3422 bool fAlreadyHave = AlreadyHave(txdb, inv);
3424 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3428 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3429 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3430 } else if (nInv == nLastBlock) {
3431 // In case we are on a very long side-chain, it is possible that we already have
3432 // the last block in an inv bundle sent in response to getblocks. Try to detect
3433 // this situation and push another getblocks to continue.
3434 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3436 printf("force request: %s\n", inv.ToString().c_str());
3439 // Track requests for our stuff
3440 Inventory(inv.hash);
3445 else if (strCommand == "getdata")
3449 if (vInv.size() > MAX_INV_SZ)
3451 pfrom->Misbehaving(20);
3452 return error("message getdata size() = %"PRIszu"", vInv.size());
3455 if (fDebugNet || (vInv.size() != 1))
3456 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3458 BOOST_FOREACH(const CInv& inv, vInv)
3462 if (fDebugNet || (vInv.size() == 1))
3463 printf("received getdata for: %s\n", inv.ToString().c_str());
3465 if (inv.type == MSG_BLOCK)
3467 // Send block from disk
3468 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3469 if (mi != mapBlockIndex.end())
3472 block.ReadFromDisk((*mi).second);
3473 pfrom->PushMessage("block", block);
3475 // Trigger them to send a getblocks request for the next batch of inventory
3476 if (inv.hash == pfrom->hashContinue)
3478 // ppcoin: send latest proof-of-work block to allow the
3479 // download node to accept as orphan (proof-of-stake
3480 // block might be rejected by stake connection check)
3482 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3483 pfrom->PushMessage("inv", vInv);
3484 pfrom->hashContinue = 0;
3488 else if (inv.IsKnownType())
3490 // Send stream from relay memory
3491 bool pushed = false;
3494 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3495 if (mi != mapRelay.end()) {
3496 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3500 if (!pushed && inv.type == MSG_TX) {
3502 if (mempool.exists(inv.hash)) {
3503 CTransaction tx = mempool.lookup(inv.hash);
3504 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3507 pfrom->PushMessage("tx", ss);
3512 // Track requests for our stuff
3513 Inventory(inv.hash);
3518 else if (strCommand == "getblocks")
3520 CBlockLocator locator;
3522 vRecv >> locator >> hashStop;
3524 // Find the last block the caller has in the main chain
3525 CBlockIndex* pindex = locator.GetBlockIndex();
3527 // Send the rest of the chain
3529 pindex = pindex->pnext;
3531 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3532 for (; pindex; pindex = pindex->pnext)
3534 if (pindex->GetBlockHash() == hashStop)
3536 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3537 // ppcoin: tell downloading node about the latest block if it's
3538 // without risk being rejected due to stake connection check
3539 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3540 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3543 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3546 // When this block is requested, we'll send an inv that'll make them
3547 // getblocks the next batch of inventory.
3548 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3549 pfrom->hashContinue = pindex->GetBlockHash();
3554 else if (strCommand == "checkpoint")
3556 CSyncCheckpoint checkpoint;
3557 vRecv >> checkpoint;
3559 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3562 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3564 BOOST_FOREACH(CNode* pnode, vNodes)
3565 checkpoint.RelayTo(pnode);
3569 else if (strCommand == "getheaders")
3571 CBlockLocator locator;
3573 vRecv >> locator >> hashStop;
3575 CBlockIndex* pindex = NULL;
3576 if (locator.IsNull())
3578 // If locator is null, return the hashStop block
3579 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3580 if (mi == mapBlockIndex.end())
3582 pindex = (*mi).second;
3586 // Find the last block the caller has in the main chain
3587 pindex = locator.GetBlockIndex();
3589 pindex = pindex->pnext;
3592 vector<CBlock> vHeaders;
3594 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3595 for (; pindex; pindex = pindex->pnext)
3597 vHeaders.push_back(pindex->GetBlockHeader());
3598 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3601 pfrom->PushMessage("headers", vHeaders);
3605 else if (strCommand == "tx")
3607 vector<uint256> vWorkQueue;
3608 vector<uint256> vEraseQueue;
3609 CDataStream vMsg(vRecv);
3614 CInv inv(MSG_TX, tx.GetHash());
3615 pfrom->AddInventoryKnown(inv);
3617 bool fMissingInputs = false;
3618 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3620 SyncWithWallets(tx, NULL, true);
3621 RelayTransaction(tx, inv.hash);
3622 mapAlreadyAskedFor.erase(inv);
3623 vWorkQueue.push_back(inv.hash);
3624 vEraseQueue.push_back(inv.hash);
3626 // Recursively process any orphan transactions that depended on this one
3627 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3629 uint256 hashPrev = vWorkQueue[i];
3630 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3631 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3634 const uint256& orphanTxHash = *mi;
3635 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3636 bool fMissingInputs2 = false;
3638 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3640 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3641 SyncWithWallets(tx, NULL, true);
3642 RelayTransaction(orphanTx, orphanTxHash);
3643 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3644 vWorkQueue.push_back(orphanTxHash);
3645 vEraseQueue.push_back(orphanTxHash);
3647 else if (!fMissingInputs2)
3650 vEraseQueue.push_back(orphanTxHash);
3651 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3656 BOOST_FOREACH(uint256 hash, vEraseQueue)
3657 EraseOrphanTx(hash);
3659 else if (fMissingInputs)
3663 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3664 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3666 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3668 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3672 else if (strCommand == "block")
3676 uint256 hashBlock = block.GetHash();
3678 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3681 CInv inv(MSG_BLOCK, hashBlock);
3682 pfrom->AddInventoryKnown(inv);
3684 if (ProcessBlock(pfrom, &block))
3685 mapAlreadyAskedFor.erase(inv);
3686 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3690 else if (strCommand == "getaddr")
3692 // Don't return addresses older than nCutOff timestamp
3693 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3694 pfrom->vAddrToSend.clear();
3695 vector<CAddress> vAddr = addrman.GetAddr();
3696 BOOST_FOREACH(const CAddress &addr, vAddr)
3697 if(addr.nTime > nCutOff)
3698 pfrom->PushAddress(addr);
3702 else if (strCommand == "mempool")
3704 std::vector<uint256> vtxid;
3705 mempool.queryHashes(vtxid);
3707 for (unsigned int i = 0; i < vtxid.size(); i++) {
3708 CInv inv(MSG_TX, vtxid[i]);
3709 vInv.push_back(inv);
3710 if (i == (MAX_INV_SZ - 1))
3713 if (vInv.size() > 0)
3714 pfrom->PushMessage("inv", vInv);
3718 else if (strCommand == "checkorder")
3723 if (!GetBoolArg("-allowreceivebyip"))
3725 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3732 /// we have a chance to check the order here
3734 // Keep giving the same key to the same ip until they use it
3735 if (!mapReuseKey.count(pfrom->addr))
3736 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3738 // Send back approval of order and pubkey to use
3739 CScript scriptPubKey;
3740 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3741 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3745 else if (strCommand == "reply")
3750 CRequestTracker tracker;
3752 LOCK(pfrom->cs_mapRequests);
3753 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3754 if (mi != pfrom->mapRequests.end())
3756 tracker = (*mi).second;
3757 pfrom->mapRequests.erase(mi);
3760 if (!tracker.IsNull())
3761 tracker.fn(tracker.param1, vRecv);
3765 else if (strCommand == "ping")
3767 if (pfrom->nVersion > BIP0031_VERSION)
3771 // Echo the message back with the nonce. This allows for two useful features:
3773 // 1) A remote node can quickly check if the connection is operational
3774 // 2) Remote nodes can measure the latency of the network thread. If this node
3775 // is overloaded it won't respond to pings quickly and the remote node can
3776 // avoid sending us more work, like chain download requests.
3778 // The nonce stops the remote getting confused between different pings: without
3779 // it, if the remote node sends a ping once per second and this node takes 5
3780 // seconds to respond to each, the 5th ping the remote sends would appear to
3781 // return very quickly.
3782 pfrom->PushMessage("pong", nonce);
3787 else if (strCommand == "alert")
3792 uint256 alertHash = alert.GetHash();
3793 if (pfrom->setKnown.count(alertHash) == 0)
3795 if (alert.ProcessAlert())
3798 pfrom->setKnown.insert(alertHash);
3801 BOOST_FOREACH(CNode* pnode, vNodes)
3802 alert.RelayTo(pnode);
3806 // Small DoS penalty so peers that send us lots of
3807 // duplicate/expired/invalid-signature/whatever alerts
3808 // eventually get banned.
3809 // This isn't a Misbehaving(100) (immediate ban) because the
3810 // peer might be an older or different implementation with
3811 // a different signature key, etc.
3812 pfrom->Misbehaving(10);
3820 // Ignore unknown commands for extensibility
3824 // Update the last seen time for this node's address
3825 if (pfrom->fNetworkNode)
3826 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3827 AddressCurrentlyConnected(pfrom->addr);
3833 bool ProcessMessages(CNode* pfrom)
3835 CDataStream& vRecv = pfrom->vRecv;
3839 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3843 // (4) message start
3852 // Don't bother if send buffer is too full to respond anyway
3853 if (pfrom->vSend.size() >= SendBufferSize())
3856 // Scan for message start
3857 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3858 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3859 if (vRecv.end() - pstart < nHeaderSize)
3861 if ((int)vRecv.size() > nHeaderSize)
3863 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3864 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3868 if (pstart - vRecv.begin() > 0)
3869 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3870 vRecv.erase(vRecv.begin(), pstart);
3873 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3878 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3881 string strCommand = hdr.GetCommand();
3884 unsigned int nMessageSize = hdr.nMessageSize;
3885 if (nMessageSize > MAX_SIZE)
3887 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3890 if (nMessageSize > vRecv.size())
3892 // Rewind and wait for rest of message
3893 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3898 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3899 unsigned int nChecksum = 0;
3900 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3901 if (nChecksum != hdr.nChecksum)
3903 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3904 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3908 // Copy message to its own buffer
3909 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3910 vRecv.ignore(nMessageSize);
3918 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3923 catch (std::ios_base::failure& e)
3925 if (strstr(e.what(), "end of data"))
3927 // Allow exceptions from under-length message on vRecv
3928 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());
3930 else if (strstr(e.what(), "size too large"))
3932 // Allow exceptions from over-long size
3933 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3937 PrintExceptionContinue(&e, "ProcessMessages()");
3940 catch (std::exception& e) {
3941 PrintExceptionContinue(&e, "ProcessMessages()");
3943 PrintExceptionContinue(NULL, "ProcessMessages()");
3947 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3955 bool SendMessages(CNode* pto, bool fSendTrickle)
3957 TRY_LOCK(cs_main, lockMain);
3959 // Don't send anything until we get their version message
3960 if (pto->nVersion == 0)
3963 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3965 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3967 if (pto->nVersion > BIP0031_VERSION)
3968 pto->PushMessage("ping", nonce);
3970 pto->PushMessage("ping");
3974 if (pto->fStartSync) {
3975 pto->fStartSync = false;
3976 pto->PushGetBlocks(pindexBest, uint256(0));
3979 // Resend wallet transactions that haven't gotten in a block yet
3980 ResendWalletTransactions();
3982 // Address refresh broadcast
3983 static int64 nLastRebroadcast;
3984 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
3988 BOOST_FOREACH(CNode* pnode, vNodes)
3990 // Periodically clear setAddrKnown to allow refresh broadcasts
3991 if (nLastRebroadcast)
3992 pnode->setAddrKnown.clear();
3994 // Rebroadcast our address
3997 CAddress addr = GetLocalAddress(&pnode->addr);
3998 if (addr.IsRoutable())
3999 pnode->PushAddress(addr);
4003 nLastRebroadcast = GetTime();
4011 vector<CAddress> vAddr;
4012 vAddr.reserve(pto->vAddrToSend.size());
4013 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4015 // returns true if wasn't already contained in the set
4016 if (pto->setAddrKnown.insert(addr).second)
4018 vAddr.push_back(addr);
4019 // receiver rejects addr messages larger than 1000
4020 if (vAddr.size() >= 1000)
4022 pto->PushMessage("addr", vAddr);
4027 pto->vAddrToSend.clear();
4029 pto->PushMessage("addr", vAddr);
4034 // Message: inventory
4037 vector<CInv> vInvWait;
4039 LOCK(pto->cs_inventory);
4040 vInv.reserve(pto->vInventoryToSend.size());
4041 vInvWait.reserve(pto->vInventoryToSend.size());
4042 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4044 if (pto->setInventoryKnown.count(inv))
4047 // trickle out tx inv to protect privacy
4048 if (inv.type == MSG_TX && !fSendTrickle)
4050 // 1/4 of tx invs blast to all immediately
4051 static uint256 hashSalt;
4053 hashSalt = GetRandHash();
4054 uint256 hashRand = inv.hash ^ hashSalt;
4055 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4056 bool fTrickleWait = ((hashRand & 3) != 0);
4058 // always trickle our own transactions
4062 if (GetTransaction(inv.hash, wtx))
4064 fTrickleWait = true;
4069 vInvWait.push_back(inv);
4074 // returns true if wasn't already contained in the set
4075 if (pto->setInventoryKnown.insert(inv).second)
4077 vInv.push_back(inv);
4078 if (vInv.size() >= 1000)
4080 pto->PushMessage("inv", vInv);
4085 pto->vInventoryToSend = vInvWait;
4088 pto->PushMessage("inv", vInv);
4094 vector<CInv> vGetData;
4095 int64 nNow = GetTime() * 1000000;
4097 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4099 const CInv& inv = (*pto->mapAskFor.begin()).second;
4100 if (!AlreadyHave(txdb, inv))
4103 printf("sending getdata: %s\n", inv.ToString().c_str());
4104 vGetData.push_back(inv);
4105 if (vGetData.size() >= 1000)
4107 pto->PushMessage("getdata", vGetData);
4110 mapAlreadyAskedFor[inv] = nNow;
4112 pto->mapAskFor.erase(pto->mapAskFor.begin());
4114 if (!vGetData.empty())
4115 pto->PushMessage("getdata", vGetData);