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 "zerocoin/Zerocoin.h"
16 #include <boost/algorithm/string/replace.hpp>
17 #include <boost/filesystem.hpp>
18 #include <boost/filesystem/fstream.hpp>
22 using namespace boost;
28 CCriticalSection cs_setpwalletRegistered;
29 set<CWallet*> setpwalletRegistered;
31 CCriticalSection cs_main;
34 unsigned int nTransactionsUpdated = 0;
36 map<uint256, CBlockIndex*> mapBlockIndex;
37 set<pair<COutPoint, unsigned int> > setStakeSeen;
38 libzerocoin::Params* ZCParams;
40 CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty
41 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
42 CBigNum bnProofOfStakeLimit(~uint256(0) >> 27); // proof of stake target limit since 20 June 2013, equal to 0.03125 proof of stake difficulty
43 CBigNum bnProofOfStakeHardLimit(~uint256(0) >> 30); // disabled temporarily, will be used in the future to fix minimal proof of stake difficulty at 0.25
44 uint256 nPoWBase = uint256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // difficulty-1 target
46 CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16);
48 unsigned int nStakeMinAge = 60 * 60 * 24 * 30; // 30 days as zero time weight
49 unsigned int nStakeMaxAge = 60 * 60 * 24 * 90; // 90 days as full weight
50 unsigned int nStakeTargetSpacing = 10 * 60; // 10-minute stakes spacing
51 unsigned int nModifierInterval = 6 * 60 * 60; // time to elapse before new modifier is computed
53 int nCoinbaseMaturity = 500;
54 CBlockIndex* pindexGenesisBlock = NULL;
57 uint256 nBestChainTrust = 0;
58 uint256 nBestInvalidTrust = 0;
60 uint256 hashBestChain = 0;
61 CBlockIndex* pindexBest = NULL;
62 int64 nTimeBestReceived = 0;
63 int nScriptCheckThreads = 0;
65 CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
67 map<uint256, CBlock*> mapOrphanBlocks;
68 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
69 set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
70 map<uint256, uint256> mapProofOfStake;
72 map<uint256, CTransaction> mapOrphanTransactions;
73 map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
75 // Constant stuff for coinbase transactions we create:
76 CScript COINBASE_FLAGS;
78 const string strMessageMagic = "NovaCoin Signed Message:\n";
81 int64 nTransactionFee = MIN_TX_FEE;
82 int64 nMinimumInputValue = MIN_TX_FEE;
84 extern enum Checkpoints::CPMode CheckpointsMode;
86 //////////////////////////////////////////////////////////////////////////////
88 // dispatching functions
91 // These functions dispatch to one or all registered wallets
94 void RegisterWallet(CWallet* pwalletIn)
97 LOCK(cs_setpwalletRegistered);
98 setpwalletRegistered.insert(pwalletIn);
102 void UnregisterWallet(CWallet* pwalletIn)
105 LOCK(cs_setpwalletRegistered);
106 setpwalletRegistered.erase(pwalletIn);
110 // check whether the passed transaction is from us
111 bool static IsFromMe(CTransaction& tx)
113 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
114 if (pwallet->IsFromMe(tx))
119 // get the wallet transaction with the given hash (if it exists)
120 bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
122 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
123 if (pwallet->GetTransaction(hashTx,wtx))
128 // erases transaction with the given hash from all wallets
129 void static EraseFromWallets(uint256 hash)
131 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
132 pwallet->EraseFromWallet(hash);
135 // make sure all wallets know about the given transaction, in the given block
136 void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
140 // ppcoin: wallets need to refund inputs when disconnecting coinstake
141 if (tx.IsCoinStake())
143 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
144 if (pwallet->IsFromMe(tx))
145 pwallet->DisableTransaction(tx);
150 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
151 pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
154 // notify wallets about a new best chain
155 void static SetBestChain(const CBlockLocator& loc)
157 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
158 pwallet->SetBestChain(loc);
161 // notify wallets about an updated transaction
162 void static UpdatedTransaction(const uint256& hashTx)
164 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
165 pwallet->UpdatedTransaction(hashTx);
169 void static PrintWallets(const CBlock& block)
171 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
172 pwallet->PrintWallet(block);
175 // notify wallets about an incoming inventory (for request counts)
176 void static Inventory(const uint256& hash)
178 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
179 pwallet->Inventory(hash);
182 // ask wallets to resend their transactions
183 void ResendWalletTransactions()
185 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
186 pwallet->ResendWalletTransactions();
195 //////////////////////////////////////////////////////////////////////////////
197 // mapOrphanTransactions
200 bool AddOrphanTx(const CTransaction& tx)
202 uint256 hash = tx.GetHash();
203 if (mapOrphanTransactions.count(hash))
206 // Ignore big transactions, to avoid a
207 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
208 // large transaction with a missing parent then we assume
209 // it will rebroadcast it later, after the parent transaction(s)
210 // have been mined or received.
211 // 10,000 orphans, each of which is at most 5,000 bytes big is
212 // at most 500 megabytes of orphans:
214 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
218 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
222 mapOrphanTransactions[hash] = tx;
223 BOOST_FOREACH(const CTxIn& txin, tx.vin)
224 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
226 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
227 mapOrphanTransactions.size());
231 void static EraseOrphanTx(uint256 hash)
233 if (!mapOrphanTransactions.count(hash))
235 const CTransaction& tx = mapOrphanTransactions[hash];
236 BOOST_FOREACH(const CTxIn& txin, tx.vin)
238 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
239 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
240 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
242 mapOrphanTransactions.erase(hash);
245 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
247 unsigned int nEvicted = 0;
248 while (mapOrphanTransactions.size() > nMaxOrphans)
250 // Evict a random orphan:
251 uint256 randomhash = GetRandHash();
252 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
253 if (it == mapOrphanTransactions.end())
254 it = mapOrphanTransactions.begin();
255 EraseOrphanTx(it->first);
267 //////////////////////////////////////////////////////////////////////////////
269 // CTransaction and CTxIndex
272 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
275 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
277 if (!ReadFromDisk(txindexRet.pos))
279 if (prevout.n >= vout.size())
287 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
290 return ReadFromDisk(txdb, prevout, txindex);
293 bool CTransaction::ReadFromDisk(COutPoint prevout)
297 return ReadFromDisk(txdb, prevout, txindex);
300 bool CTransaction::IsStandard() const
302 if (nVersion > CTransaction::CURRENT_VERSION)
305 unsigned int nDataOut = 0;
306 txnouttype whichType;
307 BOOST_FOREACH(const CTxIn& txin, vin)
309 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
310 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
311 // ~65-byte public keys, plus a few script ops.
312 if (txin.scriptSig.size() > 500)
314 if (!txin.scriptSig.IsPushOnly())
316 if (!txin.scriptSig.HasCanonicalPushes()) {
320 BOOST_FOREACH(const CTxOut& txout, vout) {
321 if (!::IsStandard(txout.scriptPubKey, whichType)) {
324 if (whichType == TX_NULL_DATA)
327 if (txout.nValue == 0) {
330 if (!txout.scriptPubKey.HasCanonicalPushes()) {
336 // only one OP_RETURN txout is permitted
345 // Check transaction inputs, and make sure any
346 // pay-to-script-hash transactions are evaluating IsStandard scripts
348 // Why bother? To avoid denial-of-service attacks; an attacker
349 // can submit a standard HASH... OP_EQUAL transaction,
350 // which will get accepted into blocks. The redemption
351 // script can be anything; an attacker could use a very
352 // expensive-to-check-upon-redemption script like:
353 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
355 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
358 return true; // Coinbases don't use vin normally
360 for (unsigned int i = 0; i < vin.size(); i++)
362 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
364 vector<vector<unsigned char> > vSolutions;
365 txnouttype whichType;
366 // get the scriptPubKey corresponding to this input:
367 const CScript& prevScript = prev.scriptPubKey;
368 if (!Solver(prevScript, whichType, vSolutions))
370 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
371 if (nArgsExpected < 0)
374 // Transactions with extra stuff in their scriptSigs are
375 // non-standard. Note that this EvalScript() call will
376 // be quick, because if there are any operations
377 // beside "push data" in the scriptSig the
378 // IsStandard() call returns false
379 vector<vector<unsigned char> > stack;
380 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
383 if (whichType == TX_SCRIPTHASH)
387 CScript subscript(stack.back().begin(), stack.back().end());
388 vector<vector<unsigned char> > vSolutions2;
389 txnouttype whichType2;
390 if (!Solver(subscript, whichType2, vSolutions2))
392 if (whichType2 == TX_SCRIPTHASH)
396 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
399 nArgsExpected += tmpExpected;
402 if (stack.size() != (unsigned int)nArgsExpected)
410 CTransaction::GetLegacySigOpCount() const
412 unsigned int nSigOps = 0;
413 BOOST_FOREACH(const CTxIn& txin, vin)
415 nSigOps += txin.scriptSig.GetSigOpCount(false);
417 BOOST_FOREACH(const CTxOut& txout, vout)
419 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
425 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
437 // Load the block this tx is in
439 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
441 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
446 // Update the tx's hashBlock
447 hashBlock = pblock->GetHash();
449 // Locate the transaction
450 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
451 if (pblock->vtx[nIndex] == *(CTransaction*)this)
453 if (nIndex == (int)pblock->vtx.size())
455 vMerkleBranch.clear();
457 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
461 // Fill in merkle branch
462 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
465 // Is the tx in a block that's in the main chain
466 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
467 if (mi == mapBlockIndex.end())
469 CBlockIndex* pindex = (*mi).second;
470 if (!pindex || !pindex->IsInMainChain())
473 return pindexBest->nHeight - pindex->nHeight + 1;
482 bool CTransaction::CheckTransaction() const
484 // Basic checks that don't depend on any context
486 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
488 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
490 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
491 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
493 // Check for negative or overflow output values
495 for (unsigned int i = 0; i < vout.size(); i++)
497 const CTxOut& txout = vout[i];
498 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
499 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
501 if (txout.nValue < 0)
502 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
503 if (txout.nValue > MAX_MONEY)
504 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
505 nValueOut += txout.nValue;
506 if (!MoneyRange(nValueOut))
507 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
510 // Check for duplicate inputs
511 set<COutPoint> vInOutPoints;
512 BOOST_FOREACH(const CTxIn& txin, vin)
514 if (vInOutPoints.count(txin.prevout))
516 vInOutPoints.insert(txin.prevout);
521 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
522 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
526 BOOST_FOREACH(const CTxIn& txin, vin)
527 if (txin.prevout.IsNull())
528 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
534 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
536 // Use new fees approach if we are on test network or
537 // switch date has been reached
538 bool fNewApproach = fTestNet || nTime > FEE_SWITCH_TIME;
540 int64 nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
542 if(!fNewApproach || IsCoinStake())
544 // Enforce 0.01 as minimum fee for old approach or coinstake
546 nMinRelayTxFee = CENT;
549 // Base fee is either nMinTxFee or nMinRelayTxFee
550 int64 nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
552 unsigned int nNewBlockSize = nBlockSize + nBytes;
553 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
561 // Transactions under 1K are free
567 // Free transaction area
568 if (nNewBlockSize < 27000)
573 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
574 // each non empty output which is less than 0.01
576 // It's safe to ignore empty outputs here, because these inputs are allowed
577 // only for coinbase and coinstake transactions.
578 BOOST_FOREACH(const CTxOut& txout, vout)
579 if (txout.nValue < CENT && !txout.IsEmpty())
582 else if (nMinFee < nBaseFee)
584 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if
585 // any output is less than 0.01
586 BOOST_FOREACH(const CTxOut& txout, vout)
587 if (txout.nValue < CENT)
591 // Raise the price as the block approaches full
592 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
594 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
596 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
599 if (!MoneyRange(nMinFee))
606 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
607 bool* pfMissingInputs)
610 *pfMissingInputs = false;
612 if (!tx.CheckTransaction())
613 return error("CTxMemPool::accept() : CheckTransaction failed");
615 // Coinbase is only valid in a block, not as a loose transaction
617 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
619 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
620 if (tx.IsCoinStake())
621 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
623 // To help v0.1.5 clients who would see it as a negative number
624 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
625 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
627 // Rather not work on nonstandard transactions (unless -testnet)
628 if (!fTestNet && !tx.IsStandard())
629 return error("CTxMemPool::accept() : nonstandard transaction type");
631 // Do we already have it?
632 uint256 hash = tx.GetHash();
635 if (mapTx.count(hash))
639 if (txdb.ContainsTx(hash))
642 // Check for conflicts with in-memory transactions
643 CTransaction* ptxOld = NULL;
644 for (unsigned int i = 0; i < tx.vin.size(); i++)
646 COutPoint outpoint = tx.vin[i].prevout;
647 if (mapNextTx.count(outpoint))
649 // Disable replacement feature for now
652 // Allow replacing with a newer version of the same transaction
655 ptxOld = mapNextTx[outpoint].ptx;
656 if (ptxOld->IsFinal())
658 if (!tx.IsNewerThan(*ptxOld))
660 for (unsigned int i = 0; i < tx.vin.size(); i++)
662 COutPoint outpoint = tx.vin[i].prevout;
663 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
673 map<uint256, CTxIndex> mapUnused;
674 bool fInvalid = false;
675 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
678 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
680 *pfMissingInputs = true;
684 // Check for non-standard pay-to-script-hash in inputs
685 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
686 return error("CTxMemPool::accept() : nonstandard transaction input");
688 // Note: if you modify this code to accept non-standard transactions, then
689 // you should add code here to check that the transaction does a
690 // reasonable number of ECDSA signature verifications.
692 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
693 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
695 // Don't accept it if it can't get into a block
696 int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
697 if (nFees < txMinFee)
698 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
699 hash.ToString().c_str(),
702 // Continuously rate-limit free transactions
703 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
704 // be annoying or make others' transactions take longer to confirm.
705 if (nFees < MIN_RELAY_TX_FEE)
707 static CCriticalSection cs;
708 static double dFreeCount;
709 static int64 nLastTime;
710 int64 nNow = GetTime();
714 // Use an exponentially decaying ~10-minute window:
715 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
717 // -limitfreerelay unit is thousand-bytes-per-minute
718 // At default rate it would take over a month to fill 1GB
719 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
720 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
722 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
727 // Check against previous transactions
728 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
729 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, STANDARD_SCRIPT_VERIFY_FLAGS))
731 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
735 // Store transaction in memory
740 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
743 addUnchecked(hash, tx);
746 ///// are we sure this is ok when loading transactions or restoring block txes
747 // If updated, erase old tx from wallet
749 EraseFromWallets(ptxOld->GetHash());
751 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
752 hash.ToString().substr(0,10).c_str(),
757 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
759 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
762 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
764 // Add to memory pool without checking anything. Don't call this directly,
765 // call CTxMemPool::accept to properly check the transaction first.
768 for (unsigned int i = 0; i < tx.vin.size(); i++)
769 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
770 nTransactionsUpdated++;
776 bool CTxMemPool::remove(CTransaction &tx)
778 // Remove transaction from memory pool
781 uint256 hash = tx.GetHash();
782 if (mapTx.count(hash))
784 BOOST_FOREACH(const CTxIn& txin, tx.vin)
785 mapNextTx.erase(txin.prevout);
787 nTransactionsUpdated++;
793 void CTxMemPool::clear()
798 ++nTransactionsUpdated;
801 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
806 vtxid.reserve(mapTx.size());
807 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
808 vtxid.push_back((*mi).first);
814 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
816 if (hashBlock == 0 || nIndex == -1)
819 // Find the block it claims to be in
820 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
821 if (mi == mapBlockIndex.end())
823 CBlockIndex* pindex = (*mi).second;
824 if (!pindex || !pindex->IsInMainChain())
827 // Make sure the merkle branch connects to this block
828 if (!fMerkleVerified)
830 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
832 fMerkleVerified = true;
836 return pindexBest->nHeight - pindex->nHeight + 1;
840 int CMerkleTx::GetBlocksToMaturity() const
842 if (!(IsCoinBase() || IsCoinStake()))
844 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
848 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
852 if (!IsInMainChain() && !ClientConnectInputs())
854 return CTransaction::AcceptToMemoryPool(txdb, false);
858 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
862 bool CMerkleTx::AcceptToMemoryPool()
865 return AcceptToMemoryPool(txdb);
870 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
875 // Add previous supporting transactions first
876 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
878 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
880 uint256 hash = tx.GetHash();
881 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
882 tx.AcceptToMemoryPool(txdb, fCheckInputs);
885 return AcceptToMemoryPool(txdb, fCheckInputs);
890 bool CWalletTx::AcceptWalletTransaction()
893 return AcceptWalletTransaction(txdb);
896 int CTxIndex::GetDepthInMainChain() const
900 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
902 // Find the block in the index
903 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
904 if (mi == mapBlockIndex.end())
906 CBlockIndex* pindex = (*mi).second;
907 if (!pindex || !pindex->IsInMainChain())
909 return 1 + nBestHeight - pindex->nHeight;
912 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
913 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
919 if (mempool.exists(hash))
921 tx = mempool.lookup(hash);
927 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
930 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
931 hashBlock = block.GetHash();
945 //////////////////////////////////////////////////////////////////////////////
947 // CBlock and CBlockIndex
950 static CBlockIndex* pblockindexFBBHLast;
951 CBlockIndex* FindBlockByHeight(int nHeight)
953 CBlockIndex *pblockindex;
954 if (nHeight < nBestHeight / 2)
955 pblockindex = pindexGenesisBlock;
957 pblockindex = pindexBest;
958 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
959 pblockindex = pblockindexFBBHLast;
960 while (pblockindex->nHeight > nHeight)
961 pblockindex = pblockindex->pprev;
962 while (pblockindex->nHeight < nHeight)
963 pblockindex = pblockindex->pnext;
964 pblockindexFBBHLast = pblockindex;
968 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
970 if (!fReadTransactions)
972 *this = pindex->GetBlockHeader();
975 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
977 if (GetHash() != pindex->GetBlockHash())
978 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
982 uint256 static GetOrphanRoot(const CBlock* pblock)
984 // Work back to the first block in the orphan chain
985 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
986 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
987 return pblock->GetHash();
990 // ppcoin: find block wanted by given orphan block
991 uint256 WantedByOrphan(const CBlock* pblockOrphan)
993 // Work back to the first block in the orphan chain
994 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
995 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
996 return pblockOrphan->hashPrevBlock;
999 // select stake target limit according to hard-coded conditions
1000 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1002 if(fTestNet) // separate proof of stake target limit for testnet
1003 return bnProofOfStakeLimit;
1004 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1005 return bnProofOfStakeLimit;
1006 if(nHeight + 1 > 15000) // 24 bits since block 15000
1007 return bnProofOfStakeLegacyLimit;
1008 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1009 return bnProofOfStakeHardLimit;
1011 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1014 // miner's coin base reward based on nBits
1015 int64 GetProofOfWorkReward(unsigned int nBits, int64 nFees)
1017 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1020 bnTarget.SetCompact(nBits);
1021 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1022 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1024 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1025 // A reasonably continuous curve is used to avoid shock to market
1026 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1028 // Human readable form:
1030 // nSubsidy = 100 / (diff ^ 1/6)
1031 CBigNum bnLowerBound = CENT;
1032 CBigNum bnUpperBound = bnSubsidyLimit;
1033 while (bnLowerBound + CENT <= bnUpperBound)
1035 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1036 if (fDebug && GetBoolArg("-printcreation"))
1037 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1038 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1039 bnUpperBound = bnMidValue;
1041 bnLowerBound = bnMidValue;
1044 int64 nSubsidy = bnUpperBound.getuint64();
1046 nSubsidy = (nSubsidy / CENT) * CENT;
1047 if (fDebug && GetBoolArg("-printcreation"))
1048 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1050 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1053 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1054 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
1056 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1058 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1060 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1062 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1064 bnTarget.SetCompact(nBits);
1065 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1066 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1068 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1070 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1071 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1072 bnMidPart, bnRewardPart;
1074 while (bnLowerBound + CENT <= bnUpperBound)
1076 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1077 if (fDebug && GetBoolArg("-printcreation"))
1078 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1080 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1083 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1085 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1087 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1090 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1091 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1096 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1098 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1100 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1103 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1104 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1107 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1108 bnUpperBound = bnMidValue;
1110 bnLowerBound = bnMidValue;
1113 nRewardCoinYear = bnUpperBound.getuint64();
1114 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1118 // Old creation amount per coin-year, 5% fixed stake mint rate
1119 nRewardCoinYear = 5 * CENT;
1123 return nRewardCoinYear;
1125 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1127 // Set reasonable reward limit for large inputs since 20 Oct 2013
1129 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1130 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1132 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1133 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1135 nSubsidy = min(nSubsidy, nSubsidyLimit);
1138 if (fDebug && GetBoolArg("-printcreation"))
1139 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1143 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1145 // get proof of work blocks max spacing according to hard-coded conditions
1146 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1148 if(nTime > TARGETS_SWITCH_TIME)
1149 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1152 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1154 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1158 // maximum nBits value could possible be required nTime after
1160 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1163 bnResult.SetCompact(nBase);
1165 while (nTime > 0 && bnResult < bnTargetLimit)
1167 // Maximum 200% adjustment per day...
1169 nTime -= 24 * 60 * 60;
1171 if (bnResult > bnTargetLimit)
1172 bnResult = bnTargetLimit;
1173 return bnResult.GetCompact();
1177 // minimum amount of work that could possibly be required nTime after
1178 // minimum proof-of-work required was nBase
1180 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1182 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1186 // minimum amount of stake that could possibly be required nTime after
1187 // minimum proof-of-stake required was nBase
1189 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1191 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1195 // ppcoin: find last block index up to pindex
1196 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1198 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1199 pindex = pindex->pprev;
1203 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1205 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1207 if (pindexLast == NULL)
1208 return bnTargetLimit.GetCompact(); // genesis block
1210 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1211 if (pindexPrev->pprev == NULL)
1212 return bnTargetLimit.GetCompact(); // first block
1213 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1214 if (pindexPrevPrev->pprev == NULL)
1215 return bnTargetLimit.GetCompact(); // second block
1217 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1219 // ppcoin: target change every block
1220 // ppcoin: retarget with exponential moving toward target spacing
1222 bnNew.SetCompact(pindexPrev->nBits);
1223 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1224 int64 nInterval = nTargetTimespan / nTargetSpacing;
1225 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1226 bnNew /= ((nInterval + 1) * nTargetSpacing);
1228 if (bnNew > bnTargetLimit)
1229 bnNew = bnTargetLimit;
1231 return bnNew.GetCompact();
1234 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1237 bnTarget.SetCompact(nBits);
1240 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1241 return error("CheckProofOfWork() : nBits below minimum work");
1243 // Check proof of work matches claimed amount
1244 if (hash > bnTarget.getuint256())
1245 return error("CheckProofOfWork() : hash doesn't match nBits");
1250 // Return maximum amount of blocks that other nodes claim to have
1251 int GetNumBlocksOfPeers()
1253 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1256 bool IsInitialBlockDownload()
1258 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1260 static int64 nLastUpdate;
1261 static CBlockIndex* pindexLastBest;
1262 if (pindexBest != pindexLastBest)
1264 pindexLastBest = pindexBest;
1265 nLastUpdate = GetTime();
1267 return (GetTime() - nLastUpdate < 10 &&
1268 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1271 void static InvalidChainFound(CBlockIndex* pindexNew)
1273 if (pindexNew->nChainTrust > nBestInvalidTrust)
1275 nBestInvalidTrust = pindexNew->nChainTrust;
1276 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1277 uiInterface.NotifyBlocksChanged();
1280 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1281 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1283 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1284 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1285 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1286 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1287 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1288 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1289 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1290 nBestBlockTrust.Get64(),
1291 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1295 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1297 nTime = max(GetBlockTime(), GetAdjustedTime());
1310 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1312 // Relinquish previous transactions' spent pointers
1315 BOOST_FOREACH(const CTxIn& txin, vin)
1317 COutPoint prevout = txin.prevout;
1319 // Get prev txindex from disk
1321 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1322 return error("DisconnectInputs() : ReadTxIndex failed");
1324 if (prevout.n >= txindex.vSpent.size())
1325 return error("DisconnectInputs() : prevout.n out of range");
1327 // Mark outpoint as not spent
1328 txindex.vSpent[prevout.n].SetNull();
1331 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1332 return error("DisconnectInputs() : UpdateTxIndex failed");
1336 // Remove transaction from index
1337 // This can fail if a duplicate of this transaction was in a chain that got
1338 // reorganized away. This is only possible if this transaction was completely
1339 // spent, so erasing it would be a no-op anyway.
1340 txdb.EraseTxIndex(*this);
1346 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1347 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1349 // FetchInputs can return false either because we just haven't seen some inputs
1350 // (in which case the transaction should be stored as an orphan)
1351 // or because the transaction is malformed (in which case the transaction should
1352 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1356 return true; // Coinbase transactions have no inputs to fetch.
1358 for (unsigned int i = 0; i < vin.size(); i++)
1360 COutPoint prevout = vin[i].prevout;
1361 if (inputsRet.count(prevout.hash))
1362 continue; // Got it already
1365 CTxIndex& txindex = inputsRet[prevout.hash].first;
1367 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1369 // Get txindex from current proposed changes
1370 txindex = mapTestPool.find(prevout.hash)->second;
1374 // Read txindex from txdb
1375 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1377 if (!fFound && (fBlock || fMiner))
1378 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());
1381 CTransaction& txPrev = inputsRet[prevout.hash].second;
1382 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1384 // Get prev tx from single transactions in memory
1387 if (!mempool.exists(prevout.hash))
1388 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());
1389 txPrev = mempool.lookup(prevout.hash);
1392 txindex.vSpent.resize(txPrev.vout.size());
1396 // Get prev tx from disk
1397 if (!txPrev.ReadFromDisk(txindex.pos))
1398 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1402 // Make sure all prevout.n indexes are valid:
1403 for (unsigned int i = 0; i < vin.size(); i++)
1405 const COutPoint prevout = vin[i].prevout;
1406 assert(inputsRet.count(prevout.hash) != 0);
1407 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1408 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1409 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1411 // Revisit this if/when transaction replacement is implemented and allows
1414 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()));
1421 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1423 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1424 if (mi == inputs.end())
1425 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1427 const CTransaction& txPrev = (mi->second).second;
1428 if (input.prevout.n >= txPrev.vout.size())
1429 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1431 return txPrev.vout[input.prevout.n];
1434 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1440 for (unsigned int i = 0; i < vin.size(); i++)
1442 nResult += GetOutputFor(vin[i], inputs).nValue;
1448 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1453 unsigned int nSigOps = 0;
1454 for (unsigned int i = 0; i < vin.size(); i++)
1456 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1457 if (prevout.scriptPubKey.IsPayToScriptHash())
1458 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1463 bool CScriptCheck::operator()() const {
1464 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1465 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1466 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1470 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1472 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1475 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1476 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1478 // Take over previous transactions' spent pointers
1479 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1480 // fMiner is true when called from the internal bitcoin miner
1481 // ... both are false when called from CTransaction::AcceptToMemoryPool
1487 for (unsigned int i = 0; i < vin.size(); i++)
1489 COutPoint prevout = vin[i].prevout;
1490 assert(inputs.count(prevout.hash) > 0);
1491 CTxIndex& txindex = inputs[prevout.hash].first;
1492 CTransaction& txPrev = inputs[prevout.hash].second;
1494 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1495 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()));
1497 // If prev is coinbase or coinstake, check that it's matured
1498 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1499 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1500 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1501 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1503 // ppcoin: check transaction timestamp
1504 if (txPrev.nTime > nTime)
1505 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1507 // Check for negative or overflow input values
1508 nValueIn += txPrev.vout[prevout.n].nValue;
1509 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1510 return DoS(100, error("ConnectInputs() : txin values out of range"));
1515 pvChecks->reserve(vin.size());
1517 // The first loop above does all the inexpensive checks.
1518 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1519 // Helps prevent CPU exhaustion attacks.
1520 for (unsigned int i = 0; i < vin.size(); i++)
1522 COutPoint prevout = vin[i].prevout;
1523 assert(inputs.count(prevout.hash) > 0);
1524 CTxIndex& txindex = inputs[prevout.hash].first;
1525 CTransaction& txPrev = inputs[prevout.hash].second;
1527 // Check for conflicts (double-spend)
1528 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1529 // for an attacker to attempt to split the network.
1530 if (!txindex.vSpent[prevout.n].IsNull())
1531 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());
1533 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1534 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1535 // still computed and checked, and any change will be caught at the next checkpoint.
1539 CScriptCheck check(txPrev, *this, i, flags, 0);
1542 pvChecks->push_back(CScriptCheck());
1543 check.swap(pvChecks->back());
1547 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS)
1549 CScriptCheck check(txPrev, *this, i, flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, 0);
1551 return error("ConnectInputs() : %s STANDARD_NOT_MANDATORY_VERIFY_FLAGS VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1554 return DoS(100,error("ConnectInputs() : %s STANDARD_MANDATORY_VERIFY_FLAGS VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1558 if (!VerifySignature(txPrev, *this, i, flags, 0))
1560 if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS)
1562 if (VerifySignature(txPrev, *this, i, flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, 0))
1563 return error("ConnectInputs() : %s STANDARD_NOT_MANDATORY_VERIFY_FLAGS VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1565 return DoS(100,error("ConnectInputs() : %s STANDARD_MANDATORY_VERIFY_FLAGS VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1570 // Mark outpoints as spent
1571 txindex.vSpent[prevout.n] = posThisTx;
1574 if (fBlock || fMiner)
1576 mapTestPool[prevout.hash] = txindex;
1582 // ppcoin: coin stake tx earns reward instead of paying fee
1584 if (!GetCoinAge(txdb, nCoinAge))
1585 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1587 unsigned int nTxSize = (nTime > VALIDATION_SWITCH_TIME || fTestNet) ? GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION) : 0;
1589 int64 nReward = GetValueOut() - nValueIn;
1590 int64 nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1592 if (nReward > nCalculatedReward)
1593 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nReward, nCalculatedReward));
1597 if (nValueIn < GetValueOut())
1598 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1600 // Tally transaction fees
1601 int64 nTxFee = nValueIn - GetValueOut();
1603 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1606 if (!MoneyRange(nFees))
1607 return DoS(100, error("ConnectInputs() : nFees out of range"));
1615 bool CTransaction::ClientConnectInputs()
1620 // Take over previous transactions' spent pointers
1624 for (unsigned int i = 0; i < vin.size(); i++)
1626 // Get prev tx from single transactions in memory
1627 COutPoint prevout = vin[i].prevout;
1628 if (!mempool.exists(prevout.hash))
1630 CTransaction& txPrev = mempool.lookup(prevout.hash);
1632 if (prevout.n >= txPrev.vout.size())
1636 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1637 return error("ClientConnectInputs() : VerifySignature failed");
1639 ///// this is redundant with the mempool.mapNextTx stuff,
1640 ///// not sure which I want to get rid of
1641 ///// this has to go away now that posNext is gone
1642 // // Check for conflicts
1643 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1644 // return error("ConnectInputs() : prev tx already used");
1646 // // Flag outpoints as used
1647 // txPrev.vout[prevout.n].posNext = posThisTx;
1649 nValueIn += txPrev.vout[prevout.n].nValue;
1651 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1652 return error("ClientConnectInputs() : txin values out of range");
1654 if (GetValueOut() > nValueIn)
1664 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1666 // Disconnect in reverse order
1667 for (int i = vtx.size()-1; i >= 0; i--)
1668 if (!vtx[i].DisconnectInputs(txdb))
1671 // Update block index on disk without changing it in memory.
1672 // The memory index structure will be changed after the db commits.
1675 CDiskBlockIndex blockindexPrev(pindex->pprev);
1676 blockindexPrev.hashNext = 0;
1677 if (!txdb.WriteBlockIndex(blockindexPrev))
1678 return error("DisconnectBlock() : WriteBlockIndex failed");
1681 // ppcoin: clean up wallet after disconnecting coinstake
1682 BOOST_FOREACH(CTransaction& tx, vtx)
1683 SyncWithWallets(tx, this, false, false);
1688 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1690 void ThreadScriptCheck(void*) {
1691 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1692 RenameThread("novacoin-scriptch");
1693 scriptcheckqueue.Thread();
1694 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1697 void ThreadScriptCheckQuit() {
1698 scriptcheckqueue.Quit();
1701 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1703 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1704 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1707 bool fProtocol048 = fTestNet || VALIDATION_SWITCH_TIME < nTime;
1709 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1710 // unless those are already completely spent.
1711 // If such overwrites are allowed, coinbases and transactions depending upon those
1712 // can be duplicated to remove the ability to spend the first instance -- even after
1713 // being sent to another address.
1714 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1715 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1716 // already refuses previously-known transaction ids entirely.
1717 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1718 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1719 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1720 // initial block download.
1721 bool fEnforceBIP30 = true; // Always active in NovaCoin
1722 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1724 //// issue here: it doesn't know the version
1725 unsigned int nTxPos;
1727 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1728 // 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
1731 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1733 map<uint256, CTxIndex> mapQueuedChanges;
1734 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1738 int64 nValueOut = 0;
1739 unsigned int nSigOps = 0;
1740 BOOST_FOREACH(CTransaction& tx, vtx)
1742 uint256 hashTx = tx.GetHash();
1744 if (fEnforceBIP30) {
1745 CTxIndex txindexOld;
1746 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1747 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1753 nSigOps += tx.GetLegacySigOpCount();
1754 if (nSigOps > MAX_BLOCK_SIGOPS)
1755 return DoS(100, error("ConnectBlock() : too many sigops"));
1757 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1759 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1761 MapPrevTx mapInputs;
1762 if (tx.IsCoinBase())
1763 nValueOut += tx.GetValueOut();
1767 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1770 // Add in sigops done by pay-to-script-hash inputs;
1771 // this is to prevent a "rogue miner" from creating
1772 // an incredibly-expensive-to-validate block.
1773 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1774 if (nSigOps > MAX_BLOCK_SIGOPS)
1775 return DoS(100, error("ConnectBlock() : too many sigops"));
1777 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1778 int64 nTxValueOut = tx.GetValueOut();
1779 nValueIn += nTxValueIn;
1780 nValueOut += nTxValueOut;
1781 if (!tx.IsCoinStake())
1782 nFees += nTxValueIn - nTxValueOut;
1784 std::vector<CScriptCheck> vChecks;
1785 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, nScriptCheckThreads ? &vChecks : NULL))
1787 control.Add(vChecks);
1790 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1793 if (!control.Wait())
1794 return DoS(100, false);
1796 if (IsProofOfWork())
1798 int64 nBlockReward = GetProofOfWorkReward(nBits, fProtocol048 ? nFees : 0);
1800 // Check coinbase reward
1801 if (vtx[0].GetValueOut() > nBlockReward)
1802 return error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
1803 vtx[0].GetValueOut(),
1807 // track money supply and mint amount info
1808 pindex->nMint = nValueOut - nValueIn + nFees;
1809 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1810 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1811 return error("Connect() : WriteBlockIndex for pindex failed");
1813 // fees are not collected by proof-of-stake miners
1814 // fees are destroyed to compensate the entire network
1815 if (fProtocol048 && fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1816 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1821 // Write queued txindex changes
1822 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1824 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1825 return error("ConnectBlock() : UpdateTxIndex failed");
1828 // Update block index on disk without changing it in memory.
1829 // The memory index structure will be changed after the db commits.
1832 CDiskBlockIndex blockindexPrev(pindex->pprev);
1833 blockindexPrev.hashNext = pindex->GetBlockHash();
1834 if (!txdb.WriteBlockIndex(blockindexPrev))
1835 return error("ConnectBlock() : WriteBlockIndex failed");
1838 // Watch for transactions paying to me
1839 BOOST_FOREACH(CTransaction& tx, vtx)
1840 SyncWithWallets(tx, this, true);
1845 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1847 printf("REORGANIZE\n");
1850 CBlockIndex* pfork = pindexBest;
1851 CBlockIndex* plonger = pindexNew;
1852 while (pfork != plonger)
1854 while (plonger->nHeight > pfork->nHeight)
1855 if (!(plonger = plonger->pprev))
1856 return error("Reorganize() : plonger->pprev is null");
1857 if (pfork == plonger)
1859 if (!(pfork = pfork->pprev))
1860 return error("Reorganize() : pfork->pprev is null");
1863 // List of what to disconnect
1864 vector<CBlockIndex*> vDisconnect;
1865 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1866 vDisconnect.push_back(pindex);
1868 // List of what to connect
1869 vector<CBlockIndex*> vConnect;
1870 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1871 vConnect.push_back(pindex);
1872 reverse(vConnect.begin(), vConnect.end());
1874 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());
1875 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());
1877 // Disconnect shorter branch
1878 vector<CTransaction> vResurrect;
1879 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1882 if (!block.ReadFromDisk(pindex))
1883 return error("Reorganize() : ReadFromDisk for disconnect failed");
1884 if (!block.DisconnectBlock(txdb, pindex))
1885 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1887 // Queue memory transactions to resurrect
1888 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1889 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1890 vResurrect.push_back(tx);
1893 // Connect longer branch
1894 vector<CTransaction> vDelete;
1895 for (unsigned int i = 0; i < vConnect.size(); i++)
1897 CBlockIndex* pindex = vConnect[i];
1899 if (!block.ReadFromDisk(pindex))
1900 return error("Reorganize() : ReadFromDisk for connect failed");
1901 if (!block.ConnectBlock(txdb, pindex))
1904 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1907 // Queue memory transactions to delete
1908 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1909 vDelete.push_back(tx);
1911 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1912 return error("Reorganize() : WriteHashBestChain failed");
1914 // Make sure it's successfully written to disk before changing memory structure
1915 if (!txdb.TxnCommit())
1916 return error("Reorganize() : TxnCommit failed");
1918 // Disconnect shorter branch
1919 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1921 pindex->pprev->pnext = NULL;
1923 // Connect longer branch
1924 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1926 pindex->pprev->pnext = pindex;
1928 // Resurrect memory transactions that were in the disconnected branch
1929 BOOST_FOREACH(CTransaction& tx, vResurrect)
1930 tx.AcceptToMemoryPool(txdb, false);
1932 // Delete redundant memory transactions that are in the connected branch
1933 BOOST_FOREACH(CTransaction& tx, vDelete)
1936 printf("REORGANIZE: done\n");
1942 // Called from inside SetBestChain: attaches a block to the new best chain being built
1943 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1945 uint256 hash = GetHash();
1947 // Adding to current best branch
1948 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1951 InvalidChainFound(pindexNew);
1954 if (!txdb.TxnCommit())
1955 return error("SetBestChain() : TxnCommit failed");
1957 // Add to current best branch
1958 pindexNew->pprev->pnext = pindexNew;
1960 // Delete redundant memory transactions
1961 BOOST_FOREACH(CTransaction& tx, vtx)
1967 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1969 uint256 hash = GetHash();
1971 if (!txdb.TxnBegin())
1972 return error("SetBestChain() : TxnBegin failed");
1974 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1976 txdb.WriteHashBestChain(hash);
1977 if (!txdb.TxnCommit())
1978 return error("SetBestChain() : TxnCommit failed");
1979 pindexGenesisBlock = pindexNew;
1981 else if (hashPrevBlock == hashBestChain)
1983 if (!SetBestChainInner(txdb, pindexNew))
1984 return error("SetBestChain() : SetBestChainInner failed");
1988 // the first block in the new chain that will cause it to become the new best chain
1989 CBlockIndex *pindexIntermediate = pindexNew;
1991 // list of blocks that need to be connected afterwards
1992 std::vector<CBlockIndex*> vpindexSecondary;
1994 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1995 // Try to limit how much needs to be done inside
1996 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1998 vpindexSecondary.push_back(pindexIntermediate);
1999 pindexIntermediate = pindexIntermediate->pprev;
2002 if (!vpindexSecondary.empty())
2003 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
2005 // Switch to new best branch
2006 if (!Reorganize(txdb, pindexIntermediate))
2009 InvalidChainFound(pindexNew);
2010 return error("SetBestChain() : Reorganize failed");
2013 // Connect further blocks
2014 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
2017 if (!block.ReadFromDisk(pindex))
2019 printf("SetBestChain() : ReadFromDisk failed\n");
2022 if (!txdb.TxnBegin()) {
2023 printf("SetBestChain() : TxnBegin 2 failed\n");
2026 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
2027 if (!block.SetBestChainInner(txdb, pindex))
2032 // Update best block in wallet (so we can detect restored wallets)
2033 bool fIsInitialDownload = IsInitialBlockDownload();
2034 if (!fIsInitialDownload)
2036 const CBlockLocator locator(pindexNew);
2037 ::SetBestChain(locator);
2041 hashBestChain = hash;
2042 pindexBest = pindexNew;
2043 pblockindexFBBHLast = NULL;
2044 nBestHeight = pindexBest->nHeight;
2045 nBestChainTrust = pindexNew->nChainTrust;
2046 nTimeBestReceived = GetTime();
2047 nTransactionsUpdated++;
2049 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2051 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
2052 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2053 CBigNum(nBestChainTrust).ToString().c_str(),
2054 nBestBlockTrust.Get64(),
2055 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2057 // Check the version of the last 100 blocks to see if we need to upgrade:
2058 if (!fIsInitialDownload)
2061 const CBlockIndex* pindex = pindexBest;
2062 for (int i = 0; i < 100 && pindex != NULL; i++)
2064 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2066 pindex = pindex->pprev;
2069 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2070 if (nUpgraded > 100/2)
2071 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2072 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2075 std::string strCmd = GetArg("-blocknotify", "");
2077 if (!fIsInitialDownload && !strCmd.empty())
2079 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
2080 boost::thread t(runCommand, strCmd); // thread runs free
2086 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2087 // Only those coins meeting minimum age requirement counts. As those
2088 // transactions not in main chain are not currently indexed so we
2089 // might not find out about their coin age. Older transactions are
2090 // guaranteed to be in main chain by sync-checkpoint. This rule is
2091 // introduced to help nodes establish a consistent view of the coin
2092 // age (trust score) of competing branches.
2093 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
2095 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2101 BOOST_FOREACH(const CTxIn& txin, vin)
2103 // First try finding the previous transaction in database
2104 CTransaction txPrev;
2106 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2107 continue; // previous transaction not in main chain
2108 if (nTime < txPrev.nTime)
2109 return false; // Transaction timestamp violation
2111 // Read block header
2113 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2114 return false; // unable to read block of previous transaction
2115 if (block.GetBlockTime() + nStakeMinAge > nTime)
2116 continue; // only count coins meeting min age requirement
2118 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2119 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2121 if (fDebug && GetBoolArg("-printcoinage"))
2122 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2125 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
2126 if (fDebug && GetBoolArg("-printcoinage"))
2127 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2128 nCoinAge = bnCoinDay.getuint64();
2132 // ppcoin: total coin age spent in block, in the unit of coin-days.
2133 bool CBlock::GetCoinAge(uint64& nCoinAge) const
2138 BOOST_FOREACH(const CTransaction& tx, vtx)
2141 if (tx.GetCoinAge(txdb, nTxCoinAge))
2142 nCoinAge += nTxCoinAge;
2147 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2149 if (fDebug && GetBoolArg("-printcoinage"))
2150 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
2154 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2156 // Check for duplicate
2157 uint256 hash = GetHash();
2158 if (mapBlockIndex.count(hash))
2159 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2161 // Construct new block index object
2162 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
2164 return error("AddToBlockIndex() : new CBlockIndex failed");
2165 pindexNew->phashBlock = &hash;
2166 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2167 if (miPrev != mapBlockIndex.end())
2169 pindexNew->pprev = (*miPrev).second;
2170 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2173 // ppcoin: compute chain trust score
2174 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2176 // ppcoin: compute stake entropy bit for stake modifier
2177 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2178 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2180 // ppcoin: record proof-of-stake hash value
2181 if (pindexNew->IsProofOfStake())
2183 if (!mapProofOfStake.count(hash))
2184 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2185 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2188 // ppcoin: compute stake modifier
2189 uint64 nStakeModifier = 0;
2190 bool fGeneratedStakeModifier = false;
2191 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2192 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2193 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2194 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2195 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2196 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2198 // Add to mapBlockIndex
2199 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2200 if (pindexNew->IsProofOfStake())
2201 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2202 pindexNew->phashBlock = &((*mi).first);
2204 // Write to disk block index
2206 if (!txdb.TxnBegin())
2208 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2209 if (!txdb.TxnCommit())
2213 if (pindexNew->nChainTrust > nBestChainTrust)
2214 if (!SetBestChain(txdb, pindexNew))
2217 if (pindexNew == pindexBest)
2219 // Notify UI to display prev block's coinbase if it was ours
2220 static uint256 hashPrevBestCoinBase;
2221 UpdatedTransaction(hashPrevBestCoinBase);
2222 hashPrevBestCoinBase = vtx[0].GetHash();
2225 uiInterface.NotifyBlocksChanged();
2232 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2234 // These are checks that are independent of context
2235 // that can be verified before saving an orphan block.
2238 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2239 return DoS(100, error("CheckBlock() : size limits failed"));
2241 bool fProtocol048 = fTestNet || VALIDATION_SWITCH_TIME < nTime;
2243 // Check proof of work matches claimed amount
2244 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2245 return DoS(50, error("CheckBlock() : proof of work failed"));
2248 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2249 return error("CheckBlock() : block timestamp too far in the future");
2251 // First transaction must be coinbase, the rest must not be
2252 if (vtx.empty() || !vtx[0].IsCoinBase())
2253 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2257 // Check coinbase timestamp
2258 if (GetBlockTime() < (int64)vtx[0].nTime)
2259 return DoS(100, error("CheckBlock() : coinbase timestamp violation"));
2263 // Check coinbase timestamp
2264 if (GetBlockTime() < PastDrift((int64)vtx[0].nTime))
2265 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2268 for (unsigned int i = 1; i < vtx.size(); i++)
2270 if (vtx[i].IsCoinBase())
2271 return DoS(100, error("CheckBlock() : more than one coinbase"));
2273 // Check transaction timestamp
2274 if (GetBlockTime() < (int64)vtx[i].nTime)
2275 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2278 if (IsProofOfStake())
2283 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2286 // Coinbase output should be empty if proof-of-stake block
2287 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2288 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2290 // Second transaction must be coinstake, the rest must not be
2291 if (vtx.empty() || !vtx[1].IsCoinStake())
2292 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2293 for (unsigned int i = 2; i < vtx.size(); i++)
2294 if (vtx[i].IsCoinStake())
2295 return DoS(100, error("CheckBlock() : more than one coinstake"));
2297 // Check coinstake timestamp
2298 if (GetBlockTime() != (int64)vtx[1].nTime)
2299 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2301 // NovaCoin: check proof-of-stake block signature
2302 if (fCheckSig && !CheckBlockSignature(true))
2303 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2307 // Should we check proof-of-work block signature or not?
2309 // * Always skip on TestNet
2310 // * Perform checking for the first 9689 blocks
2311 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2313 if(!fTestNet && fCheckSig)
2315 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2317 // NovaCoin: check proof-of-work block signature
2318 if (checkEntropySig && !CheckBlockSignature(false))
2319 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2323 // Check transactions
2324 BOOST_FOREACH(const CTransaction& tx, vtx)
2326 if (!tx.CheckTransaction())
2327 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2330 // Check for duplicate txids. This is caught by ConnectInputs(),
2331 // but catching it earlier avoids a potential DoS attack:
2332 set<uint256> uniqueTx;
2333 BOOST_FOREACH(const CTransaction& tx, vtx)
2335 uniqueTx.insert(tx.GetHash());
2337 if (uniqueTx.size() != vtx.size())
2338 return DoS(100, error("CheckBlock() : duplicate transaction"));
2340 unsigned int nSigOps = 0;
2341 BOOST_FOREACH(const CTransaction& tx, vtx)
2343 nSigOps += tx.GetLegacySigOpCount();
2345 if (nSigOps > MAX_BLOCK_SIGOPS)
2346 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2348 // Check merkle root
2349 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2350 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2356 bool CBlock::AcceptBlock()
2358 // Check for duplicate
2359 uint256 hash = GetHash();
2360 if (mapBlockIndex.count(hash))
2361 return error("AcceptBlock() : block already in mapBlockIndex");
2363 // Get prev block index
2364 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2365 if (mi == mapBlockIndex.end())
2366 return DoS(10, error("AcceptBlock() : prev block not found"));
2367 CBlockIndex* pindexPrev = (*mi).second;
2368 int nHeight = pindexPrev->nHeight+1;
2370 // Check proof-of-work or proof-of-stake
2371 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2372 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2374 // Check timestamp against prev
2375 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2376 return error("AcceptBlock() : block's timestamp is too early");
2378 // Check that all transactions are finalized
2379 BOOST_FOREACH(const CTransaction& tx, vtx)
2380 if (!tx.IsFinal(nHeight, GetBlockTime()))
2381 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2383 // Check that the block chain matches the known block chain up to a checkpoint
2384 if (!Checkpoints::CheckHardened(nHeight, hash))
2385 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2387 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2389 // Check that the block satisfies synchronized checkpoint
2390 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2391 return error("AcceptBlock() : rejected by synchronized checkpoint");
2393 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2394 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2396 // Enforce rule that the coinbase starts with serialized block height
2397 CScript expect = CScript() << nHeight;
2398 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2399 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2400 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2402 // Write block to history file
2403 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2404 return error("AcceptBlock() : out of disk space");
2405 unsigned int nFile = -1;
2406 unsigned int nBlockPos = 0;
2407 if (!WriteToDisk(nFile, nBlockPos))
2408 return error("AcceptBlock() : WriteToDisk failed");
2409 if (!AddToBlockIndex(nFile, nBlockPos))
2410 return error("AcceptBlock() : AddToBlockIndex failed");
2412 // Relay inventory, but don't relay old inventory during initial block download
2413 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2414 if (hashBestChain == hash)
2417 BOOST_FOREACH(CNode* pnode, vNodes)
2418 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2419 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2422 // ppcoin: check pending sync-checkpoint
2423 Checkpoints::AcceptPendingSyncCheckpoint();
2428 uint256 CBlockIndex::GetBlockTrust() const
2431 bnTarget.SetCompact(nBits);
2437 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2438 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2442 // Calculate work amount for block
2443 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2445 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2446 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2448 // Return nPoWTrust for the first 12 blocks
2449 if (pprev == NULL || pprev->nHeight < 12)
2452 const CBlockIndex* currentIndex = pprev;
2454 if(IsProofOfStake())
2456 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2458 // Return 1/3 of score if parent block is not the PoW block
2459 if (!pprev->IsProofOfWork())
2460 return (bnNewTrust / 3).getuint256();
2464 // Check last 12 blocks type
2465 while (pprev->nHeight - currentIndex->nHeight < 12)
2467 if (currentIndex->IsProofOfWork())
2469 currentIndex = currentIndex->pprev;
2472 // Return 1/3 of score if less than 3 PoW blocks found
2474 return (bnNewTrust / 3).getuint256();
2476 return bnNewTrust.getuint256();
2480 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2482 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2483 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2484 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2488 // Check last 12 blocks type
2489 while (pprev->nHeight - currentIndex->nHeight < 12)
2491 if (currentIndex->IsProofOfStake())
2493 currentIndex = currentIndex->pprev;
2496 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2498 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2500 bnTarget.SetCompact(pprev->nBits);
2505 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2507 // Return nPoWTrust + full trust score for previous block nBits
2508 return nPoWTrust + bnNewTrust.getuint256();
2512 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2514 unsigned int nFound = 0;
2515 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2517 if (pstart->nVersion >= minVersion)
2519 pstart = pstart->pprev;
2521 return (nFound >= nRequired);
2524 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2526 // Check for duplicate
2527 uint256 hash = pblock->GetHash();
2528 if (mapBlockIndex.count(hash))
2529 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2530 if (mapOrphanBlocks.count(hash))
2531 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2533 // ppcoin: check proof-of-stake
2534 // Limited duplicity on stake: prevents block flood attack
2535 // Duplicate stake allowed only when there is orphan child block
2536 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2537 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());
2539 // Preliminary checks
2540 if (!pblock->CheckBlock())
2541 return error("ProcessBlock() : CheckBlock FAILED");
2543 // ppcoin: verify hash target and signature of coinstake tx
2544 if (pblock->IsProofOfStake())
2546 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2547 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2549 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2550 return false; // do not error here as we expect this during initial block download
2552 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2553 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2556 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2557 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2559 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2560 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2562 bnNewBlock.SetCompact(pblock->nBits);
2565 if (pblock->IsProofOfStake())
2566 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2568 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2570 if (bnNewBlock > bnRequired)
2573 pfrom->Misbehaving(100);
2574 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2578 // ppcoin: ask for pending sync-checkpoint if any
2579 if (!IsInitialBlockDownload())
2580 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2582 // If don't already have its previous block, shunt it off to holding area until we get it
2583 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2585 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2586 CBlock* pblock2 = new CBlock(*pblock);
2587 // ppcoin: check proof-of-stake
2588 if (pblock2->IsProofOfStake())
2590 // Limited duplicity on stake: prevents block flood attack
2591 // Duplicate stake allowed only when there is orphan child block
2592 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2593 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());
2595 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2597 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2598 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2600 // Ask this guy to fill in what we're missing
2603 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2604 // ppcoin: getblocks may not obtain the ancestor block rejected
2605 // earlier by duplicate-stake check so we ask for it again directly
2606 if (!IsInitialBlockDownload())
2607 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2613 if (!pblock->AcceptBlock())
2614 return error("ProcessBlock() : AcceptBlock FAILED");
2616 // Recursively process any orphan blocks that depended on this one
2617 vector<uint256> vWorkQueue;
2618 vWorkQueue.push_back(hash);
2619 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2621 uint256 hashPrev = vWorkQueue[i];
2622 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2623 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2626 CBlock* pblockOrphan = (*mi).second;
2627 if (pblockOrphan->AcceptBlock())
2628 vWorkQueue.push_back(pblockOrphan->GetHash());
2629 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2630 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2631 delete pblockOrphan;
2633 mapOrphanBlocksByPrev.erase(hashPrev);
2636 printf("ProcessBlock: ACCEPTED\n");
2638 // ppcoin: if responsible for sync-checkpoint send it
2639 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2640 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2645 // novacoin: attempt to generate suitable proof-of-stake
2646 bool CBlock::SignBlock(CWallet& wallet)
2648 // if we are trying to sign
2649 // something except proof-of-stake block template
2650 if (!vtx[0].vout[0].IsEmpty())
2653 // if we are trying to sign
2654 // a complete proof-of-stake block
2655 if (IsProofOfStake())
2658 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2661 CTransaction txCoinStake;
2662 int64 nSearchTime = txCoinStake.nTime; // search to current time
2664 if (nSearchTime > nLastCoinStakeSearchTime)
2666 if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2668 if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2670 // make sure coinstake would meet timestamp protocol
2671 // as it would be the same as the block timestamp
2672 vtx[0].nTime = nTime = txCoinStake.nTime;
2673 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2674 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2676 // we have to make sure that we have no future timestamps in
2677 // our transactions set
2678 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2679 if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2681 vtx.insert(vtx.begin() + 1, txCoinStake);
2682 hashMerkleRoot = BuildMerkleTree();
2684 // append a signature to our block
2685 return key.Sign(GetHash(), vchBlockSig);
2688 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2689 nLastCoinStakeSearchTime = nSearchTime;
2695 // ppcoin: check block signature
2696 bool CBlock::CheckBlockSignature(bool fProofOfStake) const
2698 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2699 return vchBlockSig.empty();
2701 vector<valtype> vSolutions;
2702 txnouttype whichType;
2706 const CTxOut& txout = vtx[1].vout[1];
2708 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2710 if (whichType == TX_PUBKEY)
2712 valtype& vchPubKey = vSolutions[0];
2714 if (!key.SetPubKey(vchPubKey))
2716 if (vchBlockSig.empty())
2718 return key.Verify(GetHash(), vchBlockSig);
2723 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2725 const CTxOut& txout = vtx[0].vout[i];
2727 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2730 if (whichType == TX_PUBKEY)
2733 valtype& vchPubKey = vSolutions[0];
2735 if (!key.SetPubKey(vchPubKey))
2737 if (vchBlockSig.empty())
2739 if(!key.Verify(GetHash(), vchBlockSig))
2749 bool CheckDiskSpace(uint64 nAdditionalBytes)
2751 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2753 // Check for nMinDiskSpace bytes (currently 50MB)
2754 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2757 string strMessage = _("Warning: Disk space is low!");
2758 strMiscWarning = strMessage;
2759 printf("*** %s\n", strMessage.c_str());
2760 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2767 static filesystem::path BlockFilePath(unsigned int nFile)
2769 string strBlockFn = strprintf("blk%04u.dat", nFile);
2770 return GetDataDir() / strBlockFn;
2773 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2775 if ((nFile < 1) || (nFile == (unsigned int) -1))
2777 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2780 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2782 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2791 static unsigned int nCurrentBlockFile = 1;
2793 FILE* AppendBlockFile(unsigned int& nFileRet)
2798 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2801 if (fseek(file, 0, SEEK_END) != 0)
2803 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2804 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2806 nFileRet = nCurrentBlockFile;
2810 nCurrentBlockFile++;
2814 bool LoadBlockIndex(bool fAllowNew)
2816 CBigNum bnTrustedModulus;
2820 pchMessageStart[0] = 0xcd;
2821 pchMessageStart[1] = 0xf2;
2822 pchMessageStart[2] = 0xc0;
2823 pchMessageStart[3] = 0xef;
2825 bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
2826 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2827 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2828 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2829 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2830 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2834 bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
2837 // Set up the Zerocoin Params object
2838 ZCParams = new libzerocoin::Params(bnTrustedModulus);
2844 if (!txdb.LoadBlockIndex())
2848 // Init with genesis block
2850 if (mapBlockIndex.empty())
2859 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2860 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2861 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2863 // vMerkleTree: 4cb33b3b6a
2867 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2868 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2869 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2871 // vMerkleTree: 4cb33b3b6a
2873 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2875 txNew.nTime = 1360105017;
2876 txNew.vin.resize(1);
2877 txNew.vout.resize(1);
2878 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2879 txNew.vout[0].SetEmpty();
2881 block.vtx.push_back(txNew);
2882 block.hashPrevBlock = 0;
2883 block.hashMerkleRoot = block.BuildMerkleTree();
2885 block.nTime = 1360105017;
2886 block.nBits = bnProofOfWorkLimit.GetCompact();
2887 block.nNonce = !fTestNet ? 1575379 : 46534;
2890 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2892 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2893 assert(block.CheckBlock());
2895 // Start new block file
2897 unsigned int nBlockPos;
2898 if (!block.WriteToDisk(nFile, nBlockPos))
2899 return error("LoadBlockIndex() : writing genesis block to disk failed");
2900 if (!block.AddToBlockIndex(nFile, nBlockPos))
2901 return error("LoadBlockIndex() : genesis block not accepted");
2903 // initialize synchronized checkpoint
2904 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2905 return error("LoadBlockIndex() : failed to init sync checkpoint");
2907 // upgrade time set to zero if txdb initialized
2909 if (!txdb.WriteModifierUpgradeTime(0))
2910 return error("LoadBlockIndex() : failed to init upgrade info");
2911 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2915 string strPubKey = "";
2917 // if checkpoint master key changed must reset sync-checkpoint
2918 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2920 // write checkpoint master key to db
2922 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2923 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2924 if (!txdb.TxnCommit())
2925 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2926 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2927 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2930 // upgrade time set to zero if blocktreedb initialized
2931 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2933 if (nModifierUpgradeTime)
2934 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2936 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2940 nModifierUpgradeTime = GetTime();
2941 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2942 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2943 return error("LoadBlockIndex() : failed to write upgrade info");
2952 void PrintBlockTree()
2954 // pre-compute tree structure
2955 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2956 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2958 CBlockIndex* pindex = (*mi).second;
2959 mapNext[pindex->pprev].push_back(pindex);
2961 //while (rand() % 3 == 0)
2962 // mapNext[pindex->pprev].push_back(pindex);
2965 vector<pair<int, CBlockIndex*> > vStack;
2966 vStack.push_back(make_pair(0, pindexGenesisBlock));
2969 while (!vStack.empty())
2971 int nCol = vStack.back().first;
2972 CBlockIndex* pindex = vStack.back().second;
2975 // print split or gap
2976 if (nCol > nPrevCol)
2978 for (int i = 0; i < nCol-1; i++)
2982 else if (nCol < nPrevCol)
2984 for (int i = 0; i < nCol; i++)
2991 for (int i = 0; i < nCol; i++)
2996 block.ReadFromDisk(pindex);
2997 printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
3001 block.GetHash().ToString().c_str(),
3003 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
3004 FormatMoney(pindex->nMint).c_str(),
3007 PrintWallets(block);
3009 // put the main time-chain first
3010 vector<CBlockIndex*>& vNext = mapNext[pindex];
3011 for (unsigned int i = 0; i < vNext.size(); i++)
3013 if (vNext[i]->pnext)
3015 swap(vNext[0], vNext[i]);
3021 for (unsigned int i = 0; i < vNext.size(); i++)
3022 vStack.push_back(make_pair(nCol+i, vNext[i]));
3026 bool LoadExternalBlockFile(FILE* fileIn)
3028 int64 nStart = GetTimeMillis();
3034 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
3035 unsigned int nPos = 0;
3036 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
3038 unsigned char pchData[65536];
3040 fseek(blkdat, nPos, SEEK_SET);
3041 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
3044 nPos = (unsigned int)-1;
3047 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
3050 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
3052 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
3055 nPos += ((unsigned char*)nFind - pchData) + 1;
3058 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
3059 } while(!fRequestShutdown);
3060 if (nPos == (unsigned int)-1)
3062 fseek(blkdat, nPos, SEEK_SET);
3065 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
3069 if (ProcessBlock(NULL,&block))
3077 catch (std::exception &e) {
3078 printf("%s() : Deserialize or I/O error caught during load\n",
3079 __PRETTY_FUNCTION__);
3082 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
3086 //////////////////////////////////////////////////////////////////////////////
3091 extern map<uint256, CAlert> mapAlerts;
3092 extern CCriticalSection cs_mapAlerts;
3094 string GetWarnings(string strFor)
3097 string strStatusBar;
3100 if (GetBoolArg("-testsafemode"))
3103 // Misc warnings like out of disk space and clock is wrong
3104 if (strMiscWarning != "")
3107 strStatusBar = strMiscWarning;
3110 // if detected unmet upgrade requirement enter safe mode
3111 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3112 if (IsFixedModifierInterval(nModifierUpgradeTime + 60*60*24)) // 1 day margin
3115 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3118 // if detected invalid checkpoint enter safe mode
3119 if (Checkpoints::hashInvalidCheckpoint != 0)
3122 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3128 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3130 const CAlert& alert = item.second;
3131 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3133 nPriority = alert.nPriority;
3134 strStatusBar = alert.strStatusBar;
3135 if (nPriority > 1000)
3136 strRPC = strStatusBar;
3141 if (strFor == "statusbar")
3142 return strStatusBar;
3143 else if (strFor == "rpc")
3145 assert(!"GetWarnings() : invalid parameter");
3156 //////////////////////////////////////////////////////////////////////////////
3162 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3168 bool txInMap = false;
3171 txInMap = (mempool.exists(inv.hash));
3174 mapOrphanTransactions.count(inv.hash) ||
3175 txdb.ContainsTx(inv.hash);
3179 return mapBlockIndex.count(inv.hash) ||
3180 mapOrphanBlocks.count(inv.hash);
3182 // Don't know what it is, just say we already got one
3189 // The message start string is designed to be unlikely to occur in normal data.
3190 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3191 // a large 4-byte int at any alignment.
3192 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3194 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3196 static map<CService, CPubKey> mapReuseKey;
3197 RandAddSeedPerfmon();
3199 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3200 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3202 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3206 if (strCommand == "version")
3208 // Each connection can only send one version message
3209 if (pfrom->nVersion != 0)
3211 pfrom->Misbehaving(1);
3219 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3220 if (pfrom->nVersion < MIN_PROTO_VERSION)
3222 // Since February 20, 2012, the protocol is initiated at version 209,
3223 // and earlier versions are no longer supported
3224 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3225 pfrom->fDisconnect = true;
3229 if (pfrom->nVersion == 10300)
3230 pfrom->nVersion = 300;
3232 vRecv >> addrFrom >> nNonce;
3234 vRecv >> pfrom->strSubVer;
3236 vRecv >> pfrom->nStartingHeight;
3238 if (pfrom->fInbound && addrMe.IsRoutable())
3240 pfrom->addrLocal = addrMe;
3244 // Disconnect if we connected to ourself
3245 if (nNonce == nLocalHostNonce && nNonce > 1)
3247 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3248 pfrom->fDisconnect = true;
3252 if (pfrom->nVersion < 60010)
3254 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3255 pfrom->fDisconnect = true;
3259 // record my external IP reported by peer
3260 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3261 addrSeenByPeer = addrMe;
3263 // Be shy and don't send version until we hear
3264 if (pfrom->fInbound)
3265 pfrom->PushVersion();
3267 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3269 AddTimeData(pfrom->addr, nTime);
3272 pfrom->PushMessage("verack");
3273 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3275 if (!pfrom->fInbound)
3277 // Advertise our address
3278 if (!fNoListen && !IsInitialBlockDownload())
3280 CAddress addr = GetLocalAddress(&pfrom->addr);
3281 if (addr.IsRoutable())
3282 pfrom->PushAddress(addr);
3285 // Get recent addresses
3286 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3288 pfrom->PushMessage("getaddr");
3289 pfrom->fGetAddr = true;
3291 addrman.Good(pfrom->addr);
3293 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3295 addrman.Add(addrFrom, addrFrom);
3296 addrman.Good(addrFrom);
3300 // Ask the first connected node for block updates
3301 static int nAskedForBlocks = 0;
3302 if (!pfrom->fClient && !pfrom->fOneShot &&
3303 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3304 (pfrom->nVersion < NOBLKS_VERSION_START ||
3305 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3306 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3309 pfrom->PushGetBlocks(pindexBest, uint256(0));
3315 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3316 item.second.RelayTo(pfrom);
3319 // Relay sync-checkpoint
3321 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3322 if (!Checkpoints::checkpointMessage.IsNull())
3323 Checkpoints::checkpointMessage.RelayTo(pfrom);
3326 pfrom->fSuccessfullyConnected = true;
3328 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());
3330 cPeerBlockCounts.input(pfrom->nStartingHeight);
3332 // ppcoin: ask for pending sync-checkpoint if any
3333 if (!IsInitialBlockDownload())
3334 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3338 else if (pfrom->nVersion == 0)
3340 // Must have a version message before anything else
3341 pfrom->Misbehaving(1);
3346 else if (strCommand == "verack")
3348 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3352 else if (strCommand == "addr")
3354 vector<CAddress> vAddr;
3357 // Don't want addr from older versions unless seeding
3358 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3360 if (vAddr.size() > 1000)
3362 pfrom->Misbehaving(20);
3363 return error("message addr size() = %"PRIszu"", vAddr.size());
3366 // Store the new addresses
3367 vector<CAddress> vAddrOk;
3368 int64 nNow = GetAdjustedTime();
3369 int64 nSince = nNow - 10 * 60;
3370 BOOST_FOREACH(CAddress& addr, vAddr)
3374 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3375 addr.nTime = nNow - 5 * 24 * 60 * 60;
3376 pfrom->AddAddressKnown(addr);
3377 bool fReachable = IsReachable(addr);
3378 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3380 // Relay to a limited number of other nodes
3383 // Use deterministic randomness to send to the same nodes for 24 hours
3384 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3385 static uint256 hashSalt;
3387 hashSalt = GetRandHash();
3388 uint64 hashAddr = addr.GetHash();
3389 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3390 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3391 multimap<uint256, CNode*> mapMix;
3392 BOOST_FOREACH(CNode* pnode, vNodes)
3394 if (pnode->nVersion < CADDR_TIME_VERSION)
3396 unsigned int nPointer;
3397 memcpy(&nPointer, &pnode, sizeof(nPointer));
3398 uint256 hashKey = hashRand ^ nPointer;
3399 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3400 mapMix.insert(make_pair(hashKey, pnode));
3402 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3403 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3404 ((*mi).second)->PushAddress(addr);
3407 // Do not store addresses outside our network
3409 vAddrOk.push_back(addr);
3411 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3412 if (vAddr.size() < 1000)
3413 pfrom->fGetAddr = false;
3414 if (pfrom->fOneShot)
3415 pfrom->fDisconnect = true;
3418 else if (strCommand == "inv")
3422 if (vInv.size() > MAX_INV_SZ)
3424 pfrom->Misbehaving(20);
3425 return error("message inv size() = %"PRIszu"", vInv.size());
3428 // find last block in inv vector
3429 unsigned int nLastBlock = (unsigned int)(-1);
3430 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3431 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3432 nLastBlock = vInv.size() - 1 - nInv;
3437 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3439 const CInv &inv = vInv[nInv];
3443 pfrom->AddInventoryKnown(inv);
3445 bool fAlreadyHave = AlreadyHave(txdb, inv);
3447 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3451 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3452 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3453 } else if (nInv == nLastBlock) {
3454 // In case we are on a very long side-chain, it is possible that we already have
3455 // the last block in an inv bundle sent in response to getblocks. Try to detect
3456 // this situation and push another getblocks to continue.
3457 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3459 printf("force request: %s\n", inv.ToString().c_str());
3462 // Track requests for our stuff
3463 Inventory(inv.hash);
3468 else if (strCommand == "getdata")
3472 if (vInv.size() > MAX_INV_SZ)
3474 pfrom->Misbehaving(20);
3475 return error("message getdata size() = %"PRIszu"", vInv.size());
3478 if (fDebugNet || (vInv.size() != 1))
3479 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3481 BOOST_FOREACH(const CInv& inv, vInv)
3485 if (fDebugNet || (vInv.size() == 1))
3486 printf("received getdata for: %s\n", inv.ToString().c_str());
3488 if (inv.type == MSG_BLOCK)
3490 // Send block from disk
3491 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3492 if (mi != mapBlockIndex.end())
3495 block.ReadFromDisk((*mi).second);
3496 pfrom->PushMessage("block", block);
3498 // Trigger them to send a getblocks request for the next batch of inventory
3499 if (inv.hash == pfrom->hashContinue)
3501 // ppcoin: send latest proof-of-work block to allow the
3502 // download node to accept as orphan (proof-of-stake
3503 // block might be rejected by stake connection check)
3505 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3506 pfrom->PushMessage("inv", vInv);
3507 pfrom->hashContinue = 0;
3511 else if (inv.IsKnownType())
3513 // Send stream from relay memory
3514 bool pushed = false;
3517 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3518 if (mi != mapRelay.end()) {
3519 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3523 if (!pushed && inv.type == MSG_TX) {
3525 if (mempool.exists(inv.hash)) {
3526 CTransaction tx = mempool.lookup(inv.hash);
3527 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3530 pfrom->PushMessage("tx", ss);
3535 // Track requests for our stuff
3536 Inventory(inv.hash);
3541 else if (strCommand == "getblocks")
3543 CBlockLocator locator;
3545 vRecv >> locator >> hashStop;
3547 // Find the last block the caller has in the main chain
3548 CBlockIndex* pindex = locator.GetBlockIndex();
3550 // Send the rest of the chain
3552 pindex = pindex->pnext;
3554 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3555 for (; pindex; pindex = pindex->pnext)
3557 if (pindex->GetBlockHash() == hashStop)
3559 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3560 // ppcoin: tell downloading node about the latest block if it's
3561 // without risk being rejected due to stake connection check
3562 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3563 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3566 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3569 // When this block is requested, we'll send an inv that'll make them
3570 // getblocks the next batch of inventory.
3571 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3572 pfrom->hashContinue = pindex->GetBlockHash();
3577 else if (strCommand == "checkpoint")
3579 CSyncCheckpoint checkpoint;
3580 vRecv >> checkpoint;
3582 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3585 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3587 BOOST_FOREACH(CNode* pnode, vNodes)
3588 checkpoint.RelayTo(pnode);
3592 else if (strCommand == "getheaders")
3594 CBlockLocator locator;
3596 vRecv >> locator >> hashStop;
3598 CBlockIndex* pindex = NULL;
3599 if (locator.IsNull())
3601 // If locator is null, return the hashStop block
3602 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3603 if (mi == mapBlockIndex.end())
3605 pindex = (*mi).second;
3609 // Find the last block the caller has in the main chain
3610 pindex = locator.GetBlockIndex();
3612 pindex = pindex->pnext;
3615 vector<CBlock> vHeaders;
3617 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3618 for (; pindex; pindex = pindex->pnext)
3620 vHeaders.push_back(pindex->GetBlockHeader());
3621 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3624 pfrom->PushMessage("headers", vHeaders);
3628 else if (strCommand == "tx")
3630 vector<uint256> vWorkQueue;
3631 vector<uint256> vEraseQueue;
3632 CDataStream vMsg(vRecv);
3637 CInv inv(MSG_TX, tx.GetHash());
3638 pfrom->AddInventoryKnown(inv);
3640 bool fMissingInputs = false;
3641 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3643 SyncWithWallets(tx, NULL, true);
3644 RelayTransaction(tx, inv.hash);
3645 mapAlreadyAskedFor.erase(inv);
3646 vWorkQueue.push_back(inv.hash);
3647 vEraseQueue.push_back(inv.hash);
3649 // Recursively process any orphan transactions that depended on this one
3650 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3652 uint256 hashPrev = vWorkQueue[i];
3653 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3654 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3657 const uint256& orphanTxHash = *mi;
3658 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3659 bool fMissingInputs2 = false;
3661 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3663 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3664 SyncWithWallets(tx, NULL, true);
3665 RelayTransaction(orphanTx, orphanTxHash);
3666 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3667 vWorkQueue.push_back(orphanTxHash);
3668 vEraseQueue.push_back(orphanTxHash);
3670 else if (!fMissingInputs2)
3673 vEraseQueue.push_back(orphanTxHash);
3674 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3679 BOOST_FOREACH(uint256 hash, vEraseQueue)
3680 EraseOrphanTx(hash);
3682 else if (fMissingInputs)
3686 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3687 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3689 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3691 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3695 else if (strCommand == "block")
3699 uint256 hashBlock = block.GetHash();
3701 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3704 CInv inv(MSG_BLOCK, hashBlock);
3705 pfrom->AddInventoryKnown(inv);
3707 if (ProcessBlock(pfrom, &block))
3708 mapAlreadyAskedFor.erase(inv);
3709 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3713 else if (strCommand == "getaddr")
3715 // Don't return addresses older than nCutOff timestamp
3716 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3717 pfrom->vAddrToSend.clear();
3718 vector<CAddress> vAddr = addrman.GetAddr();
3719 BOOST_FOREACH(const CAddress &addr, vAddr)
3720 if(addr.nTime > nCutOff)
3721 pfrom->PushAddress(addr);
3725 else if (strCommand == "mempool")
3727 std::vector<uint256> vtxid;
3728 mempool.queryHashes(vtxid);
3730 for (unsigned int i = 0; i < vtxid.size(); i++) {
3731 CInv inv(MSG_TX, vtxid[i]);
3732 vInv.push_back(inv);
3733 if (i == (MAX_INV_SZ - 1))
3736 if (vInv.size() > 0)
3737 pfrom->PushMessage("inv", vInv);
3741 else if (strCommand == "checkorder")
3746 if (!GetBoolArg("-allowreceivebyip"))
3748 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3755 /// we have a chance to check the order here
3757 // Keep giving the same key to the same ip until they use it
3758 if (!mapReuseKey.count(pfrom->addr))
3759 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3761 // Send back approval of order and pubkey to use
3762 CScript scriptPubKey;
3763 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3764 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3768 else if (strCommand == "reply")
3773 CRequestTracker tracker;
3775 LOCK(pfrom->cs_mapRequests);
3776 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3777 if (mi != pfrom->mapRequests.end())
3779 tracker = (*mi).second;
3780 pfrom->mapRequests.erase(mi);
3783 if (!tracker.IsNull())
3784 tracker.fn(tracker.param1, vRecv);
3788 else if (strCommand == "ping")
3790 if (pfrom->nVersion > BIP0031_VERSION)
3794 // Echo the message back with the nonce. This allows for two useful features:
3796 // 1) A remote node can quickly check if the connection is operational
3797 // 2) Remote nodes can measure the latency of the network thread. If this node
3798 // is overloaded it won't respond to pings quickly and the remote node can
3799 // avoid sending us more work, like chain download requests.
3801 // The nonce stops the remote getting confused between different pings: without
3802 // it, if the remote node sends a ping once per second and this node takes 5
3803 // seconds to respond to each, the 5th ping the remote sends would appear to
3804 // return very quickly.
3805 pfrom->PushMessage("pong", nonce);
3810 else if (strCommand == "alert")
3815 uint256 alertHash = alert.GetHash();
3816 if (pfrom->setKnown.count(alertHash) == 0)
3818 if (alert.ProcessAlert())
3821 pfrom->setKnown.insert(alertHash);
3824 BOOST_FOREACH(CNode* pnode, vNodes)
3825 alert.RelayTo(pnode);
3829 // Small DoS penalty so peers that send us lots of
3830 // duplicate/expired/invalid-signature/whatever alerts
3831 // eventually get banned.
3832 // This isn't a Misbehaving(100) (immediate ban) because the
3833 // peer might be an older or different implementation with
3834 // a different signature key, etc.
3835 pfrom->Misbehaving(10);
3843 // Ignore unknown commands for extensibility
3847 // Update the last seen time for this node's address
3848 if (pfrom->fNetworkNode)
3849 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3850 AddressCurrentlyConnected(pfrom->addr);
3856 bool ProcessMessages(CNode* pfrom)
3858 CDataStream& vRecv = pfrom->vRecv;
3862 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3866 // (4) message start
3875 // Don't bother if send buffer is too full to respond anyway
3876 if (pfrom->vSend.size() >= SendBufferSize())
3879 // Scan for message start
3880 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3881 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3882 if (vRecv.end() - pstart < nHeaderSize)
3884 if ((int)vRecv.size() > nHeaderSize)
3886 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3887 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3891 if (pstart - vRecv.begin() > 0)
3892 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3893 vRecv.erase(vRecv.begin(), pstart);
3896 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3901 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3904 string strCommand = hdr.GetCommand();
3907 unsigned int nMessageSize = hdr.nMessageSize;
3908 if (nMessageSize > MAX_SIZE)
3910 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3913 if (nMessageSize > vRecv.size())
3915 // Rewind and wait for rest of message
3916 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3921 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3922 unsigned int nChecksum = 0;
3923 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3924 if (nChecksum != hdr.nChecksum)
3926 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3927 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3931 // Copy message to its own buffer
3932 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3933 vRecv.ignore(nMessageSize);
3941 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3946 catch (std::ios_base::failure& e)
3948 if (strstr(e.what(), "end of data"))
3950 // Allow exceptions from under-length message on vRecv
3951 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());
3953 else if (strstr(e.what(), "size too large"))
3955 // Allow exceptions from over-long size
3956 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3960 PrintExceptionContinue(&e, "ProcessMessages()");
3963 catch (std::exception& e) {
3964 PrintExceptionContinue(&e, "ProcessMessages()");
3966 PrintExceptionContinue(NULL, "ProcessMessages()");
3970 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3978 bool SendMessages(CNode* pto, bool fSendTrickle)
3980 TRY_LOCK(cs_main, lockMain);
3982 // Don't send anything until we get their version message
3983 if (pto->nVersion == 0)
3986 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3988 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3990 if (pto->nVersion > BIP0031_VERSION)
3991 pto->PushMessage("ping", nonce);
3993 pto->PushMessage("ping");
3996 // Resend wallet transactions that haven't gotten in a block yet
3997 ResendWalletTransactions();
3999 // Address refresh broadcast
4000 static int64 nLastRebroadcast;
4001 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4005 BOOST_FOREACH(CNode* pnode, vNodes)
4007 // Periodically clear setAddrKnown to allow refresh broadcasts
4008 if (nLastRebroadcast)
4009 pnode->setAddrKnown.clear();
4011 // Rebroadcast our address
4014 CAddress addr = GetLocalAddress(&pnode->addr);
4015 if (addr.IsRoutable())
4016 pnode->PushAddress(addr);
4020 nLastRebroadcast = GetTime();
4028 vector<CAddress> vAddr;
4029 vAddr.reserve(pto->vAddrToSend.size());
4030 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4032 // returns true if wasn't already contained in the set
4033 if (pto->setAddrKnown.insert(addr).second)
4035 vAddr.push_back(addr);
4036 // receiver rejects addr messages larger than 1000
4037 if (vAddr.size() >= 1000)
4039 pto->PushMessage("addr", vAddr);
4044 pto->vAddrToSend.clear();
4046 pto->PushMessage("addr", vAddr);
4051 // Message: inventory
4054 vector<CInv> vInvWait;
4056 LOCK(pto->cs_inventory);
4057 vInv.reserve(pto->vInventoryToSend.size());
4058 vInvWait.reserve(pto->vInventoryToSend.size());
4059 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4061 if (pto->setInventoryKnown.count(inv))
4064 // trickle out tx inv to protect privacy
4065 if (inv.type == MSG_TX && !fSendTrickle)
4067 // 1/4 of tx invs blast to all immediately
4068 static uint256 hashSalt;
4070 hashSalt = GetRandHash();
4071 uint256 hashRand = inv.hash ^ hashSalt;
4072 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4073 bool fTrickleWait = ((hashRand & 3) != 0);
4075 // always trickle our own transactions
4079 if (GetTransaction(inv.hash, wtx))
4081 fTrickleWait = true;
4086 vInvWait.push_back(inv);
4091 // returns true if wasn't already contained in the set
4092 if (pto->setInventoryKnown.insert(inv).second)
4094 vInv.push_back(inv);
4095 if (vInv.size() >= 1000)
4097 pto->PushMessage("inv", vInv);
4102 pto->vInventoryToSend = vInvWait;
4105 pto->PushMessage("inv", vInv);
4111 vector<CInv> vGetData;
4112 int64 nNow = GetTime() * 1000000;
4114 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4116 const CInv& inv = (*pto->mapAskFor.begin()).second;
4117 if (!AlreadyHave(txdb, inv))
4120 printf("sending getdata: %s\n", inv.ToString().c_str());
4121 vGetData.push_back(inv);
4122 if (vGetData.size() >= 1000)
4124 pto->PushMessage("getdata", vGetData);
4127 mapAlreadyAskedFor[inv] = nNow;
4129 pto->mapAskFor.erase(pto->mapAskFor.begin());
4131 if (!vGetData.empty())
4132 pto->PushMessage("getdata", vGetData);