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);
152 // Preloaded coins cache invalidation
153 fCoinsDataActual = false;
156 // notify wallets about a new best chain
157 void static SetBestChain(const CBlockLocator& loc)
159 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
160 pwallet->SetBestChain(loc);
163 // notify wallets about an updated transaction
164 void static UpdatedTransaction(const uint256& hashTx)
166 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
167 pwallet->UpdatedTransaction(hashTx);
171 void static PrintWallets(const CBlock& block)
173 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
174 pwallet->PrintWallet(block);
177 // notify wallets about an incoming inventory (for request counts)
178 void static Inventory(const uint256& hash)
180 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
181 pwallet->Inventory(hash);
184 // ask wallets to resend their transactions
185 void ResendWalletTransactions()
187 BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
188 pwallet->ResendWalletTransactions();
197 //////////////////////////////////////////////////////////////////////////////
199 // mapOrphanTransactions
202 bool AddOrphanTx(const CTransaction& tx)
204 uint256 hash = tx.GetHash();
205 if (mapOrphanTransactions.count(hash))
208 // Ignore big transactions, to avoid a
209 // send-big-orphans memory exhaustion attack. If a peer has a legitimate
210 // large transaction with a missing parent then we assume
211 // it will rebroadcast it later, after the parent transaction(s)
212 // have been mined or received.
213 // 10,000 orphans, each of which is at most 5,000 bytes big is
214 // at most 500 megabytes of orphans:
216 size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
220 printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str());
224 mapOrphanTransactions[hash] = tx;
225 BOOST_FOREACH(const CTxIn& txin, tx.vin)
226 mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
228 printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
229 mapOrphanTransactions.size());
233 void static EraseOrphanTx(uint256 hash)
235 if (!mapOrphanTransactions.count(hash))
237 const CTransaction& tx = mapOrphanTransactions[hash];
238 BOOST_FOREACH(const CTxIn& txin, tx.vin)
240 mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
241 if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
242 mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
244 mapOrphanTransactions.erase(hash);
247 unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
249 unsigned int nEvicted = 0;
250 while (mapOrphanTransactions.size() > nMaxOrphans)
252 // Evict a random orphan:
253 uint256 randomhash = GetRandHash();
254 map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
255 if (it == mapOrphanTransactions.end())
256 it = mapOrphanTransactions.begin();
257 EraseOrphanTx(it->first);
269 //////////////////////////////////////////////////////////////////////////////
271 // CTransaction and CTxIndex
274 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
277 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
279 if (!ReadFromDisk(txindexRet.pos))
281 if (prevout.n >= vout.size())
289 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
292 return ReadFromDisk(txdb, prevout, txindex);
295 bool CTransaction::ReadFromDisk(COutPoint prevout)
299 return ReadFromDisk(txdb, prevout, txindex);
302 bool CTransaction::IsStandard() const
304 if (nVersion > CTransaction::CURRENT_VERSION)
307 unsigned int nDataOut = 0;
308 txnouttype whichType;
309 BOOST_FOREACH(const CTxIn& txin, vin)
311 // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
312 // pay-to-script-hash, which is 3 ~80-byte signatures, 3
313 // ~65-byte public keys, plus a few script ops.
314 if (txin.scriptSig.size() > 500)
316 if (!txin.scriptSig.IsPushOnly())
318 if (!txin.scriptSig.HasCanonicalPushes()) {
322 BOOST_FOREACH(const CTxOut& txout, vout) {
323 if (!::IsStandard(txout.scriptPubKey, whichType)) {
326 if (whichType == TX_NULL_DATA)
329 if (txout.nValue == 0) {
332 if (!txout.scriptPubKey.HasCanonicalPushes()) {
338 // only one OP_RETURN txout is permitted
347 // Check transaction inputs, and make sure any
348 // pay-to-script-hash transactions are evaluating IsStandard scripts
350 // Why bother? To avoid denial-of-service attacks; an attacker
351 // can submit a standard HASH... OP_EQUAL transaction,
352 // which will get accepted into blocks. The redemption
353 // script can be anything; an attacker could use a very
354 // expensive-to-check-upon-redemption script like:
355 // DUP CHECKSIG DROP ... repeated 100 times... OP_1
357 bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
360 return true; // Coinbases don't use vin normally
362 for (unsigned int i = 0; i < vin.size(); i++)
364 const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
366 vector<vector<unsigned char> > vSolutions;
367 txnouttype whichType;
368 // get the scriptPubKey corresponding to this input:
369 const CScript& prevScript = prev.scriptPubKey;
370 if (!Solver(prevScript, whichType, vSolutions))
372 int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
373 if (nArgsExpected < 0)
376 // Transactions with extra stuff in their scriptSigs are
377 // non-standard. Note that this EvalScript() call will
378 // be quick, because if there are any operations
379 // beside "push data" in the scriptSig the
380 // IsStandard() call returns false
381 vector<vector<unsigned char> > stack;
382 if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
385 if (whichType == TX_SCRIPTHASH)
389 CScript subscript(stack.back().begin(), stack.back().end());
390 vector<vector<unsigned char> > vSolutions2;
391 txnouttype whichType2;
392 if (!Solver(subscript, whichType2, vSolutions2))
394 if (whichType2 == TX_SCRIPTHASH)
398 tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
401 nArgsExpected += tmpExpected;
404 if (stack.size() != (unsigned int)nArgsExpected)
412 CTransaction::GetLegacySigOpCount() const
414 unsigned int nSigOps = 0;
415 BOOST_FOREACH(const CTxIn& txin, vin)
417 nSigOps += txin.scriptSig.GetSigOpCount(false);
419 BOOST_FOREACH(const CTxOut& txout, vout)
421 nSigOps += txout.scriptPubKey.GetSigOpCount(false);
427 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
439 // Load the block this tx is in
441 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
443 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
448 // Update the tx's hashBlock
449 hashBlock = pblock->GetHash();
451 // Locate the transaction
452 for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
453 if (pblock->vtx[nIndex] == *(CTransaction*)this)
455 if (nIndex == (int)pblock->vtx.size())
457 vMerkleBranch.clear();
459 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
463 // Fill in merkle branch
464 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
467 // Is the tx in a block that's in the main chain
468 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
469 if (mi == mapBlockIndex.end())
471 CBlockIndex* pindex = (*mi).second;
472 if (!pindex || !pindex->IsInMainChain())
475 return pindexBest->nHeight - pindex->nHeight + 1;
484 bool CTransaction::CheckTransaction() const
486 // Basic checks that don't depend on any context
488 return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
490 return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
492 if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
493 return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
495 // Check for negative or overflow output values
497 for (unsigned int i = 0; i < vout.size(); i++)
499 const CTxOut& txout = vout[i];
500 if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake())
501 return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
503 if (txout.nValue < 0)
504 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue is negative"));
505 if (txout.nValue > MAX_MONEY)
506 return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
507 nValueOut += txout.nValue;
508 if (!MoneyRange(nValueOut))
509 return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
512 // Check for duplicate inputs
513 set<COutPoint> vInOutPoints;
514 BOOST_FOREACH(const CTxIn& txin, vin)
516 if (vInOutPoints.count(txin.prevout))
518 vInOutPoints.insert(txin.prevout);
523 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
524 return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid"));
528 BOOST_FOREACH(const CTxIn& txin, vin)
529 if (txin.prevout.IsNull())
530 return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
536 int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree, enum GetMinFee_mode mode, unsigned int nBytes) const
538 // Use new fees approach if we are on test network or
539 // switch date has been reached
540 bool fNewApproach = fTestNet || nTime > FEE_SWITCH_TIME;
542 int64 nMinTxFee = MIN_TX_FEE, nMinRelayTxFee = MIN_RELAY_TX_FEE;
544 if(!fNewApproach || IsCoinStake())
546 // Enforce 0.01 as minimum fee for old approach or coinstake
548 nMinRelayTxFee = CENT;
551 // Base fee is either nMinTxFee or nMinRelayTxFee
552 int64 nBaseFee = (mode == GMF_RELAY) ? nMinRelayTxFee : nMinTxFee;
554 unsigned int nNewBlockSize = nBlockSize + nBytes;
555 int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
563 // Transactions under 1K are free
569 // Free transaction area
570 if (nNewBlockSize < 27000)
575 // To limit dust spam, require additional MIN_TX_FEE/MIN_RELAY_TX_FEE for
576 // each non empty output which is less than 0.01
578 // It's safe to ignore empty outputs here, because these inputs are allowed
579 // only for coinbase and coinstake transactions.
580 BOOST_FOREACH(const CTxOut& txout, vout)
581 if (txout.nValue < CENT && !txout.IsEmpty())
584 else if (nMinFee < nBaseFee)
586 // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if
587 // any output is less than 0.01
588 BOOST_FOREACH(const CTxOut& txout, vout)
589 if (txout.nValue < CENT)
593 // Raise the price as the block approaches full
594 if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
596 if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
598 nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
601 if (!MoneyRange(nMinFee))
608 bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
609 bool* pfMissingInputs)
612 *pfMissingInputs = false;
614 if (!tx.CheckTransaction())
615 return error("CTxMemPool::accept() : CheckTransaction failed");
617 // Coinbase is only valid in a block, not as a loose transaction
619 return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
621 // ppcoin: coinstake is also only valid in a block, not as a loose transaction
622 if (tx.IsCoinStake())
623 return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
625 // To help v0.1.5 clients who would see it as a negative number
626 if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
627 return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
629 // Rather not work on nonstandard transactions (unless -testnet)
630 if (!fTestNet && !tx.IsStandard())
631 return error("CTxMemPool::accept() : nonstandard transaction type");
633 // Do we already have it?
634 uint256 hash = tx.GetHash();
637 if (mapTx.count(hash))
641 if (txdb.ContainsTx(hash))
644 // Check for conflicts with in-memory transactions
645 CTransaction* ptxOld = NULL;
646 for (unsigned int i = 0; i < tx.vin.size(); i++)
648 COutPoint outpoint = tx.vin[i].prevout;
649 if (mapNextTx.count(outpoint))
651 // Disable replacement feature for now
654 // Allow replacing with a newer version of the same transaction
657 ptxOld = mapNextTx[outpoint].ptx;
658 if (ptxOld->IsFinal())
660 if (!tx.IsNewerThan(*ptxOld))
662 for (unsigned int i = 0; i < tx.vin.size(); i++)
664 COutPoint outpoint = tx.vin[i].prevout;
665 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
675 map<uint256, CTxIndex> mapUnused;
676 bool fInvalid = false;
677 if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
680 return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
682 *pfMissingInputs = true;
686 // Check for non-standard pay-to-script-hash in inputs
687 if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
688 return error("CTxMemPool::accept() : nonstandard transaction input");
690 // Note: if you modify this code to accept non-standard transactions, then
691 // you should add code here to check that the transaction does a
692 // reasonable number of ECDSA signature verifications.
694 int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
695 unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
697 // Don't accept it if it can't get into a block
698 int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY, nSize);
699 if (nFees < txMinFee)
700 return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
701 hash.ToString().c_str(),
704 // Continuously rate-limit free transactions
705 // This mitigates 'penny-flooding' -- sending thousands of free transactions just to
706 // be annoying or make others' transactions take longer to confirm.
707 if (nFees < MIN_RELAY_TX_FEE)
709 static CCriticalSection cs;
710 static double dFreeCount;
711 static int64 nLastTime;
712 int64 nNow = GetTime();
716 // Use an exponentially decaying ~10-minute window:
717 dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
719 // -limitfreerelay unit is thousand-bytes-per-minute
720 // At default rate it would take over a month to fill 1GB
721 if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
722 return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
724 printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
729 // Check against previous transactions
730 // This is done last to help prevent CPU exhaustion denial-of-service attacks.
731 if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false, true, SIG_SWITCH_TIME < tx.nTime ? STRICT_FLAGS : SOFT_FLAGS))
733 return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
737 // Store transaction in memory
742 printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
745 addUnchecked(hash, tx);
748 ///// are we sure this is ok when loading transactions or restoring block txes
749 // If updated, erase old tx from wallet
751 EraseFromWallets(ptxOld->GetHash());
753 printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
754 hash.ToString().substr(0,10).c_str(),
759 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
761 return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
764 bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
766 // Add to memory pool without checking anything. Don't call this directly,
767 // call CTxMemPool::accept to properly check the transaction first.
770 for (unsigned int i = 0; i < tx.vin.size(); i++)
771 mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
772 nTransactionsUpdated++;
778 bool CTxMemPool::remove(CTransaction &tx)
780 // Remove transaction from memory pool
783 uint256 hash = tx.GetHash();
784 if (mapTx.count(hash))
786 BOOST_FOREACH(const CTxIn& txin, tx.vin)
787 mapNextTx.erase(txin.prevout);
789 nTransactionsUpdated++;
795 void CTxMemPool::clear()
800 ++nTransactionsUpdated;
803 void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
808 vtxid.reserve(mapTx.size());
809 for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
810 vtxid.push_back((*mi).first);
816 int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
818 if (hashBlock == 0 || nIndex == -1)
821 // Find the block it claims to be in
822 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
823 if (mi == mapBlockIndex.end())
825 CBlockIndex* pindex = (*mi).second;
826 if (!pindex || !pindex->IsInMainChain())
829 // Make sure the merkle branch connects to this block
830 if (!fMerkleVerified)
832 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
834 fMerkleVerified = true;
838 return pindexBest->nHeight - pindex->nHeight + 1;
842 int CMerkleTx::GetBlocksToMaturity() const
844 if (!(IsCoinBase() || IsCoinStake()))
846 return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
850 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
854 if (!IsInMainChain() && !ClientConnectInputs())
856 return CTransaction::AcceptToMemoryPool(txdb, false);
860 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
864 bool CMerkleTx::AcceptToMemoryPool()
867 return AcceptToMemoryPool(txdb);
872 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
877 // Add previous supporting transactions first
878 BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
880 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
882 uint256 hash = tx.GetHash();
883 if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
884 tx.AcceptToMemoryPool(txdb, fCheckInputs);
887 return AcceptToMemoryPool(txdb, fCheckInputs);
892 bool CWalletTx::AcceptWalletTransaction()
895 return AcceptWalletTransaction(txdb);
898 int CTxIndex::GetDepthInMainChain() const
902 if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
904 // Find the block in the index
905 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
906 if (mi == mapBlockIndex.end())
908 CBlockIndex* pindex = (*mi).second;
909 if (!pindex || !pindex->IsInMainChain())
911 return 1 + nBestHeight - pindex->nHeight;
914 // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
915 bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
921 if (mempool.exists(hash))
923 tx = mempool.lookup(hash);
929 if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
932 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
933 hashBlock = block.GetHash();
947 //////////////////////////////////////////////////////////////////////////////
949 // CBlock and CBlockIndex
952 static CBlockIndex* pblockindexFBBHLast;
953 CBlockIndex* FindBlockByHeight(int nHeight)
955 CBlockIndex *pblockindex;
956 if (nHeight < nBestHeight / 2)
957 pblockindex = pindexGenesisBlock;
959 pblockindex = pindexBest;
960 if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
961 pblockindex = pblockindexFBBHLast;
962 while (pblockindex->nHeight > nHeight)
963 pblockindex = pblockindex->pprev;
964 while (pblockindex->nHeight < nHeight)
965 pblockindex = pblockindex->pnext;
966 pblockindexFBBHLast = pblockindex;
970 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
972 if (!fReadTransactions)
974 *this = pindex->GetBlockHeader();
977 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
979 if (GetHash() != pindex->GetBlockHash())
980 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
984 uint256 static GetOrphanRoot(const CBlock* pblock)
986 // Work back to the first block in the orphan chain
987 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
988 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
989 return pblock->GetHash();
992 // ppcoin: find block wanted by given orphan block
993 uint256 WantedByOrphan(const CBlock* pblockOrphan)
995 // Work back to the first block in the orphan chain
996 while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
997 pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
998 return pblockOrphan->hashPrevBlock;
1001 // select stake target limit according to hard-coded conditions
1002 CBigNum inline GetProofOfStakeLimit(int nHeight, unsigned int nTime)
1004 if(fTestNet) // separate proof of stake target limit for testnet
1005 return bnProofOfStakeLimit;
1006 if(nTime > TARGETS_SWITCH_TIME) // 27 bits since 20 July 2013
1007 return bnProofOfStakeLimit;
1008 if(nHeight + 1 > 15000) // 24 bits since block 15000
1009 return bnProofOfStakeLegacyLimit;
1010 if(nHeight + 1 > 14060) // 31 bits since block 14060 until 15000
1011 return bnProofOfStakeHardLimit;
1013 return bnProofOfWorkLimit; // return bnProofOfWorkLimit of none matched
1016 // miner's coin base reward based on nBits
1017 int64 GetProofOfWorkReward(unsigned int nBits, int64 nFees)
1019 CBigNum bnSubsidyLimit = MAX_MINT_PROOF_OF_WORK;
1022 bnTarget.SetCompact(nBits);
1023 CBigNum bnTargetLimit = bnProofOfWorkLimit;
1024 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1026 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
1027 // A reasonably continuous curve is used to avoid shock to market
1028 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
1030 // Human readable form:
1032 // nSubsidy = 100 / (diff ^ 1/6)
1033 CBigNum bnLowerBound = CENT;
1034 CBigNum bnUpperBound = bnSubsidyLimit;
1035 while (bnLowerBound + CENT <= bnUpperBound)
1037 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1038 if (fDebug && GetBoolArg("-printcreation"))
1039 printf("GetProofOfWorkReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1040 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
1041 bnUpperBound = bnMidValue;
1043 bnLowerBound = bnMidValue;
1046 int64 nSubsidy = bnUpperBound.getuint64();
1048 nSubsidy = (nSubsidy / CENT) * CENT;
1049 if (fDebug && GetBoolArg("-printcreation"))
1050 printf("GetProofOfWorkReward() : create=%s nBits=0x%08x nSubsidy=%"PRI64d"\n", FormatMoney(nSubsidy).c_str(), nBits, nSubsidy);
1052 return min(nSubsidy, MAX_MINT_PROOF_OF_WORK) + nFees;
1055 // miner's coin stake reward based on nBits and coin age spent (coin-days)
1056 int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, bool bCoinYearOnly)
1058 int64 nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * COIN;
1060 if(fTestNet || nTime > STAKE_SWITCH_TIME)
1062 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
1064 CBigNum bnRewardCoinYearLimit = MAX_MINT_PROOF_OF_STAKE; // Base stake mint rate, 100% year interest
1066 bnTarget.SetCompact(nBits);
1067 CBigNum bnTargetLimit = GetProofOfStakeLimit(0, nTime);
1068 bnTargetLimit.SetCompact(bnTargetLimit.GetCompact());
1070 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
1072 CBigNum bnLowerBound = 1 * CENT, // Lower interest bound is 1% per year
1073 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
1074 bnMidPart, bnRewardPart;
1076 while (bnLowerBound + CENT <= bnUpperBound)
1078 CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
1079 if (fDebug && GetBoolArg("-printcreation"))
1080 printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
1082 if(!fTestNet && nTime < STAKECURVE_SWITCH_TIME)
1085 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
1087 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
1089 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
1092 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
1093 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1098 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
1100 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
1102 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
1105 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
1106 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
1109 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
1110 bnUpperBound = bnMidValue;
1112 bnLowerBound = bnMidValue;
1115 nRewardCoinYear = bnUpperBound.getuint64();
1116 nRewardCoinYear = min((nRewardCoinYear / CENT) * CENT, MAX_MINT_PROOF_OF_STAKE);
1120 // Old creation amount per coin-year, 5% fixed stake mint rate
1121 nRewardCoinYear = 5 * CENT;
1125 return nRewardCoinYear;
1127 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
1129 // Set reasonable reward limit for large inputs since 20 Oct 2013
1131 // This will stimulate large holders to use smaller inputs, that's good for the network protection
1132 if(fTestNet || STAKECURVE_SWITCH_TIME < nTime)
1134 if (fDebug && GetBoolArg("-printcreation") && nSubsidyLimit < nSubsidy)
1135 printf("GetProofOfStakeReward(): %s is greater than %s, coinstake reward will be truncated\n", FormatMoney(nSubsidy).c_str(), FormatMoney(nSubsidyLimit).c_str());
1137 nSubsidy = min(nSubsidy, nSubsidyLimit);
1140 if (fDebug && GetBoolArg("-printcreation"))
1141 printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
1145 static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
1147 // get proof of work blocks max spacing according to hard-coded conditions
1148 int64 inline GetTargetSpacingWorkMax(int nHeight, unsigned int nTime)
1150 if(nTime > TARGETS_SWITCH_TIME)
1151 return 3 * nStakeTargetSpacing; // 30 minutes on mainNet since 20 Jul 2013 00:00:00
1154 return 3 * nStakeTargetSpacing; // 15 minutes on testNet
1156 return 12 * nStakeTargetSpacing; // 2 hours otherwise
1160 // maximum nBits value could possible be required nTime after
1162 unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64 nTime)
1165 bnResult.SetCompact(nBase);
1167 while (nTime > 0 && bnResult < bnTargetLimit)
1169 // Maximum 200% adjustment per day...
1171 nTime -= 24 * 60 * 60;
1173 if (bnResult > bnTargetLimit)
1174 bnResult = bnTargetLimit;
1175 return bnResult.GetCompact();
1179 // minimum amount of work that could possibly be required nTime after
1180 // minimum proof-of-work required was nBase
1182 unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
1184 return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime);
1188 // minimum amount of stake that could possibly be required nTime after
1189 // minimum proof-of-stake required was nBase
1191 unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime)
1193 return ComputeMaxBits(GetProofOfStakeLimit(0, nBlockTime), nBase, nTime);
1197 // ppcoin: find last block index up to pindex
1198 const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
1200 while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
1201 pindex = pindex->pprev;
1205 unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
1207 CBigNum bnTargetLimit = !fProofOfStake ? bnProofOfWorkLimit : GetProofOfStakeLimit(pindexLast->nHeight, pindexLast->nTime);
1209 if (pindexLast == NULL)
1210 return bnTargetLimit.GetCompact(); // genesis block
1212 const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
1213 if (pindexPrev->pprev == NULL)
1214 return bnTargetLimit.GetCompact(); // first block
1215 const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
1216 if (pindexPrevPrev->pprev == NULL)
1217 return bnTargetLimit.GetCompact(); // second block
1219 int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
1221 // ppcoin: target change every block
1222 // ppcoin: retarget with exponential moving toward target spacing
1224 bnNew.SetCompact(pindexPrev->nBits);
1225 int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(GetTargetSpacingWorkMax(pindexLast->nHeight, pindexLast->nTime), (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
1226 int64 nInterval = nTargetTimespan / nTargetSpacing;
1227 bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
1228 bnNew /= ((nInterval + 1) * nTargetSpacing);
1230 if (bnNew > bnTargetLimit)
1231 bnNew = bnTargetLimit;
1233 return bnNew.GetCompact();
1236 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
1239 bnTarget.SetCompact(nBits);
1242 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
1243 return error("CheckProofOfWork() : nBits below minimum work");
1245 // Check proof of work matches claimed amount
1246 if (hash > bnTarget.getuint256())
1247 return error("CheckProofOfWork() : hash doesn't match nBits");
1252 // Return maximum amount of blocks that other nodes claim to have
1253 int GetNumBlocksOfPeers()
1255 return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
1258 bool IsInitialBlockDownload()
1260 if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
1262 static int64 nLastUpdate;
1263 static CBlockIndex* pindexLastBest;
1264 if (pindexBest != pindexLastBest)
1266 pindexLastBest = pindexBest;
1267 nLastUpdate = GetTime();
1269 return (GetTime() - nLastUpdate < 10 &&
1270 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
1273 void static InvalidChainFound(CBlockIndex* pindexNew)
1275 if (pindexNew->nChainTrust > nBestInvalidTrust)
1277 nBestInvalidTrust = pindexNew->nChainTrust;
1278 CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust));
1279 uiInterface.NotifyBlocksChanged();
1282 uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust;
1283 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
1285 printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1286 pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
1287 CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(),
1288 DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str());
1289 printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
1290 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
1291 CBigNum(pindexBest->nChainTrust).ToString().c_str(),
1292 nBestBlockTrust.Get64(),
1293 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
1297 void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
1299 nTime = max(GetBlockTime(), GetAdjustedTime());
1312 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1314 // Relinquish previous transactions' spent pointers
1317 BOOST_FOREACH(const CTxIn& txin, vin)
1319 COutPoint prevout = txin.prevout;
1321 // Get prev txindex from disk
1323 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1324 return error("DisconnectInputs() : ReadTxIndex failed");
1326 if (prevout.n >= txindex.vSpent.size())
1327 return error("DisconnectInputs() : prevout.n out of range");
1329 // Mark outpoint as not spent
1330 txindex.vSpent[prevout.n].SetNull();
1333 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1334 return error("DisconnectInputs() : UpdateTxIndex failed");
1338 // Remove transaction from index
1339 // This can fail if a duplicate of this transaction was in a chain that got
1340 // reorganized away. This is only possible if this transaction was completely
1341 // spent, so erasing it would be a no-op anyway.
1342 txdb.EraseTxIndex(*this);
1348 bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
1349 bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
1351 // FetchInputs can return false either because we just haven't seen some inputs
1352 // (in which case the transaction should be stored as an orphan)
1353 // or because the transaction is malformed (in which case the transaction should
1354 // be dropped). If tx is definitely invalid, fInvalid will be set to true.
1358 return true; // Coinbase transactions have no inputs to fetch.
1360 for (unsigned int i = 0; i < vin.size(); i++)
1362 COutPoint prevout = vin[i].prevout;
1363 if (inputsRet.count(prevout.hash))
1364 continue; // Got it already
1367 CTxIndex& txindex = inputsRet[prevout.hash].first;
1369 if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
1371 // Get txindex from current proposed changes
1372 txindex = mapTestPool.find(prevout.hash)->second;
1376 // Read txindex from txdb
1377 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1379 if (!fFound && (fBlock || fMiner))
1380 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());
1383 CTransaction& txPrev = inputsRet[prevout.hash].second;
1384 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1386 // Get prev tx from single transactions in memory
1389 if (!mempool.exists(prevout.hash))
1390 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());
1391 txPrev = mempool.lookup(prevout.hash);
1394 txindex.vSpent.resize(txPrev.vout.size());
1398 // Get prev tx from disk
1399 if (!txPrev.ReadFromDisk(txindex.pos))
1400 return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1404 // Make sure all prevout.n indexes are valid:
1405 for (unsigned int i = 0; i < vin.size(); i++)
1407 const COutPoint prevout = vin[i].prevout;
1408 assert(inputsRet.count(prevout.hash) != 0);
1409 const CTxIndex& txindex = inputsRet[prevout.hash].first;
1410 const CTransaction& txPrev = inputsRet[prevout.hash].second;
1411 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1413 // Revisit this if/when transaction replacement is implemented and allows
1416 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()));
1423 const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
1425 MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
1426 if (mi == inputs.end())
1427 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
1429 const CTransaction& txPrev = (mi->second).second;
1430 if (input.prevout.n >= txPrev.vout.size())
1431 throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
1433 return txPrev.vout[input.prevout.n];
1436 int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
1442 for (unsigned int i = 0; i < vin.size(); i++)
1444 nResult += GetOutputFor(vin[i], inputs).nValue;
1450 unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
1455 unsigned int nSigOps = 0;
1456 for (unsigned int i = 0; i < vin.size(); i++)
1458 const CTxOut& prevout = GetOutputFor(vin[i], inputs);
1459 if (prevout.scriptPubKey.IsPayToScriptHash())
1460 nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
1465 bool CScriptCheck::operator()() const {
1466 const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
1467 if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
1468 return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().substr(0,10).c_str());
1472 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
1474 return CScriptCheck(txFrom, txTo, nIn, flags, nHashType)();
1477 bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
1478 const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fScriptChecks, unsigned int flags, std::vector<CScriptCheck> *pvChecks)
1480 // Take over previous transactions' spent pointers
1481 // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
1482 // fMiner is true when called from the internal bitcoin miner
1483 // ... both are false when called from CTransaction::AcceptToMemoryPool
1489 for (unsigned int i = 0; i < vin.size(); i++)
1491 COutPoint prevout = vin[i].prevout;
1492 assert(inputs.count(prevout.hash) > 0);
1493 CTxIndex& txindex = inputs[prevout.hash].first;
1494 CTransaction& txPrev = inputs[prevout.hash].second;
1496 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1497 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()));
1499 // If prev is coinbase or coinstake, check that it's matured
1500 if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
1501 for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
1502 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1503 return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight);
1505 // ppcoin: check transaction timestamp
1506 if (txPrev.nTime > nTime)
1507 return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
1509 // Check for negative or overflow input values
1510 nValueIn += txPrev.vout[prevout.n].nValue;
1511 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1512 return DoS(100, error("ConnectInputs() : txin values out of range"));
1517 pvChecks->reserve(vin.size());
1519 // The first loop above does all the inexpensive checks.
1520 // Only if ALL inputs pass do we perform expensive ECDSA signature checks.
1521 // Helps prevent CPU exhaustion attacks.
1522 for (unsigned int i = 0; i < vin.size(); i++)
1524 COutPoint prevout = vin[i].prevout;
1525 assert(inputs.count(prevout.hash) > 0);
1526 CTxIndex& txindex = inputs[prevout.hash].first;
1527 CTransaction& txPrev = inputs[prevout.hash].second;
1529 // Check for conflicts (double-spend)
1530 // This doesn't trigger the DoS code on purpose; if it did, it would make it easier
1531 // for an attacker to attempt to split the network.
1532 if (!txindex.vSpent[prevout.n].IsNull())
1533 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());
1535 // Skip ECDSA signature verification when connecting blocks (fBlock=true)
1536 // before the last blockchain checkpoint. This is safe because block merkle hashes are
1537 // still computed and checked, and any change will be caught at the next checkpoint.
1541 CScriptCheck check(txPrev, *this, i, flags, 0);
1544 pvChecks->push_back(CScriptCheck());
1545 check.swap(pvChecks->back());
1549 if (flags & STRICT_FLAGS)
1551 // Don't trigger DoS code in case of STRICT_FLAGS caused failure.
1552 CScriptCheck check(txPrev, *this, i, flags & ~STRICT_FLAGS, 0);
1554 return error("ConnectInputs() : %s strict VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1556 return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
1560 // Mark outpoints as spent
1561 txindex.vSpent[prevout.n] = posThisTx;
1564 if (fBlock || fMiner)
1566 mapTestPool[prevout.hash] = txindex;
1572 // ppcoin: coin stake tx earns reward instead of paying fee
1574 if (!GetCoinAge(txdb, nCoinAge))
1575 return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
1577 unsigned int nTxSize = (nTime > VALIDATION_SWITCH_TIME || fTestNet) ? GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION) : 0;
1579 int64 nReward = GetValueOut() - nValueIn;
1580 int64 nCalculatedReward = GetProofOfStakeReward(nCoinAge, pindexBlock->nBits, nTime) - GetMinFee(1, false, GMF_BLOCK, nTxSize) + CENT;
1582 if (nReward > nCalculatedReward)
1583 return DoS(100, error("ConnectInputs() : coinstake pays too much(actual=%"PRI64d" vs calculated=%"PRI64d")", nReward, nCalculatedReward));
1587 if (nValueIn < GetValueOut())
1588 return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
1590 // Tally transaction fees
1591 int64 nTxFee = nValueIn - GetValueOut();
1593 return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
1596 if (!MoneyRange(nFees))
1597 return DoS(100, error("ConnectInputs() : nFees out of range"));
1605 bool CTransaction::ClientConnectInputs()
1610 // Take over previous transactions' spent pointers
1614 for (unsigned int i = 0; i < vin.size(); i++)
1616 // Get prev tx from single transactions in memory
1617 COutPoint prevout = vin[i].prevout;
1618 if (!mempool.exists(prevout.hash))
1620 CTransaction& txPrev = mempool.lookup(prevout.hash);
1622 if (prevout.n >= txPrev.vout.size())
1626 if (!VerifySignature(txPrev, *this, i, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, 0))
1627 return error("ClientConnectInputs() : VerifySignature failed");
1629 ///// this is redundant with the mempool.mapNextTx stuff,
1630 ///// not sure which I want to get rid of
1631 ///// this has to go away now that posNext is gone
1632 // // Check for conflicts
1633 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1634 // return error("ConnectInputs() : prev tx already used");
1636 // // Flag outpoints as used
1637 // txPrev.vout[prevout.n].posNext = posThisTx;
1639 nValueIn += txPrev.vout[prevout.n].nValue;
1641 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1642 return error("ClientConnectInputs() : txin values out of range");
1644 if (GetValueOut() > nValueIn)
1654 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1656 // Disconnect in reverse order
1657 for (int i = vtx.size()-1; i >= 0; i--)
1658 if (!vtx[i].DisconnectInputs(txdb))
1661 // Update block index on disk without changing it in memory.
1662 // The memory index structure will be changed after the db commits.
1665 CDiskBlockIndex blockindexPrev(pindex->pprev);
1666 blockindexPrev.hashNext = 0;
1667 if (!txdb.WriteBlockIndex(blockindexPrev))
1668 return error("DisconnectBlock() : WriteBlockIndex failed");
1671 // ppcoin: clean up wallet after disconnecting coinstake
1672 BOOST_FOREACH(CTransaction& tx, vtx)
1673 SyncWithWallets(tx, this, false, false);
1678 static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
1680 void ThreadScriptCheck(void*) {
1681 vnThreadsRunning[THREAD_SCRIPTCHECK]++;
1682 RenameThread("novacoin-scriptch");
1683 scriptcheckqueue.Thread();
1684 vnThreadsRunning[THREAD_SCRIPTCHECK]--;
1687 void ThreadScriptCheckQuit() {
1688 scriptcheckqueue.Quit();
1691 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
1693 // Check it again in case a previous version let a bad block in, but skip BlockSig checking
1694 if (!CheckBlock(!fJustCheck, !fJustCheck, false))
1697 bool fProtocol048 = fTestNet || VALIDATION_SWITCH_TIME < nTime;
1699 // Do not allow blocks that contain transactions which 'overwrite' older transactions,
1700 // unless those are already completely spent.
1701 // If such overwrites are allowed, coinbases and transactions depending upon those
1702 // can be duplicated to remove the ability to spend the first instance -- even after
1703 // being sent to another address.
1704 // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
1705 // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
1706 // already refuses previously-known transaction ids entirely.
1707 // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
1708 // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
1709 // two in the chain that violate it. This prevents exploiting the issue against nodes in their
1710 // initial block download.
1711 bool fEnforceBIP30 = true; // Always active in NovaCoin
1712 bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
1714 //// issue here: it doesn't know the version
1715 unsigned int nTxPos;
1717 // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator
1718 // 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
1721 nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
1723 map<uint256, CTxIndex> mapQueuedChanges;
1724 CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
1728 int64 nValueOut = 0;
1729 unsigned int nSigOps = 0;
1730 BOOST_FOREACH(CTransaction& tx, vtx)
1732 uint256 hashTx = tx.GetHash();
1734 if (fEnforceBIP30) {
1735 CTxIndex txindexOld;
1736 if (txdb.ReadTxIndex(hashTx, txindexOld)) {
1737 BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
1743 nSigOps += tx.GetLegacySigOpCount();
1744 if (nSigOps > MAX_BLOCK_SIGOPS)
1745 return DoS(100, error("ConnectBlock() : too many sigops"));
1747 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1749 nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
1751 MapPrevTx mapInputs;
1752 if (tx.IsCoinBase())
1753 nValueOut += tx.GetValueOut();
1757 if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
1760 // Add in sigops done by pay-to-script-hash inputs;
1761 // this is to prevent a "rogue miner" from creating
1762 // an incredibly-expensive-to-validate block.
1763 nSigOps += tx.GetP2SHSigOpCount(mapInputs);
1764 if (nSigOps > MAX_BLOCK_SIGOPS)
1765 return DoS(100, error("ConnectBlock() : too many sigops"));
1767 int64 nTxValueIn = tx.GetValueIn(mapInputs);
1768 int64 nTxValueOut = tx.GetValueOut();
1769 nValueIn += nTxValueIn;
1770 nValueOut += nTxValueOut;
1771 if (!tx.IsCoinStake())
1772 nFees += nTxValueIn - nTxValueOut;
1774 std::vector<CScriptCheck> vChecks;
1775 if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fScriptChecks, SCRIPT_VERIFY_NOCACHE | SCRIPT_VERIFY_P2SH, nScriptCheckThreads ? &vChecks : NULL))
1777 control.Add(vChecks);
1780 mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
1783 if (!control.Wait())
1784 return DoS(100, false);
1786 if (IsProofOfWork())
1788 int64 nBlockReward = GetProofOfWorkReward(nBits, fProtocol048 ? nFees : 0);
1790 // Check coinbase reward
1791 if (vtx[0].GetValueOut() > nBlockReward)
1792 return error("CheckBlock() : coinbase reward exceeded (actual=%"PRI64d" vs calculated=%"PRI64d")",
1793 vtx[0].GetValueOut(),
1797 // track money supply and mint amount info
1798 pindex->nMint = nValueOut - nValueIn + nFees;
1799 pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
1800 if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
1801 return error("Connect() : WriteBlockIndex for pindex failed");
1803 // fees are not collected by proof-of-stake miners
1804 // fees are destroyed to compensate the entire network
1805 if (fProtocol048 && fDebug && IsProofOfStake() && GetBoolArg("-printcreation"))
1806 printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
1811 // Write queued txindex changes
1812 for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
1814 if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
1815 return error("ConnectBlock() : UpdateTxIndex failed");
1818 // Update block index on disk without changing it in memory.
1819 // The memory index structure will be changed after the db commits.
1822 CDiskBlockIndex blockindexPrev(pindex->pprev);
1823 blockindexPrev.hashNext = pindex->GetBlockHash();
1824 if (!txdb.WriteBlockIndex(blockindexPrev))
1825 return error("ConnectBlock() : WriteBlockIndex failed");
1828 // Watch for transactions paying to me
1829 BOOST_FOREACH(CTransaction& tx, vtx)
1830 SyncWithWallets(tx, this, true);
1836 bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1838 printf("REORGANIZE\n");
1841 CBlockIndex* pfork = pindexBest;
1842 CBlockIndex* plonger = pindexNew;
1843 while (pfork != plonger)
1845 while (plonger->nHeight > pfork->nHeight)
1846 if (!(plonger = plonger->pprev))
1847 return error("Reorganize() : plonger->pprev is null");
1848 if (pfork == plonger)
1850 if (!(pfork = pfork->pprev))
1851 return error("Reorganize() : pfork->pprev is null");
1854 // List of what to disconnect
1855 vector<CBlockIndex*> vDisconnect;
1856 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1857 vDisconnect.push_back(pindex);
1859 // List of what to connect
1860 vector<CBlockIndex*> vConnect;
1861 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1862 vConnect.push_back(pindex);
1863 reverse(vConnect.begin(), vConnect.end());
1865 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());
1866 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());
1868 // Disconnect shorter branch
1869 vector<CTransaction> vResurrect;
1870 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1873 if (!block.ReadFromDisk(pindex))
1874 return error("Reorganize() : ReadFromDisk for disconnect failed");
1875 if (!block.DisconnectBlock(txdb, pindex))
1876 return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1878 // Queue memory transactions to resurrect
1879 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1880 if (!(tx.IsCoinBase() || tx.IsCoinStake()))
1881 vResurrect.push_back(tx);
1884 // Connect longer branch
1885 vector<CTransaction> vDelete;
1886 for (unsigned int i = 0; i < vConnect.size(); i++)
1888 CBlockIndex* pindex = vConnect[i];
1890 if (!block.ReadFromDisk(pindex))
1891 return error("Reorganize() : ReadFromDisk for connect failed");
1892 if (!block.ConnectBlock(txdb, pindex))
1895 return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
1898 // Queue memory transactions to delete
1899 BOOST_FOREACH(const CTransaction& tx, block.vtx)
1900 vDelete.push_back(tx);
1902 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1903 return error("Reorganize() : WriteHashBestChain failed");
1905 // Make sure it's successfully written to disk before changing memory structure
1906 if (!txdb.TxnCommit())
1907 return error("Reorganize() : TxnCommit failed");
1909 // Disconnect shorter branch
1910 BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
1912 pindex->pprev->pnext = NULL;
1914 // Connect longer branch
1915 BOOST_FOREACH(CBlockIndex* pindex, vConnect)
1917 pindex->pprev->pnext = pindex;
1919 // Resurrect memory transactions that were in the disconnected branch
1920 BOOST_FOREACH(CTransaction& tx, vResurrect)
1921 tx.AcceptToMemoryPool(txdb, false);
1923 // Delete redundant memory transactions that are in the connected branch
1924 BOOST_FOREACH(CTransaction& tx, vDelete)
1927 printf("REORGANIZE: done\n");
1933 // Called from inside SetBestChain: attaches a block to the new best chain being built
1934 bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
1936 uint256 hash = GetHash();
1938 // Adding to current best branch
1939 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1942 InvalidChainFound(pindexNew);
1945 if (!txdb.TxnCommit())
1946 return error("SetBestChain() : TxnCommit failed");
1948 // Add to current best branch
1949 pindexNew->pprev->pnext = pindexNew;
1951 // Delete redundant memory transactions
1952 BOOST_FOREACH(CTransaction& tx, vtx)
1958 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1960 uint256 hash = GetHash();
1962 if (!txdb.TxnBegin())
1963 return error("SetBestChain() : TxnBegin failed");
1965 if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
1967 txdb.WriteHashBestChain(hash);
1968 if (!txdb.TxnCommit())
1969 return error("SetBestChain() : TxnCommit failed");
1970 pindexGenesisBlock = pindexNew;
1972 else if (hashPrevBlock == hashBestChain)
1974 if (!SetBestChainInner(txdb, pindexNew))
1975 return error("SetBestChain() : SetBestChainInner failed");
1979 // the first block in the new chain that will cause it to become the new best chain
1980 CBlockIndex *pindexIntermediate = pindexNew;
1982 // list of blocks that need to be connected afterwards
1983 std::vector<CBlockIndex*> vpindexSecondary;
1985 // Reorganize is costly in terms of db load, as it works in a single db transaction.
1986 // Try to limit how much needs to be done inside
1987 while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust)
1989 vpindexSecondary.push_back(pindexIntermediate);
1990 pindexIntermediate = pindexIntermediate->pprev;
1993 if (!vpindexSecondary.empty())
1994 printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
1996 // Switch to new best branch
1997 if (!Reorganize(txdb, pindexIntermediate))
2000 InvalidChainFound(pindexNew);
2001 return error("SetBestChain() : Reorganize failed");
2004 // Connect further blocks
2005 BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
2008 if (!block.ReadFromDisk(pindex))
2010 printf("SetBestChain() : ReadFromDisk failed\n");
2013 if (!txdb.TxnBegin()) {
2014 printf("SetBestChain() : TxnBegin 2 failed\n");
2017 // errors now are not fatal, we still did a reorganisation to a new chain in a valid way
2018 if (!block.SetBestChainInner(txdb, pindex))
2023 // Update best block in wallet (so we can detect restored wallets)
2024 bool fIsInitialDownload = IsInitialBlockDownload();
2025 if (!fIsInitialDownload)
2027 const CBlockLocator locator(pindexNew);
2028 ::SetBestChain(locator);
2032 hashBestChain = hash;
2033 pindexBest = pindexNew;
2034 pblockindexFBBHLast = NULL;
2035 nBestHeight = pindexBest->nHeight;
2036 nBestChainTrust = pindexNew->nChainTrust;
2037 nTimeBestReceived = GetTime();
2038 nTransactionsUpdated++;
2040 uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust;
2042 printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRI64d" date=%s\n",
2043 hashBestChain.ToString().substr(0,20).c_str(), nBestHeight,
2044 CBigNum(nBestChainTrust).ToString().c_str(),
2045 nBestBlockTrust.Get64(),
2046 DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
2048 // Check the version of the last 100 blocks to see if we need to upgrade:
2049 if (!fIsInitialDownload)
2052 const CBlockIndex* pindex = pindexBest;
2053 for (int i = 0; i < 100 && pindex != NULL; i++)
2055 if (pindex->nVersion > CBlock::CURRENT_VERSION)
2057 pindex = pindex->pprev;
2060 printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
2061 if (nUpgraded > 100/2)
2062 // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
2063 strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
2066 std::string strCmd = GetArg("-blocknotify", "");
2068 if (!fIsInitialDownload && !strCmd.empty())
2070 boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
2071 boost::thread t(runCommand, strCmd); // thread runs free
2077 // ppcoin: total coin age spent in transaction, in the unit of coin-days.
2078 // Only those coins meeting minimum age requirement counts. As those
2079 // transactions not in main chain are not currently indexed so we
2080 // might not find out about their coin age. Older transactions are
2081 // guaranteed to be in main chain by sync-checkpoint. This rule is
2082 // introduced to help nodes establish a consistent view of the coin
2083 // age (trust score) of competing branches.
2084 bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
2086 CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
2092 BOOST_FOREACH(const CTxIn& txin, vin)
2094 // First try finding the previous transaction in database
2095 CTransaction txPrev;
2097 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
2098 continue; // previous transaction not in main chain
2099 if (nTime < txPrev.nTime)
2100 return false; // Transaction timestamp violation
2102 // Read block header
2104 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
2105 return false; // unable to read block of previous transaction
2106 if (block.GetBlockTime() + nStakeMinAge > nTime)
2107 continue; // only count coins meeting min age requirement
2109 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
2110 bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
2112 if (fDebug && GetBoolArg("-printcoinage"))
2113 printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
2116 CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
2117 if (fDebug && GetBoolArg("-printcoinage"))
2118 printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
2119 nCoinAge = bnCoinDay.getuint64();
2123 // ppcoin: total coin age spent in block, in the unit of coin-days.
2124 bool CBlock::GetCoinAge(uint64& nCoinAge) const
2129 BOOST_FOREACH(const CTransaction& tx, vtx)
2132 if (tx.GetCoinAge(txdb, nTxCoinAge))
2133 nCoinAge += nTxCoinAge;
2138 if (nCoinAge == 0) // block coin age minimum 1 coin-day
2140 if (fDebug && GetBoolArg("-printcoinage"))
2141 printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
2145 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
2147 // Check for duplicate
2148 uint256 hash = GetHash();
2149 if (mapBlockIndex.count(hash))
2150 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
2152 // Construct new block index object
2153 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
2155 return error("AddToBlockIndex() : new CBlockIndex failed");
2156 pindexNew->phashBlock = &hash;
2157 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
2158 if (miPrev != mapBlockIndex.end())
2160 pindexNew->pprev = (*miPrev).second;
2161 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
2164 // ppcoin: compute chain trust score
2165 pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust();
2167 // ppcoin: compute stake entropy bit for stake modifier
2168 if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit(pindexNew->nTime)))
2169 return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
2171 // ppcoin: record proof-of-stake hash value
2172 if (pindexNew->IsProofOfStake())
2174 if (!mapProofOfStake.count(hash))
2175 return error("AddToBlockIndex() : hashProofOfStake not found in map");
2176 pindexNew->hashProofOfStake = mapProofOfStake[hash];
2179 // ppcoin: compute stake modifier
2180 uint64 nStakeModifier = 0;
2181 bool fGeneratedStakeModifier = false;
2182 if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
2183 return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
2184 pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
2185 pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
2186 if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
2187 return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
2189 // Add to mapBlockIndex
2190 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
2191 if (pindexNew->IsProofOfStake())
2192 setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
2193 pindexNew->phashBlock = &((*mi).first);
2195 // Write to disk block index
2197 if (!txdb.TxnBegin())
2199 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
2200 if (!txdb.TxnCommit())
2204 if (pindexNew->nChainTrust > nBestChainTrust)
2205 if (!SetBestChain(txdb, pindexNew))
2208 if (pindexNew == pindexBest)
2210 // Notify UI to display prev block's coinbase if it was ours
2211 static uint256 hashPrevBestCoinBase;
2212 UpdatedTransaction(hashPrevBestCoinBase);
2213 hashPrevBestCoinBase = vtx[0].GetHash();
2216 uiInterface.NotifyBlocksChanged();
2223 bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const
2225 // These are checks that are independent of context
2226 // that can be verified before saving an orphan block.
2229 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
2230 return DoS(100, error("CheckBlock() : size limits failed"));
2232 bool fProtocol048 = fTestNet || VALIDATION_SWITCH_TIME < nTime;
2234 // Check proof of work matches claimed amount
2235 if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
2236 return DoS(50, error("CheckBlock() : proof of work failed"));
2239 if (GetBlockTime() > FutureDrift(GetAdjustedTime()))
2240 return error("CheckBlock() : block timestamp too far in the future");
2242 // First transaction must be coinbase, the rest must not be
2243 if (vtx.empty() || !vtx[0].IsCoinBase())
2244 return DoS(100, error("CheckBlock() : first tx is not coinbase"));
2248 // Check coinbase timestamp
2249 if (GetBlockTime() < (int64)vtx[0].nTime)
2250 return DoS(100, error("CheckBlock() : coinbase timestamp violation"));
2254 // Check coinbase timestamp
2255 if (GetBlockTime() < PastDrift((int64)vtx[0].nTime))
2256 return DoS(50, error("CheckBlock() : coinbase timestamp is too late"));
2259 for (unsigned int i = 1; i < vtx.size(); i++)
2261 if (vtx[i].IsCoinBase())
2262 return DoS(100, error("CheckBlock() : more than one coinbase"));
2264 // Check transaction timestamp
2265 if (GetBlockTime() < (int64)vtx[i].nTime)
2266 return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
2269 if (IsProofOfStake())
2274 return DoS(100, error("CheckBlock() : non-zero nonce in proof-of-stake block"));
2277 // Coinbase output should be empty if proof-of-stake block
2278 if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty())
2279 return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
2281 // Second transaction must be coinstake, the rest must not be
2282 if (vtx.empty() || !vtx[1].IsCoinStake())
2283 return DoS(100, error("CheckBlock() : second tx is not coinstake"));
2284 for (unsigned int i = 2; i < vtx.size(); i++)
2285 if (vtx[i].IsCoinStake())
2286 return DoS(100, error("CheckBlock() : more than one coinstake"));
2288 // Check coinstake timestamp
2289 if (GetBlockTime() != (int64)vtx[1].nTime)
2290 return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
2292 // NovaCoin: check proof-of-stake block signature
2293 if (fCheckSig && !CheckBlockSignature(true))
2294 return DoS(100, error("CheckBlock() : bad proof-of-stake block signature"));
2298 // Should we check proof-of-work block signature or not?
2300 // * Always skip on TestNet
2301 // * Perform checking for the first 9689 blocks
2302 // * Perform checking since last checkpoint until 20 Sep 2013 (will be removed after)
2304 if(!fTestNet && fCheckSig)
2306 bool checkEntropySig = (GetBlockTime() < ENTROPY_SWITCH_TIME);
2308 // NovaCoin: check proof-of-work block signature
2309 if (checkEntropySig && !CheckBlockSignature(false))
2310 return DoS(100, error("CheckBlock() : bad proof-of-work block signature"));
2314 // Check transactions
2315 BOOST_FOREACH(const CTransaction& tx, vtx)
2317 if (!tx.CheckTransaction())
2318 return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
2321 // Check for duplicate txids. This is caught by ConnectInputs(),
2322 // but catching it earlier avoids a potential DoS attack:
2323 set<uint256> uniqueTx;
2324 BOOST_FOREACH(const CTransaction& tx, vtx)
2326 uniqueTx.insert(tx.GetHash());
2328 if (uniqueTx.size() != vtx.size())
2329 return DoS(100, error("CheckBlock() : duplicate transaction"));
2331 unsigned int nSigOps = 0;
2332 BOOST_FOREACH(const CTransaction& tx, vtx)
2334 nSigOps += tx.GetLegacySigOpCount();
2336 if (nSigOps > MAX_BLOCK_SIGOPS)
2337 return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
2339 // Check merkle root
2340 if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree())
2341 return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
2347 bool CBlock::AcceptBlock()
2349 // Check for duplicate
2350 uint256 hash = GetHash();
2351 if (mapBlockIndex.count(hash))
2352 return error("AcceptBlock() : block already in mapBlockIndex");
2354 // Get prev block index
2355 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
2356 if (mi == mapBlockIndex.end())
2357 return DoS(10, error("AcceptBlock() : prev block not found"));
2358 CBlockIndex* pindexPrev = (*mi).second;
2359 int nHeight = pindexPrev->nHeight+1;
2361 // Check proof-of-work or proof-of-stake
2362 if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
2363 return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake"));
2365 // Check timestamp against prev
2366 if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime())
2367 return error("AcceptBlock() : block's timestamp is too early");
2369 // Check that all transactions are finalized
2370 BOOST_FOREACH(const CTransaction& tx, vtx)
2371 if (!tx.IsFinal(nHeight, GetBlockTime()))
2372 return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
2374 // Check that the block chain matches the known block chain up to a checkpoint
2375 if (!Checkpoints::CheckHardened(nHeight, hash))
2376 return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight));
2378 bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev);
2380 // Check that the block satisfies synchronized checkpoint
2381 if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies)
2382 return error("AcceptBlock() : rejected by synchronized checkpoint");
2384 if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies)
2385 strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!");
2387 // Enforce rule that the coinbase starts with serialized block height
2388 CScript expect = CScript() << nHeight;
2389 if (vtx[0].vin[0].scriptSig.size() < expect.size() ||
2390 !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin()))
2391 return DoS(100, error("AcceptBlock() : block height mismatch in coinbase"));
2393 // Write block to history file
2394 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
2395 return error("AcceptBlock() : out of disk space");
2396 unsigned int nFile = -1;
2397 unsigned int nBlockPos = 0;
2398 if (!WriteToDisk(nFile, nBlockPos))
2399 return error("AcceptBlock() : WriteToDisk failed");
2400 if (!AddToBlockIndex(nFile, nBlockPos))
2401 return error("AcceptBlock() : AddToBlockIndex failed");
2403 // Relay inventory, but don't relay old inventory during initial block download
2404 int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
2405 if (hashBestChain == hash)
2408 BOOST_FOREACH(CNode* pnode, vNodes)
2409 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
2410 pnode->PushInventory(CInv(MSG_BLOCK, hash));
2413 // ppcoin: check pending sync-checkpoint
2414 Checkpoints::AcceptPendingSyncCheckpoint();
2419 uint256 CBlockIndex::GetBlockTrust() const
2422 bnTarget.SetCompact(nBits);
2428 if (!fTestNet && GetBlockTime() < CHAINCHECKS_SWITCH_TIME)
2429 return (IsProofOfStake()? ((CBigNum(1)<<256) / (bnTarget+1)).getuint256() : 1);
2433 // Calculate work amount for block
2434 uint256 nPoWTrust = (CBigNum(nPoWBase) / (bnTarget+1)).getuint256();
2436 // Set nPowTrust to 1 if we are checking PoS block or PoW difficulty is too low
2437 nPoWTrust = (IsProofOfStake() || nPoWTrust < 1) ? 1 : nPoWTrust;
2439 // Return nPoWTrust for the first 12 blocks
2440 if (pprev == NULL || pprev->nHeight < 12)
2443 const CBlockIndex* currentIndex = pprev;
2445 if(IsProofOfStake())
2447 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2449 // Return 1/3 of score if parent block is not the PoW block
2450 if (!pprev->IsProofOfWork())
2451 return (bnNewTrust / 3).getuint256();
2455 // Check last 12 blocks type
2456 while (pprev->nHeight - currentIndex->nHeight < 12)
2458 if (currentIndex->IsProofOfWork())
2460 currentIndex = currentIndex->pprev;
2463 // Return 1/3 of score if less than 3 PoW blocks found
2465 return (bnNewTrust / 3).getuint256();
2467 return bnNewTrust.getuint256();
2471 CBigNum bnLastBlockTrust = CBigNum(pprev->nChainTrust - pprev->pprev->nChainTrust);
2473 // Return nPoWTrust + 2/3 of previous block score if two parent blocks are not PoS blocks
2474 if (!(pprev->IsProofOfStake() && pprev->pprev->IsProofOfStake()))
2475 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2479 // Check last 12 blocks type
2480 while (pprev->nHeight - currentIndex->nHeight < 12)
2482 if (currentIndex->IsProofOfStake())
2484 currentIndex = currentIndex->pprev;
2487 // Return nPoWTrust + 2/3 of previous block score if less than 7 PoS blocks found
2489 return nPoWTrust + (2 * bnLastBlockTrust / 3).getuint256();
2491 bnTarget.SetCompact(pprev->nBits);
2496 CBigNum bnNewTrust = (CBigNum(1)<<256) / (bnTarget+1);
2498 // Return nPoWTrust + full trust score for previous block nBits
2499 return nPoWTrust + bnNewTrust.getuint256();
2503 bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck)
2505 unsigned int nFound = 0;
2506 for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++)
2508 if (pstart->nVersion >= minVersion)
2510 pstart = pstart->pprev;
2512 return (nFound >= nRequired);
2515 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
2517 // Check for duplicate
2518 uint256 hash = pblock->GetHash();
2519 if (mapBlockIndex.count(hash))
2520 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
2521 if (mapOrphanBlocks.count(hash))
2522 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
2524 // ppcoin: check proof-of-stake
2525 // Limited duplicity on stake: prevents block flood attack
2526 // Duplicate stake allowed only when there is orphan child block
2527 if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2528 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());
2530 // Preliminary checks
2531 if (!pblock->CheckBlock())
2532 return error("ProcessBlock() : CheckBlock FAILED");
2534 // ppcoin: verify hash target and signature of coinstake tx
2535 if (pblock->IsProofOfStake())
2537 uint256 hashProofOfStake = 0, targetProofOfStake = 0;
2538 if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake, targetProofOfStake))
2540 printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
2541 return false; // do not error here as we expect this during initial block download
2543 if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
2544 mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
2547 CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
2548 if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2550 // Extra checks to prevent "fill up memory by spamming with bogus blocks"
2551 int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
2553 bnNewBlock.SetCompact(pblock->nBits);
2556 if (pblock->IsProofOfStake())
2557 bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime));
2559 bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime));
2561 if (bnNewBlock > bnRequired)
2564 pfrom->Misbehaving(100);
2565 return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
2569 // ppcoin: ask for pending sync-checkpoint if any
2570 if (!IsInitialBlockDownload())
2571 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
2573 // If don't already have its previous block, shunt it off to holding area until we get it
2574 if (!mapBlockIndex.count(pblock->hashPrevBlock))
2576 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
2577 CBlock* pblock2 = new CBlock(*pblock);
2578 // ppcoin: check proof-of-stake
2579 if (pblock2->IsProofOfStake())
2581 // Limited duplicity on stake: prevents block flood attack
2582 // Duplicate stake allowed only when there is orphan child block
2583 if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
2584 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());
2586 setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
2588 mapOrphanBlocks.insert(make_pair(hash, pblock2));
2589 mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
2591 // Ask this guy to fill in what we're missing
2594 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
2595 // ppcoin: getblocks may not obtain the ancestor block rejected
2596 // earlier by duplicate-stake check so we ask for it again directly
2597 if (!IsInitialBlockDownload())
2598 pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
2604 if (!pblock->AcceptBlock())
2605 return error("ProcessBlock() : AcceptBlock FAILED");
2607 // Recursively process any orphan blocks that depended on this one
2608 vector<uint256> vWorkQueue;
2609 vWorkQueue.push_back(hash);
2610 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
2612 uint256 hashPrev = vWorkQueue[i];
2613 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
2614 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
2617 CBlock* pblockOrphan = (*mi).second;
2618 if (pblockOrphan->AcceptBlock())
2619 vWorkQueue.push_back(pblockOrphan->GetHash());
2620 mapOrphanBlocks.erase(pblockOrphan->GetHash());
2621 setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
2622 delete pblockOrphan;
2624 mapOrphanBlocksByPrev.erase(hashPrev);
2627 printf("ProcessBlock: ACCEPTED\n");
2629 // ppcoin: if responsible for sync-checkpoint send it
2630 if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
2631 Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
2636 // novacoin: attempt to generate suitable proof-of-stake
2637 bool CBlock::SignBlock(CWallet& wallet)
2639 // if we are trying to sign
2640 // something except proof-of-stake block template
2641 if (!vtx[0].vout[0].IsEmpty())
2644 // if we are trying to sign
2645 // a complete proof-of-stake block
2646 if (IsProofOfStake())
2649 static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp
2652 CTransaction txCoinStake;
2653 int64 nSearchTime = txCoinStake.nTime; // search to current time
2655 if (nSearchTime > nLastCoinStakeSearchTime)
2657 if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, key))
2659 if (txCoinStake.nTime >= max(pindexBest->GetMedianTimePast()+1, PastDrift(pindexBest->GetBlockTime())))
2661 // make sure coinstake would meet timestamp protocol
2662 // as it would be the same as the block timestamp
2663 vtx[0].nTime = nTime = txCoinStake.nTime;
2664 nTime = max(pindexBest->GetMedianTimePast()+1, GetMaxTransactionTime());
2665 nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime()));
2667 // we have to make sure that we have no future timestamps in
2668 // our transactions set
2669 for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();)
2670 if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; }
2672 vtx.insert(vtx.begin() + 1, txCoinStake);
2673 hashMerkleRoot = BuildMerkleTree();
2675 // append a signature to our block
2676 return key.Sign(GetHash(), vchBlockSig);
2679 nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
2680 nLastCoinStakeSearchTime = nSearchTime;
2686 // ppcoin: check block signature
2687 bool CBlock::CheckBlockSignature(bool fProofOfStake) const
2689 if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
2690 return vchBlockSig.empty();
2692 vector<valtype> vSolutions;
2693 txnouttype whichType;
2697 const CTxOut& txout = vtx[1].vout[1];
2699 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2701 if (whichType == TX_PUBKEY)
2703 valtype& vchPubKey = vSolutions[0];
2705 if (!key.SetPubKey(vchPubKey))
2707 if (vchBlockSig.empty())
2709 return key.Verify(GetHash(), vchBlockSig);
2714 for(unsigned int i = 0; i < vtx[0].vout.size(); i++)
2716 const CTxOut& txout = vtx[0].vout[i];
2718 if (!Solver(txout.scriptPubKey, whichType, vSolutions))
2721 if (whichType == TX_PUBKEY)
2724 valtype& vchPubKey = vSolutions[0];
2726 if (!key.SetPubKey(vchPubKey))
2728 if (vchBlockSig.empty())
2730 if(!key.Verify(GetHash(), vchBlockSig))
2740 bool CheckDiskSpace(uint64 nAdditionalBytes)
2742 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
2744 // Check for nMinDiskSpace bytes (currently 50MB)
2745 if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
2748 string strMessage = _("Warning: Disk space is low!");
2749 strMiscWarning = strMessage;
2750 printf("*** %s\n", strMessage.c_str());
2751 uiInterface.ThreadSafeMessageBox(strMessage, "NovaCoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
2758 static filesystem::path BlockFilePath(unsigned int nFile)
2760 string strBlockFn = strprintf("blk%04u.dat", nFile);
2761 return GetDataDir() / strBlockFn;
2764 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
2766 if ((nFile < 1) || (nFile == (unsigned int) -1))
2768 FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode);
2771 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
2773 if (fseek(file, nBlockPos, SEEK_SET) != 0)
2782 static unsigned int nCurrentBlockFile = 1;
2784 FILE* AppendBlockFile(unsigned int& nFileRet)
2789 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
2792 if (fseek(file, 0, SEEK_END) != 0)
2794 // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
2795 if (ftell(file) < (long)(0x7F000000 - MAX_SIZE))
2797 nFileRet = nCurrentBlockFile;
2801 nCurrentBlockFile++;
2805 bool LoadBlockIndex(bool fAllowNew)
2807 CBigNum bnTrustedModulus;
2811 pchMessageStart[0] = 0xcd;
2812 pchMessageStart[1] = 0xf2;
2813 pchMessageStart[2] = 0xc0;
2814 pchMessageStart[3] = 0xef;
2816 bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55");
2817 bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet
2818 nStakeMinAge = 2 * 60 * 60; // test net min age is 2 hours
2819 nModifierInterval = 20 * 60; // test modifier interval is 20 minutes
2820 nCoinbaseMaturity = 10; // test maturity is 10 blocks
2821 nStakeTargetSpacing = 5 * 60; // test block spacing is 5 minutes
2825 bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081");
2828 // Set up the Zerocoin Params object
2829 ZCParams = new libzerocoin::Params(bnTrustedModulus);
2835 if (!txdb.LoadBlockIndex())
2839 // Init with genesis block
2841 if (mapBlockIndex.empty())
2850 //CBlock(hash=00000a060336cbb72fe969666d337b87198b1add2abaa59cca226820b32933a4, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1e0fffff, nNonce=1575379, vtx=1, vchBlockSig=)
2851 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2852 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2854 // vMerkleTree: 4cb33b3b6a
2858 //CBlock(hash=0000c763e402f2436da9ed36c7286f62c3f6e5dbafce9ff289bd43d7459327eb, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b, nTime=1360105017, nBits=1f00ffff, nNonce=46534, vtx=1, vchBlockSig=)
2859 // Coinbase(hash=4cb33b3b6a, nTime=1360105017, ver=1, vin.size=1, vout.size=1, nLockTime=0)
2860 // CTxIn(COutPoint(0000000000, 4294967295), coinbase 04ffff001d020f274468747470733a2f2f626974636f696e74616c6b2e6f72672f696e6465782e7068703f746f7069633d3133343137392e6d736731353032313936236d736731353032313936)
2862 // vMerkleTree: 4cb33b3b6a
2864 const char* pszTimestamp = "https://bitcointalk.org/index.php?topic=134179.msg1502196#msg1502196";
2866 txNew.nTime = 1360105017;
2867 txNew.vin.resize(1);
2868 txNew.vout.resize(1);
2869 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
2870 txNew.vout[0].SetEmpty();
2872 block.vtx.push_back(txNew);
2873 block.hashPrevBlock = 0;
2874 block.hashMerkleRoot = block.BuildMerkleTree();
2876 block.nTime = 1360105017;
2877 block.nBits = bnProofOfWorkLimit.GetCompact();
2878 block.nNonce = !fTestNet ? 1575379 : 46534;
2881 assert(block.hashMerkleRoot == uint256("0x4cb33b3b6a861dcbc685d3e614a9cafb945738d6833f182855679f2fad02057b"));
2883 assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
2884 assert(block.CheckBlock());
2886 // Start new block file
2888 unsigned int nBlockPos;
2889 if (!block.WriteToDisk(nFile, nBlockPos))
2890 return error("LoadBlockIndex() : writing genesis block to disk failed");
2891 if (!block.AddToBlockIndex(nFile, nBlockPos))
2892 return error("LoadBlockIndex() : genesis block not accepted");
2894 // initialize synchronized checkpoint
2895 if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)))
2896 return error("LoadBlockIndex() : failed to init sync checkpoint");
2898 // upgrade time set to zero if txdb initialized
2900 if (!txdb.WriteModifierUpgradeTime(0))
2901 return error("LoadBlockIndex() : failed to init upgrade info");
2902 printf(" Upgrade Info: ModifierUpgradeTime txdb initialization\n");
2908 string strPubKey = "";
2909 if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
2911 // write checkpoint master key to db
2913 if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
2914 return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
2915 if (!txdb.TxnCommit())
2916 return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
2917 if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
2918 return error("LoadBlockIndex() : failed to reset sync-checkpoint");
2921 // upgrade time set to zero if blocktreedb initialized
2922 if (txdb.ReadModifierUpgradeTime(nModifierUpgradeTime))
2924 if (nModifierUpgradeTime)
2925 printf(" Upgrade Info: blocktreedb upgrade detected at timestamp %d\n", nModifierUpgradeTime);
2927 printf(" Upgrade Info: no blocktreedb upgrade detected.\n");
2931 nModifierUpgradeTime = GetTime();
2932 printf(" Upgrade Info: upgrading blocktreedb at timestamp %u\n", nModifierUpgradeTime);
2933 if (!txdb.WriteModifierUpgradeTime(nModifierUpgradeTime))
2934 return error("LoadBlockIndex() : failed to write upgrade info");
2947 void PrintBlockTree()
2949 // pre-compute tree structure
2950 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
2951 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
2953 CBlockIndex* pindex = (*mi).second;
2954 mapNext[pindex->pprev].push_back(pindex);
2956 //while (rand() % 3 == 0)
2957 // mapNext[pindex->pprev].push_back(pindex);
2960 vector<pair<int, CBlockIndex*> > vStack;
2961 vStack.push_back(make_pair(0, pindexGenesisBlock));
2964 while (!vStack.empty())
2966 int nCol = vStack.back().first;
2967 CBlockIndex* pindex = vStack.back().second;
2970 // print split or gap
2971 if (nCol > nPrevCol)
2973 for (int i = 0; i < nCol-1; i++)
2977 else if (nCol < nPrevCol)
2979 for (int i = 0; i < nCol; i++)
2986 for (int i = 0; i < nCol; i++)
2991 block.ReadFromDisk(pindex);
2992 printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
2996 block.GetHash().ToString().c_str(),
2998 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
2999 FormatMoney(pindex->nMint).c_str(),
3002 PrintWallets(block);
3004 // put the main time-chain first
3005 vector<CBlockIndex*>& vNext = mapNext[pindex];
3006 for (unsigned int i = 0; i < vNext.size(); i++)
3008 if (vNext[i]->pnext)
3010 swap(vNext[0], vNext[i]);
3016 for (unsigned int i = 0; i < vNext.size(); i++)
3017 vStack.push_back(make_pair(nCol+i, vNext[i]));
3021 bool LoadExternalBlockFile(FILE* fileIn)
3023 int64 nStart = GetTimeMillis();
3029 CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
3030 unsigned int nPos = 0;
3031 while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
3033 unsigned char pchData[65536];
3035 fseek(blkdat, nPos, SEEK_SET);
3036 int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
3039 nPos = (unsigned int)-1;
3042 void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
3045 if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
3047 nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
3050 nPos += ((unsigned char*)nFind - pchData) + 1;
3053 nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
3054 } while(!fRequestShutdown);
3055 if (nPos == (unsigned int)-1)
3057 fseek(blkdat, nPos, SEEK_SET);
3060 if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
3064 if (ProcessBlock(NULL,&block))
3072 catch (std::exception &e) {
3073 printf("%s() : Deserialize or I/O error caught during load\n",
3074 __PRETTY_FUNCTION__);
3077 printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
3081 //////////////////////////////////////////////////////////////////////////////
3086 extern map<uint256, CAlert> mapAlerts;
3087 extern CCriticalSection cs_mapAlerts;
3089 string GetWarnings(string strFor)
3092 string strStatusBar;
3095 if (GetBoolArg("-testsafemode"))
3098 // Misc warnings like out of disk space and clock is wrong
3099 if (strMiscWarning != "")
3102 strStatusBar = strMiscWarning;
3105 // if detected unmet upgrade requirement enter safe mode
3106 // Note: Modifier upgrade requires blockchain redownload if past protocol switch
3107 if (IsFixedModifierInterval(nModifierUpgradeTime + 60*60*24)) // 1 day margin
3110 strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v.0.4.4.6u4 upgrade deadline.";
3113 // if detected invalid checkpoint enter safe mode
3114 if (Checkpoints::hashInvalidCheckpoint != 0)
3117 strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.");
3123 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3125 const CAlert& alert = item.second;
3126 if (alert.AppliesToMe() && alert.nPriority > nPriority)
3128 nPriority = alert.nPriority;
3129 strStatusBar = alert.strStatusBar;
3130 if (nPriority > 1000)
3131 strRPC = strStatusBar;
3136 if (strFor == "statusbar")
3137 return strStatusBar;
3138 else if (strFor == "rpc")
3140 assert(!"GetWarnings() : invalid parameter");
3151 //////////////////////////////////////////////////////////////////////////////
3157 bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
3163 bool txInMap = false;
3166 txInMap = (mempool.exists(inv.hash));
3169 mapOrphanTransactions.count(inv.hash) ||
3170 txdb.ContainsTx(inv.hash);
3174 return mapBlockIndex.count(inv.hash) ||
3175 mapOrphanBlocks.count(inv.hash);
3177 // Don't know what it is, just say we already got one
3184 // The message start string is designed to be unlikely to occur in normal data.
3185 // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
3186 // a large 4-byte int at any alignment.
3187 unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
3189 bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
3191 static map<CService, CPubKey> mapReuseKey;
3192 RandAddSeedPerfmon();
3194 printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
3195 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
3197 printf("dropmessagestest DROPPING RECV MESSAGE\n");
3201 if (strCommand == "version")
3203 // Each connection can only send one version message
3204 if (pfrom->nVersion != 0)
3206 pfrom->Misbehaving(1);
3214 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
3215 if (pfrom->nVersion < MIN_PROTO_VERSION)
3217 // Since February 20, 2012, the protocol is initiated at version 209,
3218 // and earlier versions are no longer supported
3219 printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3220 pfrom->fDisconnect = true;
3224 if (pfrom->nVersion == 10300)
3225 pfrom->nVersion = 300;
3227 vRecv >> addrFrom >> nNonce;
3229 vRecv >> pfrom->strSubVer;
3231 vRecv >> pfrom->nStartingHeight;
3233 if (pfrom->fInbound && addrMe.IsRoutable())
3235 pfrom->addrLocal = addrMe;
3239 // Disconnect if we connected to ourself
3240 if (nNonce == nLocalHostNonce && nNonce > 1)
3242 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
3243 pfrom->fDisconnect = true;
3247 if (pfrom->nVersion < 60010)
3249 printf("partner %s using a buggy client %d, disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
3250 pfrom->fDisconnect = true;
3254 // record my external IP reported by peer
3255 if (addrFrom.IsRoutable() && addrMe.IsRoutable())
3256 addrSeenByPeer = addrMe;
3258 // Be shy and don't send version until we hear
3259 if (pfrom->fInbound)
3260 pfrom->PushVersion();
3262 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
3264 AddTimeData(pfrom->addr, nTime);
3267 pfrom->PushMessage("verack");
3268 pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3270 if (!pfrom->fInbound)
3272 // Advertise our address
3273 if (!fNoListen && !IsInitialBlockDownload())
3275 CAddress addr = GetLocalAddress(&pfrom->addr);
3276 if (addr.IsRoutable())
3277 pfrom->PushAddress(addr);
3280 // Get recent addresses
3281 if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
3283 pfrom->PushMessage("getaddr");
3284 pfrom->fGetAddr = true;
3286 addrman.Good(pfrom->addr);
3288 if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
3290 addrman.Add(addrFrom, addrFrom);
3291 addrman.Good(addrFrom);
3295 // Ask the first connected node for block updates
3296 static int nAskedForBlocks = 0;
3297 if (!pfrom->fClient && !pfrom->fOneShot &&
3298 (pfrom->nStartingHeight > (nBestHeight - 144)) &&
3299 (pfrom->nVersion < NOBLKS_VERSION_START ||
3300 pfrom->nVersion >= NOBLKS_VERSION_END) &&
3301 (nAskedForBlocks < 1 || vNodes.size() <= 1))
3304 pfrom->PushGetBlocks(pindexBest, uint256(0));
3310 BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
3311 item.second.RelayTo(pfrom);
3314 // Relay sync-checkpoint
3316 LOCK(Checkpoints::cs_hashSyncCheckpoint);
3317 if (!Checkpoints::checkpointMessage.IsNull())
3318 Checkpoints::checkpointMessage.RelayTo(pfrom);
3321 pfrom->fSuccessfullyConnected = true;
3323 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());
3325 cPeerBlockCounts.input(pfrom->nStartingHeight);
3327 // ppcoin: ask for pending sync-checkpoint if any
3328 if (!IsInitialBlockDownload())
3329 Checkpoints::AskForPendingSyncCheckpoint(pfrom);
3333 else if (pfrom->nVersion == 0)
3335 // Must have a version message before anything else
3336 pfrom->Misbehaving(1);
3341 else if (strCommand == "verack")
3343 pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
3347 else if (strCommand == "addr")
3349 vector<CAddress> vAddr;
3352 // Don't want addr from older versions unless seeding
3353 if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
3355 if (vAddr.size() > 1000)
3357 pfrom->Misbehaving(20);
3358 return error("message addr size() = %"PRIszu"", vAddr.size());
3361 // Store the new addresses
3362 vector<CAddress> vAddrOk;
3363 int64 nNow = GetAdjustedTime();
3364 int64 nSince = nNow - 10 * 60;
3365 BOOST_FOREACH(CAddress& addr, vAddr)
3369 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
3370 addr.nTime = nNow - 5 * 24 * 60 * 60;
3371 pfrom->AddAddressKnown(addr);
3372 bool fReachable = IsReachable(addr);
3373 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
3375 // Relay to a limited number of other nodes
3378 // Use deterministic randomness to send to the same nodes for 24 hours
3379 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
3380 static uint256 hashSalt;
3382 hashSalt = GetRandHash();
3383 uint64 hashAddr = addr.GetHash();
3384 uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
3385 hashRand = Hash(BEGIN(hashRand), END(hashRand));
3386 multimap<uint256, CNode*> mapMix;
3387 BOOST_FOREACH(CNode* pnode, vNodes)
3389 if (pnode->nVersion < CADDR_TIME_VERSION)
3391 unsigned int nPointer;
3392 memcpy(&nPointer, &pnode, sizeof(nPointer));
3393 uint256 hashKey = hashRand ^ nPointer;
3394 hashKey = Hash(BEGIN(hashKey), END(hashKey));
3395 mapMix.insert(make_pair(hashKey, pnode));
3397 int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
3398 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
3399 ((*mi).second)->PushAddress(addr);
3402 // Do not store addresses outside our network
3404 vAddrOk.push_back(addr);
3406 addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
3407 if (vAddr.size() < 1000)
3408 pfrom->fGetAddr = false;
3409 if (pfrom->fOneShot)
3410 pfrom->fDisconnect = true;
3413 else if (strCommand == "inv")
3417 if (vInv.size() > MAX_INV_SZ)
3419 pfrom->Misbehaving(20);
3420 return error("message inv size() = %"PRIszu"", vInv.size());
3423 // find last block in inv vector
3424 unsigned int nLastBlock = (unsigned int)(-1);
3425 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
3426 if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
3427 nLastBlock = vInv.size() - 1 - nInv;
3432 for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
3434 const CInv &inv = vInv[nInv];
3438 pfrom->AddInventoryKnown(inv);
3440 bool fAlreadyHave = AlreadyHave(txdb, inv);
3442 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
3446 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
3447 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
3448 } else if (nInv == nLastBlock) {
3449 // In case we are on a very long side-chain, it is possible that we already have
3450 // the last block in an inv bundle sent in response to getblocks. Try to detect
3451 // this situation and push another getblocks to continue.
3452 pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
3454 printf("force request: %s\n", inv.ToString().c_str());
3457 // Track requests for our stuff
3458 Inventory(inv.hash);
3463 else if (strCommand == "getdata")
3467 if (vInv.size() > MAX_INV_SZ)
3469 pfrom->Misbehaving(20);
3470 return error("message getdata size() = %"PRIszu"", vInv.size());
3473 if (fDebugNet || (vInv.size() != 1))
3474 printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
3476 BOOST_FOREACH(const CInv& inv, vInv)
3480 if (fDebugNet || (vInv.size() == 1))
3481 printf("received getdata for: %s\n", inv.ToString().c_str());
3483 if (inv.type == MSG_BLOCK)
3485 // Send block from disk
3486 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
3487 if (mi != mapBlockIndex.end())
3490 block.ReadFromDisk((*mi).second);
3491 pfrom->PushMessage("block", block);
3493 // Trigger them to send a getblocks request for the next batch of inventory
3494 if (inv.hash == pfrom->hashContinue)
3496 // ppcoin: send latest proof-of-work block to allow the
3497 // download node to accept as orphan (proof-of-stake
3498 // block might be rejected by stake connection check)
3500 vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
3501 pfrom->PushMessage("inv", vInv);
3502 pfrom->hashContinue = 0;
3506 else if (inv.IsKnownType())
3508 // Send stream from relay memory
3509 bool pushed = false;
3512 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
3513 if (mi != mapRelay.end()) {
3514 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
3518 if (!pushed && inv.type == MSG_TX) {
3520 if (mempool.exists(inv.hash)) {
3521 CTransaction tx = mempool.lookup(inv.hash);
3522 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
3525 pfrom->PushMessage("tx", ss);
3530 // Track requests for our stuff
3531 Inventory(inv.hash);
3536 else if (strCommand == "getblocks")
3538 CBlockLocator locator;
3540 vRecv >> locator >> hashStop;
3542 // Find the last block the caller has in the main chain
3543 CBlockIndex* pindex = locator.GetBlockIndex();
3545 // Send the rest of the chain
3547 pindex = pindex->pnext;
3549 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
3550 for (; pindex; pindex = pindex->pnext)
3552 if (pindex->GetBlockHash() == hashStop)
3554 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3555 // ppcoin: tell downloading node about the latest block if it's
3556 // without risk being rejected due to stake connection check
3557 if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
3558 pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
3561 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
3564 // When this block is requested, we'll send an inv that'll make them
3565 // getblocks the next batch of inventory.
3566 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
3567 pfrom->hashContinue = pindex->GetBlockHash();
3572 else if (strCommand == "checkpoint")
3574 CSyncCheckpoint checkpoint;
3575 vRecv >> checkpoint;
3577 if (checkpoint.ProcessSyncCheckpoint(pfrom))
3580 pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
3582 BOOST_FOREACH(CNode* pnode, vNodes)
3583 checkpoint.RelayTo(pnode);
3587 else if (strCommand == "getheaders")
3589 CBlockLocator locator;
3591 vRecv >> locator >> hashStop;
3593 CBlockIndex* pindex = NULL;
3594 if (locator.IsNull())
3596 // If locator is null, return the hashStop block
3597 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
3598 if (mi == mapBlockIndex.end())
3600 pindex = (*mi).second;
3604 // Find the last block the caller has in the main chain
3605 pindex = locator.GetBlockIndex();
3607 pindex = pindex->pnext;
3610 vector<CBlock> vHeaders;
3612 printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
3613 for (; pindex; pindex = pindex->pnext)
3615 vHeaders.push_back(pindex->GetBlockHeader());
3616 if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
3619 pfrom->PushMessage("headers", vHeaders);
3623 else if (strCommand == "tx")
3625 vector<uint256> vWorkQueue;
3626 vector<uint256> vEraseQueue;
3627 CDataStream vMsg(vRecv);
3632 CInv inv(MSG_TX, tx.GetHash());
3633 pfrom->AddInventoryKnown(inv);
3635 bool fMissingInputs = false;
3636 if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
3638 SyncWithWallets(tx, NULL, true);
3639 RelayTransaction(tx, inv.hash);
3640 mapAlreadyAskedFor.erase(inv);
3641 vWorkQueue.push_back(inv.hash);
3642 vEraseQueue.push_back(inv.hash);
3644 // Recursively process any orphan transactions that depended on this one
3645 for (unsigned int i = 0; i < vWorkQueue.size(); i++)
3647 uint256 hashPrev = vWorkQueue[i];
3648 for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
3649 mi != mapOrphanTransactionsByPrev[hashPrev].end();
3652 const uint256& orphanTxHash = *mi;
3653 CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash];
3654 bool fMissingInputs2 = false;
3656 if (orphanTx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
3658 printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3659 SyncWithWallets(tx, NULL, true);
3660 RelayTransaction(orphanTx, orphanTxHash);
3661 mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash));
3662 vWorkQueue.push_back(orphanTxHash);
3663 vEraseQueue.push_back(orphanTxHash);
3665 else if (!fMissingInputs2)
3668 vEraseQueue.push_back(orphanTxHash);
3669 printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str());
3674 BOOST_FOREACH(uint256 hash, vEraseQueue)
3675 EraseOrphanTx(hash);
3677 else if (fMissingInputs)
3681 // DoS prevention: do not allow mapOrphanTransactions to grow unbounded
3682 unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
3684 printf("mapOrphan overflow, removed %u tx\n", nEvicted);
3686 if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
3690 else if (strCommand == "block")
3694 uint256 hashBlock = block.GetHash();
3696 printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str());
3699 CInv inv(MSG_BLOCK, hashBlock);
3700 pfrom->AddInventoryKnown(inv);
3702 if (ProcessBlock(pfrom, &block))
3703 mapAlreadyAskedFor.erase(inv);
3704 if (block.nDoS) pfrom->Misbehaving(block.nDoS);
3708 else if (strCommand == "getaddr")
3710 // Don't return addresses older than nCutOff timestamp
3711 int64 nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60);
3712 pfrom->vAddrToSend.clear();
3713 vector<CAddress> vAddr = addrman.GetAddr();
3714 BOOST_FOREACH(const CAddress &addr, vAddr)
3715 if(addr.nTime > nCutOff)
3716 pfrom->PushAddress(addr);
3720 else if (strCommand == "mempool")
3722 std::vector<uint256> vtxid;
3723 mempool.queryHashes(vtxid);
3725 for (unsigned int i = 0; i < vtxid.size(); i++) {
3726 CInv inv(MSG_TX, vtxid[i]);
3727 vInv.push_back(inv);
3728 if (i == (MAX_INV_SZ - 1))
3731 if (vInv.size() > 0)
3732 pfrom->PushMessage("inv", vInv);
3736 else if (strCommand == "checkorder")
3741 if (!GetBoolArg("-allowreceivebyip"))
3743 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
3750 /// we have a chance to check the order here
3752 // Keep giving the same key to the same ip until they use it
3753 if (!mapReuseKey.count(pfrom->addr))
3754 pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
3756 // Send back approval of order and pubkey to use
3757 CScript scriptPubKey;
3758 scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
3759 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
3763 else if (strCommand == "reply")
3768 CRequestTracker tracker;
3770 LOCK(pfrom->cs_mapRequests);
3771 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
3772 if (mi != pfrom->mapRequests.end())
3774 tracker = (*mi).second;
3775 pfrom->mapRequests.erase(mi);
3778 if (!tracker.IsNull())
3779 tracker.fn(tracker.param1, vRecv);
3783 else if (strCommand == "ping")
3785 if (pfrom->nVersion > BIP0031_VERSION)
3789 // Echo the message back with the nonce. This allows for two useful features:
3791 // 1) A remote node can quickly check if the connection is operational
3792 // 2) Remote nodes can measure the latency of the network thread. If this node
3793 // is overloaded it won't respond to pings quickly and the remote node can
3794 // avoid sending us more work, like chain download requests.
3796 // The nonce stops the remote getting confused between different pings: without
3797 // it, if the remote node sends a ping once per second and this node takes 5
3798 // seconds to respond to each, the 5th ping the remote sends would appear to
3799 // return very quickly.
3800 pfrom->PushMessage("pong", nonce);
3805 else if (strCommand == "alert")
3810 uint256 alertHash = alert.GetHash();
3811 if (pfrom->setKnown.count(alertHash) == 0)
3813 if (alert.ProcessAlert())
3816 pfrom->setKnown.insert(alertHash);
3819 BOOST_FOREACH(CNode* pnode, vNodes)
3820 alert.RelayTo(pnode);
3824 // Small DoS penalty so peers that send us lots of
3825 // duplicate/expired/invalid-signature/whatever alerts
3826 // eventually get banned.
3827 // This isn't a Misbehaving(100) (immediate ban) because the
3828 // peer might be an older or different implementation with
3829 // a different signature key, etc.
3830 pfrom->Misbehaving(10);
3838 // Ignore unknown commands for extensibility
3842 // Update the last seen time for this node's address
3843 if (pfrom->fNetworkNode)
3844 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
3845 AddressCurrentlyConnected(pfrom->addr);
3851 bool ProcessMessages(CNode* pfrom)
3853 CDataStream& vRecv = pfrom->vRecv;
3857 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
3861 // (4) message start
3870 // Don't bother if send buffer is too full to respond anyway
3871 if (pfrom->vSend.size() >= SendBufferSize())
3874 // Scan for message start
3875 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
3876 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
3877 if (vRecv.end() - pstart < nHeaderSize)
3879 if ((int)vRecv.size() > nHeaderSize)
3881 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
3882 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
3886 if (pstart - vRecv.begin() > 0)
3887 printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
3888 vRecv.erase(vRecv.begin(), pstart);
3891 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
3896 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
3899 string strCommand = hdr.GetCommand();
3902 unsigned int nMessageSize = hdr.nMessageSize;
3903 if (nMessageSize > MAX_SIZE)
3905 printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
3908 if (nMessageSize > vRecv.size())
3910 // Rewind and wait for rest of message
3911 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
3916 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
3917 unsigned int nChecksum = 0;
3918 memcpy(&nChecksum, &hash, sizeof(nChecksum));
3919 if (nChecksum != hdr.nChecksum)
3921 printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
3922 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
3926 // Copy message to its own buffer
3927 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
3928 vRecv.ignore(nMessageSize);
3936 fRet = ProcessMessage(pfrom, strCommand, vMsg);
3941 catch (std::ios_base::failure& e)
3943 if (strstr(e.what(), "end of data"))
3945 // Allow exceptions from under-length message on vRecv
3946 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());
3948 else if (strstr(e.what(), "size too large"))
3950 // Allow exceptions from over-long size
3951 printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
3955 PrintExceptionContinue(&e, "ProcessMessages()");
3958 catch (std::exception& e) {
3959 PrintExceptionContinue(&e, "ProcessMessages()");
3961 PrintExceptionContinue(NULL, "ProcessMessages()");
3965 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
3973 bool SendMessages(CNode* pto, bool fSendTrickle)
3975 TRY_LOCK(cs_main, lockMain);
3977 // Don't send anything until we get their version message
3978 if (pto->nVersion == 0)
3981 // Keep-alive ping. We send a nonce of zero because we don't use it anywhere
3983 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
3985 if (pto->nVersion > BIP0031_VERSION)
3986 pto->PushMessage("ping", nonce);
3988 pto->PushMessage("ping");
3992 if (pto->fStartSync) {
3993 pto->fStartSync = false;
3994 pto->PushGetBlocks(pindexBest, uint256(0));
3997 // Resend wallet transactions that haven't gotten in a block yet
3998 ResendWalletTransactions();
4000 // Address refresh broadcast
4001 static int64 nLastRebroadcast;
4002 if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
4006 BOOST_FOREACH(CNode* pnode, vNodes)
4008 // Periodically clear setAddrKnown to allow refresh broadcasts
4009 if (nLastRebroadcast)
4010 pnode->setAddrKnown.clear();
4012 // Rebroadcast our address
4015 CAddress addr = GetLocalAddress(&pnode->addr);
4016 if (addr.IsRoutable())
4017 pnode->PushAddress(addr);
4021 nLastRebroadcast = GetTime();
4029 vector<CAddress> vAddr;
4030 vAddr.reserve(pto->vAddrToSend.size());
4031 BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
4033 // returns true if wasn't already contained in the set
4034 if (pto->setAddrKnown.insert(addr).second)
4036 vAddr.push_back(addr);
4037 // receiver rejects addr messages larger than 1000
4038 if (vAddr.size() >= 1000)
4040 pto->PushMessage("addr", vAddr);
4045 pto->vAddrToSend.clear();
4047 pto->PushMessage("addr", vAddr);
4052 // Message: inventory
4055 vector<CInv> vInvWait;
4057 LOCK(pto->cs_inventory);
4058 vInv.reserve(pto->vInventoryToSend.size());
4059 vInvWait.reserve(pto->vInventoryToSend.size());
4060 BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
4062 if (pto->setInventoryKnown.count(inv))
4065 // trickle out tx inv to protect privacy
4066 if (inv.type == MSG_TX && !fSendTrickle)
4068 // 1/4 of tx invs blast to all immediately
4069 static uint256 hashSalt;
4071 hashSalt = GetRandHash();
4072 uint256 hashRand = inv.hash ^ hashSalt;
4073 hashRand = Hash(BEGIN(hashRand), END(hashRand));
4074 bool fTrickleWait = ((hashRand & 3) != 0);
4076 // always trickle our own transactions
4080 if (GetTransaction(inv.hash, wtx))
4082 fTrickleWait = true;
4087 vInvWait.push_back(inv);
4092 // returns true if wasn't already contained in the set
4093 if (pto->setInventoryKnown.insert(inv).second)
4095 vInv.push_back(inv);
4096 if (vInv.size() >= 1000)
4098 pto->PushMessage("inv", vInv);
4103 pto->vInventoryToSend = vInvWait;
4106 pto->PushMessage("inv", vInv);
4112 vector<CInv> vGetData;
4113 int64 nNow = GetTime() * 1000000;
4115 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
4117 const CInv& inv = (*pto->mapAskFor.begin()).second;
4118 if (!AlreadyHave(txdb, inv))
4121 printf("sending getdata: %s\n", inv.ToString().c_str());
4122 vGetData.push_back(inv);
4123 if (vGetData.size() >= 1000)
4125 pto->PushMessage("getdata", vGetData);
4128 mapAlreadyAskedFor[inv] = nNow;
4130 pto->mapAskFor.erase(pto->mapAskFor.begin());
4132 if (!vGetData.empty())
4133 pto->PushMessage("getdata", vGetData);