1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #include "cryptopp/sha.h"
16 CCriticalSection cs_main;
18 map<uint256, CTransaction> mapTransactions;
19 CCriticalSection cs_mapTransactions;
20 unsigned int nTransactionsUpdated = 0;
21 map<COutPoint, CInPoint> mapNextTx;
23 map<uint256, CBlockIndex*> mapBlockIndex;
24 uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
25 CBigNum bnProofOfWorkLimit(~uint256(0) >> 32);
26 CBlockIndex* pindexGenesisBlock = NULL;
28 CBigNum bnBestChainWork = 0;
29 CBigNum bnBestInvalidWork = 0;
30 uint256 hashBestChain = 0;
31 CBlockIndex* pindexBest = NULL;
32 int64 nTimeBestReceived = 0;
34 map<uint256, CBlock*> mapOrphanBlocks;
35 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
37 map<uint256, CDataStream*> mapOrphanTransactions;
38 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
40 map<uint256, CWalletTx> mapWallet;
41 vector<uint256> vWalletUpdated;
42 CCriticalSection cs_mapWallet;
44 map<vector<unsigned char>, CPrivKey> mapKeys;
45 map<uint160, vector<unsigned char> > mapPubKeys;
46 CCriticalSection cs_mapKeys;
49 map<uint256, int> mapRequestCount;
50 CCriticalSection cs_mapRequestCount;
52 map<string, string> mapAddressBook;
53 CCriticalSection cs_mapAddressBook;
55 vector<unsigned char> vchDefaultKey;
61 int fGenerateBitcoins = false;
62 int64 nTransactionFee = 0;
63 CAddress addrIncoming;
64 int fLimitProcessors = false;
65 int nLimitProcessors = 1;
66 int fMinimizeToTray = true;
67 int fMinimizeOnClose = true;
74 //////////////////////////////////////////////////////////////////////////////
79 bool AddKey(const CKey& key)
81 CRITICAL_BLOCK(cs_mapKeys)
83 mapKeys[key.GetPubKey()] = key.GetPrivKey();
84 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
86 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
89 vector<unsigned char> GenerateNewKey()
95 throw runtime_error("GenerateNewKey() : AddKey failed");
96 return key.GetPubKey();
102 //////////////////////////////////////////////////////////////////////////////
107 bool AddToWallet(const CWalletTx& wtxIn)
109 uint256 hash = wtxIn.GetHash();
110 CRITICAL_BLOCK(cs_mapWallet)
112 // Inserts only if not already there, returns tx inserted or tx found
113 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
114 CWalletTx& wtx = (*ret.first).second;
115 bool fInsertedNew = ret.second;
117 wtx.nTimeReceived = GetAdjustedTime();
119 bool fUpdated = false;
123 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
125 wtx.hashBlock = wtxIn.hashBlock;
128 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
130 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
131 wtx.nIndex = wtxIn.nIndex;
134 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
136 wtx.fFromMe = wtxIn.fFromMe;
139 if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
141 wtx.fSpent = wtxIn.fSpent;
147 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
150 if (fInsertedNew || fUpdated)
151 if (!wtx.WriteToDisk())
154 // If default receiving address gets used, replace it with a new one
155 CScript scriptDefaultKey;
156 scriptDefaultKey.SetBitcoinAddress(vchDefaultKey);
157 foreach(const CTxOut& txout, wtx.vout)
159 if (txout.scriptPubKey == scriptDefaultKey)
162 vchDefaultKey = walletdb.GetKeyFromKeyPool();
163 walletdb.WriteDefaultKey(vchDefaultKey);
164 walletdb.WriteName(PubKeyToAddress(vchDefaultKey), "");
169 vWalletUpdated.push_back(hash);
177 bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
179 if (tx.IsMine() || mapWallet.count(tx.GetHash()))
182 // Get merkle branch if transaction was found in a block
184 wtx.SetMerkleBranch(pblock);
185 return AddToWallet(wtx);
190 bool EraseFromWallet(uint256 hash)
192 CRITICAL_BLOCK(cs_mapWallet)
194 if (mapWallet.erase(hash))
195 CWalletDB().EraseTx(hash);
200 void WalletUpdateSpent(const COutPoint& prevout)
202 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
203 // Update the wallet spent flag if it doesn't know due to wallet.dat being
204 // restored from backup or the user making copies of wallet.dat.
205 CRITICAL_BLOCK(cs_mapWallet)
207 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
208 if (mi != mapWallet.end())
210 CWalletTx& wtx = (*mi).second;
211 if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
213 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
216 vWalletUpdated.push_back(prevout.hash);
229 //////////////////////////////////////////////////////////////////////////////
231 // mapOrphanTransactions
234 void AddOrphanTx(const CDataStream& vMsg)
237 CDataStream(vMsg) >> tx;
238 uint256 hash = tx.GetHash();
239 if (mapOrphanTransactions.count(hash))
241 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
242 foreach(const CTxIn& txin, tx.vin)
243 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
246 void EraseOrphanTx(uint256 hash)
248 if (!mapOrphanTransactions.count(hash))
250 const CDataStream* pvMsg = mapOrphanTransactions[hash];
252 CDataStream(*pvMsg) >> tx;
253 foreach(const CTxIn& txin, tx.vin)
255 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
256 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
258 if ((*mi).second == pvMsg)
259 mapOrphanTransactionsByPrev.erase(mi++);
265 mapOrphanTransactions.erase(hash);
275 //////////////////////////////////////////////////////////////////////////////
280 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
283 if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
285 if (!ReadFromDisk(txindexRet.pos))
287 if (prevout.n >= vout.size())
295 bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
298 return ReadFromDisk(txdb, prevout, txindex);
301 bool CTransaction::ReadFromDisk(COutPoint prevout)
305 return ReadFromDisk(txdb, prevout, txindex);
308 bool CTxIn::IsMine() const
310 CRITICAL_BLOCK(cs_mapWallet)
312 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
313 if (mi != mapWallet.end())
315 const CWalletTx& prev = (*mi).second;
316 if (prevout.n < prev.vout.size())
317 if (prev.vout[prevout.n].IsMine())
324 int64 CTxIn::GetDebit() const
326 CRITICAL_BLOCK(cs_mapWallet)
328 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
329 if (mi != mapWallet.end())
331 const CWalletTx& prev = (*mi).second;
332 if (prevout.n < prev.vout.size())
333 if (prev.vout[prevout.n].IsMine())
334 return prev.vout[prevout.n].nValue;
340 int64 CWalletTx::GetTxTime() const
342 if (!fTimeReceivedIsTxTime && hashBlock != 0)
344 // If we did not receive the transaction directly, we rely on the block's
345 // time to figure out when it happened. We use the median over a range
346 // of blocks to try to filter out inaccurate block times.
347 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
348 if (mi != mapBlockIndex.end())
350 CBlockIndex* pindex = (*mi).second;
352 return pindex->GetMedianTime();
355 return nTimeReceived;
358 int CWalletTx::GetRequestCount() const
360 // Returns -1 if it wasn't being tracked
362 CRITICAL_BLOCK(cs_mapRequestCount)
369 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
370 if (mi != mapRequestCount.end())
371 nRequests = (*mi).second;
376 // Did anyone request this transaction?
377 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
378 if (mi != mapRequestCount.end())
380 nRequests = (*mi).second;
382 // How about the block it's in?
383 if (nRequests == 0 && hashBlock != 0)
385 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
386 if (mi != mapRequestCount.end())
387 nRequests = (*mi).second;
389 nRequests = 1; // If it's in someone else's block it must have got out
400 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
412 // Load the block this tx is in
414 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
416 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
421 // Update the tx's hashBlock
422 hashBlock = pblock->GetHash();
424 // Locate the transaction
425 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
426 if (pblock->vtx[nIndex] == *(CTransaction*)this)
428 if (nIndex == pblock->vtx.size())
430 vMerkleBranch.clear();
432 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
436 // Fill in merkle branch
437 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
440 // Is the tx in a block that's in the main chain
441 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
442 if (mi == mapBlockIndex.end())
444 CBlockIndex* pindex = (*mi).second;
445 if (!pindex || !pindex->IsInMainChain())
448 return pindexBest->nHeight - pindex->nHeight + 1;
453 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
457 const int COPY_DEPTH = 3;
458 if (SetMerkleBranch() < COPY_DEPTH)
460 vector<uint256> vWorkQueue;
461 foreach(const CTxIn& txin, vin)
462 vWorkQueue.push_back(txin.prevout.hash);
464 // This critsect is OK because txdb is already open
465 CRITICAL_BLOCK(cs_mapWallet)
467 map<uint256, const CMerkleTx*> mapWalletPrev;
468 set<uint256> setAlreadyDone;
469 for (int i = 0; i < vWorkQueue.size(); i++)
471 uint256 hash = vWorkQueue[i];
472 if (setAlreadyDone.count(hash))
474 setAlreadyDone.insert(hash);
477 if (mapWallet.count(hash))
479 tx = mapWallet[hash];
480 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
481 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
483 else if (mapWalletPrev.count(hash))
485 tx = *mapWalletPrev[hash];
487 else if (!fClient && txdb.ReadDiskTx(hash, tx))
493 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
497 int nDepth = tx.SetMerkleBranch();
498 vtxPrev.push_back(tx);
500 if (nDepth < COPY_DEPTH)
501 foreach(const CTxIn& txin, tx.vin)
502 vWorkQueue.push_back(txin.prevout.hash);
507 reverse(vtxPrev.begin(), vtxPrev.end());
520 bool CTransaction::CheckTransaction() const
522 // Basic checks that don't depend on any context
523 if (vin.empty() || vout.empty())
524 return error("CTransaction::CheckTransaction() : vin or vout empty");
527 if (::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
528 return error("CTransaction::CheckTransaction() : size limits failed");
530 // Check for negative or overflow output values
532 foreach(const CTxOut& txout, vout)
534 if (txout.nValue < 0)
535 return error("CTransaction::CheckTransaction() : txout.nValue negative");
536 if (txout.nValue > MAX_MONEY)
537 return error("CTransaction::CheckTransaction() : txout.nValue too high");
538 nValueOut += txout.nValue;
539 if (!MoneyRange(nValueOut))
540 return error("CTransaction::CheckTransaction() : txout total out of range");
545 if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
546 return error("CTransaction::CheckTransaction() : coinbase script size");
550 foreach(const CTxIn& txin, vin)
551 if (txin.prevout.IsNull())
552 return error("CTransaction::CheckTransaction() : prevout is null");
558 bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
561 *pfMissingInputs = false;
563 if (!CheckTransaction())
564 return error("AcceptToMemoryPool() : CheckTransaction failed");
566 // Coinbase is only valid in a block, not as a loose transaction
568 return error("AcceptToMemoryPool() : coinbase as individual tx");
570 // To help v0.1.5 clients who would see it as a negative number
571 if ((int64)nLockTime > INT_MAX)
572 return error("AcceptToMemoryPool() : not accepting nLockTime beyond 2038 yet");
574 // Rather not work on nonstandard transactions
575 if (GetSigOpCount() > 2 || ::GetSerializeSize(*this, SER_NETWORK) < 100)
576 return error("AcceptToMemoryPool() : nonstandard transaction");
578 // Do we already have it?
579 uint256 hash = GetHash();
580 CRITICAL_BLOCK(cs_mapTransactions)
581 if (mapTransactions.count(hash))
584 if (txdb.ContainsTx(hash))
587 // Check for conflicts with in-memory transactions
588 CTransaction* ptxOld = NULL;
589 for (int i = 0; i < vin.size(); i++)
591 COutPoint outpoint = vin[i].prevout;
592 if (mapNextTx.count(outpoint))
594 // Disable replacement feature for now
597 // Allow replacing with a newer version of the same transaction
600 ptxOld = mapNextTx[outpoint].ptx;
601 if (ptxOld->IsFinal())
603 if (!IsNewerThan(*ptxOld))
605 for (int i = 0; i < vin.size(); i++)
607 COutPoint outpoint = vin[i].prevout;
608 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
615 // Check against previous transactions
616 map<uint256, CTxIndex> mapUnused;
618 if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), pindexBest, nFees, false, false))
621 *pfMissingInputs = true;
622 return error("AcceptToMemoryPool() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
625 // Store transaction in memory
626 CRITICAL_BLOCK(cs_mapTransactions)
630 printf("AcceptToMemoryPool() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
631 ptxOld->RemoveFromMemoryPool();
633 AddToMemoryPoolUnchecked();
636 ///// are we sure this is ok when loading transactions or restoring block txes
637 // If updated, erase old tx from wallet
639 EraseFromWallet(ptxOld->GetHash());
641 printf("AcceptToMemoryPool(): accepted %s\n", hash.ToString().substr(0,10).c_str());
646 bool CTransaction::AddToMemoryPoolUnchecked()
648 // Add to memory pool without checking anything. Don't call this directly,
649 // call AcceptToMemoryPool to properly check the transaction first.
650 CRITICAL_BLOCK(cs_mapTransactions)
652 uint256 hash = GetHash();
653 mapTransactions[hash] = *this;
654 for (int i = 0; i < vin.size(); i++)
655 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
656 nTransactionsUpdated++;
662 bool CTransaction::RemoveFromMemoryPool()
664 // Remove transaction from memory pool
665 CRITICAL_BLOCK(cs_mapTransactions)
667 foreach(const CTxIn& txin, vin)
668 mapNextTx.erase(txin.prevout);
669 mapTransactions.erase(GetHash());
670 nTransactionsUpdated++;
680 int CMerkleTx::GetDepthInMainChain(int& nHeightRet) const
682 if (hashBlock == 0 || nIndex == -1)
685 // Find the block it claims to be in
686 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
687 if (mi == mapBlockIndex.end())
689 CBlockIndex* pindex = (*mi).second;
690 if (!pindex || !pindex->IsInMainChain())
693 // Make sure the merkle branch connects to this block
694 if (!fMerkleVerified)
696 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
698 fMerkleVerified = true;
701 nHeightRet = pindex->nHeight;
702 return pindexBest->nHeight - pindex->nHeight + 1;
706 int CMerkleTx::GetBlocksToMaturity() const
710 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
714 bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
718 if (!IsInMainChain() && !ClientConnectInputs())
720 return CTransaction::AcceptToMemoryPool(txdb, false);
724 return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
730 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
732 CRITICAL_BLOCK(cs_mapTransactions)
734 // Add previous supporting transactions first
735 foreach(CMerkleTx& tx, vtxPrev)
737 if (!tx.IsCoinBase())
739 uint256 hash = tx.GetHash();
740 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
741 tx.AcceptToMemoryPool(txdb, fCheckInputs);
744 return AcceptToMemoryPool(txdb, fCheckInputs);
749 void ReacceptWalletTransactions()
752 CRITICAL_BLOCK(cs_mapWallet)
754 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
756 CWalletTx& wtx = item.second;
757 if (wtx.fSpent && wtx.IsCoinBase())
761 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
763 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
766 if (txindex.vSpent.size() != wtx.vout.size())
768 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
771 for (int i = 0; i < txindex.vSpent.size(); i++)
773 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
775 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
785 // Reaccept any txes of ours that aren't already in a block
786 if (!wtx.IsCoinBase())
787 wtx.AcceptWalletTransaction(txdb, false);
794 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
796 foreach(const CMerkleTx& tx, vtxPrev)
798 if (!tx.IsCoinBase())
800 uint256 hash = tx.GetHash();
801 if (!txdb.ContainsTx(hash))
802 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
807 uint256 hash = GetHash();
808 if (!txdb.ContainsTx(hash))
810 printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
811 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
816 void ResendWalletTransactions()
818 // Do this infrequently and randomly to avoid giving away
819 // that these are our transactions.
820 static int64 nNextTime;
821 if (GetTime() < nNextTime)
823 bool fFirst = (nNextTime == 0);
824 nNextTime = GetTime() + GetRand(30 * 60);
828 // Only do it if there's been a new block since last time
829 static int64 nLastTime;
830 if (nTimeBestReceived < nLastTime)
832 nLastTime = GetTime();
834 // Rebroadcast any of our txes that aren't in a block yet
835 printf("ResendWalletTransactions()\n");
837 CRITICAL_BLOCK(cs_mapWallet)
839 // Sort them in chronological order
840 multimap<unsigned int, CWalletTx*> mapSorted;
841 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
843 CWalletTx& wtx = item.second;
844 // Don't rebroadcast until it's had plenty of time that
845 // it should have gotten in already by now.
846 if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
847 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
849 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
851 CWalletTx& wtx = *item.second;
852 wtx.RelayWalletTransaction(txdb);
866 //////////////////////////////////////////////////////////////////////////////
868 // CBlock and CBlockIndex
871 bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
873 if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
875 if (GetHash() != pindex->GetBlockHash())
876 return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
880 uint256 GetOrphanRoot(const CBlock* pblock)
882 // Work back to the first block in the orphan chain
883 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
884 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
885 return pblock->GetHash();
888 int64 GetBlockValue(int nHeight, int64 nFees)
890 int64 nSubsidy = 50 * COIN;
892 // Subsidy is cut in half every 4 years
893 nSubsidy >>= (nHeight / 210000);
895 return nSubsidy + nFees;
898 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
900 const int64 nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
901 const int64 nTargetSpacing = 10 * 60;
902 const int64 nInterval = nTargetTimespan / nTargetSpacing;
905 if (pindexLast == NULL)
906 return bnProofOfWorkLimit.GetCompact();
908 // Only change once per interval
909 if ((pindexLast->nHeight+1) % nInterval != 0)
910 return pindexLast->nBits;
912 // Go back by what we want to be 14 days worth of blocks
913 const CBlockIndex* pindexFirst = pindexLast;
914 for (int i = 0; pindexFirst && i < nInterval-1; i++)
915 pindexFirst = pindexFirst->pprev;
918 // Limit adjustment step
919 int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
920 printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
921 if (nActualTimespan < nTargetTimespan/4)
922 nActualTimespan = nTargetTimespan/4;
923 if (nActualTimespan > nTargetTimespan*4)
924 nActualTimespan = nTargetTimespan*4;
928 bnNew.SetCompact(pindexLast->nBits);
929 bnNew *= nActualTimespan;
930 bnNew /= nTargetTimespan;
932 if (bnNew > bnProofOfWorkLimit)
933 bnNew = bnProofOfWorkLimit;
936 printf("GetNextWorkRequired RETARGET\n");
937 printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
938 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
939 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
941 return bnNew.GetCompact();
944 bool CheckProofOfWork(uint256 hash, unsigned int nBits)
947 bnTarget.SetCompact(nBits);
950 if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
951 return error("CheckProofOfWork() : nBits below minimum work");
953 // Check proof of work matches claimed amount
954 if (hash > bnTarget.getuint256())
955 return error("CheckProofOfWork() : hash doesn't match nBits");
960 bool IsInitialBlockDownload()
962 if (pindexBest == NULL || (!fTestNet && nBestHeight < 74000))
964 static int64 nLastUpdate;
965 static CBlockIndex* pindexLastBest;
966 if (pindexBest != pindexLastBest)
968 pindexLastBest = pindexBest;
969 nLastUpdate = GetTime();
971 return (GetTime() - nLastUpdate < 10 &&
972 pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
975 void InvalidChainFound(CBlockIndex* pindexNew)
977 if (pindexNew->bnChainWork > bnBestInvalidWork)
979 bnBestInvalidWork = pindexNew->bnChainWork;
980 CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
983 printf("InvalidChainFound: invalid block=%s height=%d work=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str());
984 printf("InvalidChainFound: current best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
985 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
986 printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
999 bool CTransaction::DisconnectInputs(CTxDB& txdb)
1001 // Relinquish previous transactions' spent pointers
1004 foreach(const CTxIn& txin, vin)
1006 COutPoint prevout = txin.prevout;
1008 // Get prev txindex from disk
1010 if (!txdb.ReadTxIndex(prevout.hash, txindex))
1011 return error("DisconnectInputs() : ReadTxIndex failed");
1013 if (prevout.n >= txindex.vSpent.size())
1014 return error("DisconnectInputs() : prevout.n out of range");
1016 // Mark outpoint as not spent
1017 txindex.vSpent[prevout.n].SetNull();
1020 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1021 return error("DisconnectInputs() : UpdateTxIndex failed");
1025 // Remove transaction from index
1026 if (!txdb.EraseTxIndex(*this))
1027 return error("DisconnectInputs() : EraseTxPos failed");
1033 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
1034 CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
1036 // Take over previous transactions' spent pointers
1040 for (int i = 0; i < vin.size(); i++)
1042 COutPoint prevout = vin[i].prevout;
1047 if (fMiner && mapTestPool.count(prevout.hash))
1049 // Get txindex from current proposed changes
1050 txindex = mapTestPool[prevout.hash];
1054 // Read txindex from txdb
1055 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
1057 if (!fFound && (fBlock || fMiner))
1058 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1061 CTransaction txPrev;
1062 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
1064 // Get prev tx from single transactions in memory
1065 CRITICAL_BLOCK(cs_mapTransactions)
1067 if (!mapTransactions.count(prevout.hash))
1068 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1069 txPrev = mapTransactions[prevout.hash];
1072 txindex.vSpent.resize(txPrev.vout.size());
1076 // Get prev tx from disk
1077 if (!txPrev.ReadFromDisk(txindex.pos))
1078 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
1081 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
1082 return error("ConnectInputs() : %s prevout.n out of range %d %d %d 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());
1084 // If prev is coinbase, check that it's matured
1085 if (txPrev.IsCoinBase())
1086 for (CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
1087 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
1088 return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
1091 if (!VerifySignature(txPrev, *this, i))
1092 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
1094 // Check for conflicts
1095 if (!txindex.vSpent[prevout.n].IsNull())
1096 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());
1098 // Check for negative or overflow input values
1099 nValueIn += txPrev.vout[prevout.n].nValue;
1100 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1101 return error("ConnectInputs() : txin values out of range");
1103 // Mark outpoints as spent
1104 txindex.vSpent[prevout.n] = posThisTx;
1109 if (!txdb.UpdateTxIndex(prevout.hash, txindex))
1110 return error("ConnectInputs() : UpdateTxIndex failed");
1114 mapTestPool[prevout.hash] = txindex;
1118 if (nValueIn < GetValueOut())
1119 return error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str());
1121 // Tally transaction fees
1122 int64 nTxFee = nValueIn - GetValueOut();
1124 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str());
1125 if (nTxFee < nMinFee)
1128 if (!MoneyRange(nFees))
1129 return error("ConnectInputs() : nFees out of range");
1134 // Add transaction to disk index
1135 if (!txdb.AddTxIndex(*this, posThisTx, pindexBlock->nHeight))
1136 return error("ConnectInputs() : AddTxPos failed");
1140 // Add transaction to test pool
1141 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
1148 bool CTransaction::ClientConnectInputs()
1153 // Take over previous transactions' spent pointers
1154 CRITICAL_BLOCK(cs_mapTransactions)
1157 for (int i = 0; i < vin.size(); i++)
1159 // Get prev tx from single transactions in memory
1160 COutPoint prevout = vin[i].prevout;
1161 if (!mapTransactions.count(prevout.hash))
1163 CTransaction& txPrev = mapTransactions[prevout.hash];
1165 if (prevout.n >= txPrev.vout.size())
1169 if (!VerifySignature(txPrev, *this, i))
1170 return error("ConnectInputs() : VerifySignature failed");
1172 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
1173 ///// this has to go away now that posNext is gone
1174 // // Check for conflicts
1175 // if (!txPrev.vout[prevout.n].posNext.IsNull())
1176 // return error("ConnectInputs() : prev tx already used");
1178 // // Flag outpoints as used
1179 // txPrev.vout[prevout.n].posNext = posThisTx;
1181 nValueIn += txPrev.vout[prevout.n].nValue;
1183 if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
1184 return error("ClientConnectInputs() : txin values out of range");
1186 if (GetValueOut() > nValueIn)
1196 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1198 // Disconnect in reverse order
1199 for (int i = vtx.size()-1; i >= 0; i--)
1200 if (!vtx[i].DisconnectInputs(txdb))
1203 // Update block index on disk without changing it in memory.
1204 // The memory index structure will be changed after the db commits.
1207 CDiskBlockIndex blockindexPrev(pindex->pprev);
1208 blockindexPrev.hashNext = 0;
1209 if (!txdb.WriteBlockIndex(blockindexPrev))
1210 return error("DisconnectBlock() : WriteBlockIndex failed");
1216 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
1218 // Check it again in case a previous version let a bad block in
1222 //// issue here: it doesn't know the version
1223 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
1225 map<uint256, CTxIndex> mapUnused;
1227 foreach(CTransaction& tx, vtx)
1229 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
1230 nTxPos += ::GetSerializeSize(tx, SER_DISK);
1232 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex, nFees, true, false))
1236 if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
1239 // Update block index on disk without changing it in memory.
1240 // The memory index structure will be changed after the db commits.
1243 CDiskBlockIndex blockindexPrev(pindex->pprev);
1244 blockindexPrev.hashNext = pindex->GetBlockHash();
1245 if (!txdb.WriteBlockIndex(blockindexPrev))
1246 return error("ConnectBlock() : WriteBlockIndex failed");
1249 // Watch for transactions paying to me
1250 foreach(CTransaction& tx, vtx)
1251 AddToWalletIfMine(tx, this);
1258 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
1260 printf("REORGANIZE\n");
1263 CBlockIndex* pfork = pindexBest;
1264 CBlockIndex* plonger = pindexNew;
1265 while (pfork != plonger)
1267 while (plonger->nHeight > pfork->nHeight)
1268 if (!(plonger = plonger->pprev))
1269 return error("Reorganize() : plonger->pprev is null");
1270 if (pfork == plonger)
1272 if (!(pfork = pfork->pprev))
1273 return error("Reorganize() : pfork->pprev is null");
1276 // List of what to disconnect
1277 vector<CBlockIndex*> vDisconnect;
1278 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
1279 vDisconnect.push_back(pindex);
1281 // List of what to connect
1282 vector<CBlockIndex*> vConnect;
1283 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
1284 vConnect.push_back(pindex);
1285 reverse(vConnect.begin(), vConnect.end());
1287 // Disconnect shorter branch
1288 vector<CTransaction> vResurrect;
1289 foreach(CBlockIndex* pindex, vDisconnect)
1292 if (!block.ReadFromDisk(pindex))
1293 return error("Reorganize() : ReadFromDisk for disconnect failed");
1294 if (!block.DisconnectBlock(txdb, pindex))
1295 return error("Reorganize() : DisconnectBlock failed");
1297 // Queue memory transactions to resurrect
1298 foreach(const CTransaction& tx, block.vtx)
1299 if (!tx.IsCoinBase())
1300 vResurrect.push_back(tx);
1303 // Connect longer branch
1304 vector<CTransaction> vDelete;
1305 for (int i = 0; i < vConnect.size(); i++)
1307 CBlockIndex* pindex = vConnect[i];
1309 if (!block.ReadFromDisk(pindex))
1310 return error("Reorganize() : ReadFromDisk for connect failed");
1311 if (!block.ConnectBlock(txdb, pindex))
1315 return error("Reorganize() : ConnectBlock failed");
1318 // Queue memory transactions to delete
1319 foreach(const CTransaction& tx, block.vtx)
1320 vDelete.push_back(tx);
1322 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
1323 return error("Reorganize() : WriteHashBestChain failed");
1325 // Make sure it's successfully written to disk before changing memory structure
1326 if (!txdb.TxnCommit())
1327 return error("Reorganize() : TxnCommit failed");
1329 // Disconnect shorter branch
1330 foreach(CBlockIndex* pindex, vDisconnect)
1332 pindex->pprev->pnext = NULL;
1334 // Connect longer branch
1335 foreach(CBlockIndex* pindex, vConnect)
1337 pindex->pprev->pnext = pindex;
1339 // Resurrect memory transactions that were in the disconnected branch
1340 foreach(CTransaction& tx, vResurrect)
1341 tx.AcceptToMemoryPool(txdb, false);
1343 // Delete redundant memory transactions that are in the connected branch
1344 foreach(CTransaction& tx, vDelete)
1345 tx.RemoveFromMemoryPool();
1351 bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
1353 uint256 hash = GetHash();
1356 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
1358 txdb.WriteHashBestChain(hash);
1359 if (!txdb.TxnCommit())
1360 return error("SetBestChain() : TxnCommit failed");
1361 pindexGenesisBlock = pindexNew;
1363 else if (hashPrevBlock == hashBestChain)
1365 // Adding to current best branch
1366 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
1369 InvalidChainFound(pindexNew);
1370 return error("SetBestChain() : ConnectBlock failed");
1372 if (!txdb.TxnCommit())
1373 return error("SetBestChain() : TxnCommit failed");
1375 // Add to current best branch
1376 pindexNew->pprev->pnext = pindexNew;
1378 // Delete redundant memory transactions
1379 foreach(CTransaction& tx, vtx)
1380 tx.RemoveFromMemoryPool();
1385 if (!Reorganize(txdb, pindexNew))
1388 InvalidChainFound(pindexNew);
1389 return error("SetBestChain() : Reorganize failed");
1394 hashBestChain = hash;
1395 pindexBest = pindexNew;
1396 nBestHeight = pindexBest->nHeight;
1397 bnBestChainWork = pindexNew->bnChainWork;
1398 nTimeBestReceived = GetTime();
1399 nTransactionsUpdated++;
1400 printf("SetBestChain: new best=%s height=%d work=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str());
1406 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
1408 // Check for duplicate
1409 uint256 hash = GetHash();
1410 if (mapBlockIndex.count(hash))
1411 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
1413 // Construct new block index object
1414 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
1416 return error("AddToBlockIndex() : new CBlockIndex failed");
1417 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
1418 pindexNew->phashBlock = &((*mi).first);
1419 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
1420 if (miPrev != mapBlockIndex.end())
1422 pindexNew->pprev = (*miPrev).second;
1423 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
1425 pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
1428 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
1431 if (pindexNew->bnChainWork > bnBestChainWork)
1432 if (!SetBestChain(txdb, pindexNew))
1437 if (pindexNew == pindexBest)
1439 // Notify UI to display prev block's coinbase if it was ours
1440 static uint256 hashPrevBestCoinBase;
1441 CRITICAL_BLOCK(cs_mapWallet)
1442 vWalletUpdated.push_back(hashPrevBestCoinBase);
1443 hashPrevBestCoinBase = vtx[0].GetHash();
1453 bool CBlock::CheckBlock() const
1455 // These are checks that are independent of context
1456 // that can be verified before saving an orphan block.
1459 if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK) > MAX_BLOCK_SIZE)
1460 return error("CheckBlock() : size limits failed");
1462 // Check proof of work matches claimed amount
1463 if (!CheckProofOfWork(GetHash(), nBits))
1464 return error("CheckBlock() : proof of work failed");
1467 if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
1468 return error("CheckBlock() : block timestamp too far in the future");
1470 // First transaction must be coinbase, the rest must not be
1471 if (vtx.empty() || !vtx[0].IsCoinBase())
1472 return error("CheckBlock() : first tx is not coinbase");
1473 for (int i = 1; i < vtx.size(); i++)
1474 if (vtx[i].IsCoinBase())
1475 return error("CheckBlock() : more than one coinbase");
1477 // Check transactions
1478 foreach(const CTransaction& tx, vtx)
1479 if (!tx.CheckTransaction())
1480 return error("CheckBlock() : CheckTransaction failed");
1482 // Check that it's not full of nonstandard transactions
1483 if (GetSigOpCount() > MAX_BLOCK_SIGOPS)
1484 return error("CheckBlock() : too many nonstandard transactions");
1487 if (hashMerkleRoot != BuildMerkleTree())
1488 return error("CheckBlock() : hashMerkleRoot mismatch");
1493 bool CBlock::AcceptBlock()
1495 // Check for duplicate
1496 uint256 hash = GetHash();
1497 if (mapBlockIndex.count(hash))
1498 return error("AcceptBlock() : block already in mapBlockIndex");
1500 // Get prev block index
1501 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
1502 if (mi == mapBlockIndex.end())
1503 return error("AcceptBlock() : prev block not found");
1504 CBlockIndex* pindexPrev = (*mi).second;
1505 int nHeight = pindexPrev->nHeight+1;
1507 // Check proof of work
1508 if (nBits != GetNextWorkRequired(pindexPrev))
1509 return error("AcceptBlock() : incorrect proof of work");
1511 // Check timestamp against prev
1512 if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
1513 return error("AcceptBlock() : block's timestamp is too early");
1515 // Check that all transactions are finalized
1516 foreach(const CTransaction& tx, vtx)
1517 if (!tx.IsFinal(nHeight, GetBlockTime()))
1518 return error("AcceptBlock() : contains a non-final transaction");
1520 // Check that the block chain matches the known block chain up to a checkpoint
1522 if ((nHeight == 11111 && hash != uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ||
1523 (nHeight == 33333 && hash != uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ||
1524 (nHeight == 68555 && hash != uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a")) ||
1525 (nHeight == 70567 && hash != uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a")) ||
1526 (nHeight == 74000 && hash != uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")))
1527 return error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight);
1529 // Write block to history file
1530 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
1531 return error("AcceptBlock() : out of disk space");
1533 unsigned int nBlockPos;
1534 if (!WriteToDisk(!fClient, nFile, nBlockPos))
1535 return error("AcceptBlock() : WriteToDisk failed");
1536 if (!AddToBlockIndex(nFile, nBlockPos))
1537 return error("AcceptBlock() : AddToBlockIndex failed");
1539 // Relay inventory, but don't relay old inventory during initial block download
1540 if (hashBestChain == hash)
1541 CRITICAL_BLOCK(cs_vNodes)
1542 foreach(CNode* pnode, vNodes)
1543 if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 55000))
1544 pnode->PushInventory(CInv(MSG_BLOCK, hash));
1549 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
1551 // Check for duplicate
1552 uint256 hash = pblock->GetHash();
1553 if (mapBlockIndex.count(hash))
1554 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
1555 if (mapOrphanBlocks.count(hash))
1556 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
1558 // Preliminary checks
1559 if (!pblock->CheckBlock())
1562 return error("ProcessBlock() : CheckBlock FAILED");
1565 // If don't already have its previous block, shunt it off to holding area until we get it
1566 if (!mapBlockIndex.count(pblock->hashPrevBlock))
1568 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
1569 mapOrphanBlocks.insert(make_pair(hash, pblock));
1570 mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));
1572 // Ask this guy to fill in what we're missing
1574 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));
1579 if (!pblock->AcceptBlock())
1582 return error("ProcessBlock() : AcceptBlock FAILED");
1586 // Recursively process any orphan blocks that depended on this one
1587 vector<uint256> vWorkQueue;
1588 vWorkQueue.push_back(hash);
1589 for (int i = 0; i < vWorkQueue.size(); i++)
1591 uint256 hashPrev = vWorkQueue[i];
1592 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
1593 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
1596 CBlock* pblockOrphan = (*mi).second;
1597 if (pblockOrphan->AcceptBlock())
1598 vWorkQueue.push_back(pblockOrphan->GetHash());
1599 mapOrphanBlocks.erase(pblockOrphan->GetHash());
1600 delete pblockOrphan;
1602 mapOrphanBlocksByPrev.erase(hashPrev);
1605 printf("ProcessBlock: ACCEPTED\n");
1616 template<typename Stream>
1617 bool ScanMessageStart(Stream& s)
1619 // Scan ahead to the next pchMessageStart, which should normally be immediately
1620 // at the file pointer. Leaves file pointer at end of pchMessageStart.
1622 short prevmask = s.exceptions(0);
1623 const char* p = BEGIN(pchMessageStart);
1633 s.exceptions(prevmask);
1637 p = BEGIN(pchMessageStart);
1640 if (++p == END(pchMessageStart))
1643 s.exceptions(prevmask);
1652 s.exceptions(prevmask);
1657 bool CheckDiskSpace(uint64 nAdditionalBytes)
1659 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
1661 // Check for 15MB because database could create another 10MB log file at any time
1662 if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
1665 string strMessage = _("Warning: Disk space is low ");
1666 strMiscWarning = strMessage;
1667 printf("*** %s\n", strMessage.c_str());
1668 ThreadSafeMessageBox(strMessage, "Bitcoin", wxOK | wxICON_EXCLAMATION);
1669 CreateThread(Shutdown, NULL);
1675 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
1679 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
1682 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
1684 if (fseek(file, nBlockPos, SEEK_SET) != 0)
1693 static unsigned int nCurrentBlockFile = 1;
1695 FILE* AppendBlockFile(unsigned int& nFileRet)
1700 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
1703 if (fseek(file, 0, SEEK_END) != 0)
1705 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
1706 if (ftell(file) < 0x7F000000 - MAX_SIZE)
1708 nFileRet = nCurrentBlockFile;
1712 nCurrentBlockFile++;
1716 bool LoadBlockIndex(bool fAllowNew)
1720 hashGenesisBlock = uint256("0x0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110");
1721 bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
1722 pchMessageStart[0] = 0xfa;
1723 pchMessageStart[1] = 0xbf;
1724 pchMessageStart[2] = 0xb5;
1725 pchMessageStart[3] = 0xda;
1732 if (!txdb.LoadBlockIndex())
1737 // Init with genesis block
1739 if (mapBlockIndex.empty())
1745 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
1746 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
1747 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
1748 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
1749 // vMerkleTree: 4a5e1e
1752 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
1754 txNew.vin.resize(1);
1755 txNew.vout.resize(1);
1756 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
1757 txNew.vout[0].nValue = 50 * COIN;
1758 txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
1760 block.vtx.push_back(txNew);
1761 block.hashPrevBlock = 0;
1762 block.hashMerkleRoot = block.BuildMerkleTree();
1764 block.nTime = 1231006505;
1765 block.nBits = 0x1d00ffff;
1766 block.nNonce = 2083236893;
1770 block.nTime = 1279232055;
1771 block.nBits = 0x1d07fff8;
1772 block.nNonce = 81622180;
1776 printf("%s\n", block.GetHash().ToString().c_str());
1777 printf("%s\n", hashGenesisBlock.ToString().c_str());
1778 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
1779 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
1781 assert(block.GetHash() == hashGenesisBlock);
1783 // Start new block file
1785 unsigned int nBlockPos;
1786 if (!block.WriteToDisk(!fClient, nFile, nBlockPos))
1787 return error("LoadBlockIndex() : writing genesis block to disk failed");
1788 if (!block.AddToBlockIndex(nFile, nBlockPos))
1789 return error("LoadBlockIndex() : genesis block not accepted");
1797 void PrintBlockTree()
1799 // precompute tree structure
1800 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
1801 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
1803 CBlockIndex* pindex = (*mi).second;
1804 mapNext[pindex->pprev].push_back(pindex);
1806 //while (rand() % 3 == 0)
1807 // mapNext[pindex->pprev].push_back(pindex);
1810 vector<pair<int, CBlockIndex*> > vStack;
1811 vStack.push_back(make_pair(0, pindexGenesisBlock));
1814 while (!vStack.empty())
1816 int nCol = vStack.back().first;
1817 CBlockIndex* pindex = vStack.back().second;
1820 // print split or gap
1821 if (nCol > nPrevCol)
1823 for (int i = 0; i < nCol-1; i++)
1827 else if (nCol < nPrevCol)
1829 for (int i = 0; i < nCol; i++)
1836 for (int i = 0; i < nCol; i++)
1841 block.ReadFromDisk(pindex);
1842 printf("%d (%u,%u) %s %s tx %d",
1846 block.GetHash().ToString().substr(0,20).c_str(),
1847 DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
1850 CRITICAL_BLOCK(cs_mapWallet)
1852 if (mapWallet.count(block.vtx[0].GetHash()))
1854 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1855 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1861 // put the main timechain first
1862 vector<CBlockIndex*>& vNext = mapNext[pindex];
1863 for (int i = 0; i < vNext.size(); i++)
1865 if (vNext[i]->pnext)
1867 swap(vNext[0], vNext[i]);
1873 for (int i = 0; i < vNext.size(); i++)
1874 vStack.push_back(make_pair(nCol+i, vNext[i]));
1887 //////////////////////////////////////////////////////////////////////////////
1892 map<uint256, CAlert> mapAlerts;
1893 CCriticalSection cs_mapAlerts;
1895 string GetWarnings(string strFor)
1898 string strStatusBar;
1900 if (mapArgs.count("-testsafemode"))
1903 // Misc warnings like out of disk space and clock is wrong
1904 if (strMiscWarning != "")
1907 strStatusBar = strMiscWarning;
1910 // Longer invalid proof-of-work chain
1911 if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
1914 strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
1918 CRITICAL_BLOCK(cs_mapAlerts)
1920 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1922 const CAlert& alert = item.second;
1923 if (alert.AppliesToMe() && alert.nPriority > nPriority)
1925 nPriority = alert.nPriority;
1926 strStatusBar = alert.strStatusBar;
1927 strRPC = alert.strRPCError;
1932 if (strFor == "statusbar")
1933 return strStatusBar;
1934 else if (strFor == "rpc")
1936 assert(("GetWarnings() : invalid parameter", false));
1940 bool CAlert::ProcessAlert()
1942 if (!CheckSignature())
1947 CRITICAL_BLOCK(cs_mapAlerts)
1949 // Cancel previous alerts
1950 for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
1952 const CAlert& alert = (*mi).second;
1955 printf("cancelling alert %d\n", alert.nID);
1956 mapAlerts.erase(mi++);
1958 else if (!alert.IsInEffect())
1960 printf("expiring alert %d\n", alert.nID);
1961 mapAlerts.erase(mi++);
1967 // Check if this alert has been cancelled
1968 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
1970 const CAlert& alert = item.second;
1971 if (alert.Cancels(*this))
1973 printf("alert already cancelled by %d\n", alert.nID);
1979 mapAlerts.insert(make_pair(GetHash(), *this));
1982 printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
1994 //////////////////////////////////////////////////////////////////////////////
2000 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
2004 case MSG_TX: return mapTransactions.count(inv.hash) || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
2005 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
2007 // Don't know what it is, just say we already got one
2014 // The message start string is designed to be unlikely to occur in normal data.
2015 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
2016 // a large 4-byte int at any alignment.
2017 char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
2020 bool ProcessMessages(CNode* pfrom)
2022 CDataStream& vRecv = pfrom->vRecv;
2026 // printf("ProcessMessages(%u bytes)\n", vRecv.size());
2030 // (4) message start
2039 // Scan for message start
2040 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
2041 int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
2042 if (vRecv.end() - pstart < nHeaderSize)
2044 if (vRecv.size() > nHeaderSize)
2046 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
2047 vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
2051 if (pstart - vRecv.begin() > 0)
2052 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
2053 vRecv.erase(vRecv.begin(), pstart);
2056 vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
2061 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
2064 string strCommand = hdr.GetCommand();
2067 unsigned int nMessageSize = hdr.nMessageSize;
2068 if (nMessageSize > MAX_SIZE)
2070 printf("ProcessMessage(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
2073 if (nMessageSize > vRecv.size())
2075 // Rewind and wait for rest of message
2076 vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
2081 if (vRecv.GetVersion() >= 209)
2083 uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
2084 unsigned int nChecksum = 0;
2085 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2086 if (nChecksum != hdr.nChecksum)
2088 printf("ProcessMessage(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
2089 strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
2094 // Copy message to its own buffer
2095 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
2096 vRecv.ignore(nMessageSize);
2102 CRITICAL_BLOCK(cs_main)
2103 fRet = ProcessMessage(pfrom, strCommand, vMsg);
2107 catch (std::ios_base::failure& e)
2109 if (strstr(e.what(), "end of data"))
2111 // Allow exceptions from underlength message on vRecv
2112 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
2114 else if (strstr(e.what(), "size too large"))
2116 // Allow exceptions from overlong size
2117 printf("ProcessMessage(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
2121 PrintExceptionContinue(&e, "ProcessMessage()");
2124 catch (std::exception& e) {
2125 PrintExceptionContinue(&e, "ProcessMessage()");
2127 PrintExceptionContinue(NULL, "ProcessMessage()");
2131 printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
2141 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
2143 static map<unsigned int, vector<unsigned char> > mapReuseKey;
2144 RandAddSeedPerfmon();
2146 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
2147 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
2148 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
2150 printf("dropmessagestest DROPPING RECV MESSAGE\n");
2158 if (strCommand == "version")
2160 // Each connection can only send one version message
2161 if (pfrom->nVersion != 0)
2168 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
2169 if (pfrom->nVersion == 10300)
2170 pfrom->nVersion = 300;
2171 if (pfrom->nVersion >= 106 && !vRecv.empty())
2172 vRecv >> addrFrom >> nNonce;
2173 if (pfrom->nVersion >= 106 && !vRecv.empty())
2174 vRecv >> pfrom->strSubVer;
2175 if (pfrom->nVersion >= 209 && !vRecv.empty())
2176 vRecv >> pfrom->nStartingHeight;
2178 if (pfrom->nVersion == 0)
2181 // Disconnect if we connected to ourself
2182 if (nNonce == nLocalHostNonce && nNonce > 1)
2184 printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
2185 pfrom->fDisconnect = true;
2189 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
2192 pfrom->vSend.nType |= SER_BLOCKHEADERONLY;
2193 pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;
2196 AddTimeData(pfrom->addr.ip, nTime);
2199 if (pfrom->nVersion >= 209)
2200 pfrom->PushMessage("verack");
2201 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
2202 if (pfrom->nVersion < 209)
2203 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2205 if (!pfrom->fInbound)
2207 // Advertise our address
2208 if (addrLocalHost.IsRoutable() && !fUseProxy)
2210 CAddress addr(addrLocalHost);
2211 addr.nTime = GetAdjustedTime();
2212 pfrom->PushAddress(addr);
2215 // Get recent addresses
2216 if (pfrom->nVersion >= 31402 || mapAddresses.size() < 1000)
2218 pfrom->PushMessage("getaddr");
2219 pfrom->fGetAddr = true;
2223 // Ask the first connected node for block updates
2224 static int nAskedForBlocks;
2225 if (!pfrom->fClient && (nAskedForBlocks < 1 || vNodes.size() <= 1))
2228 pfrom->PushGetBlocks(pindexBest, uint256(0));
2232 CRITICAL_BLOCK(cs_mapAlerts)
2233 foreach(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
2234 item.second.RelayTo(pfrom);
2236 pfrom->fSuccessfullyConnected = true;
2238 printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
2242 else if (pfrom->nVersion == 0)
2244 // Must have a version message before anything else
2249 else if (strCommand == "verack")
2251 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
2255 else if (strCommand == "addr")
2257 vector<CAddress> vAddr;
2260 // Don't want addr from older versions unless seeding
2261 if (pfrom->nVersion < 209)
2263 if (pfrom->nVersion < 31402 && mapAddresses.size() > 1000)
2265 if (vAddr.size() > 1000)
2266 return error("message addr size() = %d", vAddr.size());
2268 // Store the new addresses
2269 int64 nNow = GetAdjustedTime();
2270 int64 nSince = nNow - 10 * 60;
2271 foreach(CAddress& addr, vAddr)
2275 // ignore IPv6 for now, since it isn't implemented anyway
2278 if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
2279 addr.nTime = nNow - 5 * 24 * 60 * 60;
2280 AddAddress(addr, 2 * 60 * 60);
2281 pfrom->AddAddressKnown(addr);
2282 if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
2284 // Relay to a limited number of other nodes
2285 CRITICAL_BLOCK(cs_vNodes)
2287 // Use deterministic randomness to send to the same nodes for 24 hours
2288 // at a time so the setAddrKnowns of the chosen nodes prevent repeats
2289 static uint256 hashSalt;
2291 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2292 uint256 hashRand = hashSalt ^ (((int64)addr.ip)<<32) ^ ((GetTime()+addr.ip)/(24*60*60));
2293 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2294 multimap<uint256, CNode*> mapMix;
2295 foreach(CNode* pnode, vNodes)
2297 if (pnode->nVersion < 31402)
2299 unsigned int nPointer;
2300 memcpy(&nPointer, &pnode, sizeof(nPointer));
2301 uint256 hashKey = hashRand ^ nPointer;
2302 hashKey = Hash(BEGIN(hashKey), END(hashKey));
2303 mapMix.insert(make_pair(hashKey, pnode));
2305 int nRelayNodes = 2;
2306 for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
2307 ((*mi).second)->PushAddress(addr);
2311 if (vAddr.size() < 1000)
2312 pfrom->fGetAddr = false;
2316 else if (strCommand == "inv")
2320 if (vInv.size() > 50000)
2321 return error("message inv size() = %d", vInv.size());
2324 foreach(const CInv& inv, vInv)
2328 pfrom->AddInventoryKnown(inv);
2330 bool fAlreadyHave = AlreadyHave(txdb, inv);
2331 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
2335 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
2336 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
2338 // Track requests for our stuff
2339 CRITICAL_BLOCK(cs_mapRequestCount)
2341 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2342 if (mi != mapRequestCount.end())
2349 else if (strCommand == "getdata")
2353 if (vInv.size() > 50000)
2354 return error("message getdata size() = %d", vInv.size());
2356 foreach(const CInv& inv, vInv)
2360 printf("received getdata for: %s\n", inv.ToString().c_str());
2362 if (inv.type == MSG_BLOCK)
2364 // Send block from disk
2365 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
2366 if (mi != mapBlockIndex.end())
2368 //// could optimize this to send header straight from blockindex for client
2370 block.ReadFromDisk((*mi).second, !pfrom->fClient);
2371 pfrom->PushMessage("block", block);
2373 // Trigger them to send a getblocks request for the next batch of inventory
2374 if (inv.hash == pfrom->hashContinue)
2376 // Bypass PushInventory, this must send even if redundant,
2377 // and we want it right after the last block so they don't
2378 // wait for other stuff first.
2380 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
2381 pfrom->PushMessage("inv", vInv);
2382 pfrom->hashContinue = 0;
2386 else if (inv.IsKnownType())
2388 // Send stream from relay memory
2389 CRITICAL_BLOCK(cs_mapRelay)
2391 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
2392 if (mi != mapRelay.end())
2393 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
2397 // Track requests for our stuff
2398 CRITICAL_BLOCK(cs_mapRequestCount)
2400 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
2401 if (mi != mapRequestCount.end())
2408 else if (strCommand == "getblocks")
2410 CBlockLocator locator;
2412 vRecv >> locator >> hashStop;
2414 // Find the first block the caller has in the main chain
2415 CBlockIndex* pindex = locator.GetBlockIndex();
2417 // Send the rest of the chain
2419 pindex = pindex->pnext;
2420 int nLimit = 500 + locator.GetDistanceBack();
2421 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
2422 for (; pindex; pindex = pindex->pnext)
2424 if (pindex->GetBlockHash() == hashStop)
2426 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2429 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
2432 // When this block is requested, we'll send an inv that'll make them
2433 // getblocks the next batch of inventory.
2434 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
2435 pfrom->hashContinue = pindex->GetBlockHash();
2442 else if (strCommand == "tx")
2444 vector<uint256> vWorkQueue;
2445 CDataStream vMsg(vRecv);
2449 CInv inv(MSG_TX, tx.GetHash());
2450 pfrom->AddInventoryKnown(inv);
2452 bool fMissingInputs = false;
2453 if (tx.AcceptToMemoryPool(true, &fMissingInputs))
2455 AddToWalletIfMine(tx, NULL);
2456 RelayMessage(inv, vMsg);
2457 mapAlreadyAskedFor.erase(inv);
2458 vWorkQueue.push_back(inv.hash);
2460 // Recursively process any orphan transactions that depended on this one
2461 for (int i = 0; i < vWorkQueue.size(); i++)
2463 uint256 hashPrev = vWorkQueue[i];
2464 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
2465 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
2468 const CDataStream& vMsg = *((*mi).second);
2470 CDataStream(vMsg) >> tx;
2471 CInv inv(MSG_TX, tx.GetHash());
2473 if (tx.AcceptToMemoryPool(true))
2475 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2476 AddToWalletIfMine(tx, NULL);
2477 RelayMessage(inv, vMsg);
2478 mapAlreadyAskedFor.erase(inv);
2479 vWorkQueue.push_back(inv.hash);
2484 foreach(uint256 hash, vWorkQueue)
2485 EraseOrphanTx(hash);
2487 else if (fMissingInputs)
2489 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
2495 else if (strCommand == "block")
2497 auto_ptr<CBlock> pblock(new CBlock);
2501 printf("received block %s\n", pblock->GetHash().ToString().substr(0,20).c_str());
2504 CInv inv(MSG_BLOCK, pblock->GetHash());
2505 pfrom->AddInventoryKnown(inv);
2507 if (ProcessBlock(pfrom, pblock.release()))
2508 mapAlreadyAskedFor.erase(inv);
2512 else if (strCommand == "getaddr")
2514 // Nodes rebroadcast an addr every 24 hours
2515 pfrom->vAddrToSend.clear();
2516 int64 nSince = GetAdjustedTime() - 3 * 60 * 60; // in the last 3 hours
2517 CRITICAL_BLOCK(cs_mapAddresses)
2519 unsigned int nCount = 0;
2520 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2522 const CAddress& addr = item.second;
2523 if (addr.nTime > nSince)
2526 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
2528 const CAddress& addr = item.second;
2529 if (addr.nTime > nSince && GetRand(nCount) < 2500)
2530 pfrom->PushAddress(addr);
2536 else if (strCommand == "checkorder")
2540 vRecv >> hashReply >> order;
2542 if (!mapArgs.count("-allowreceivebyip") || mapArgs["-allowreceivebyip"] == "0")
2544 pfrom->PushMessage("reply", hashReply, (int)2, string(""));
2548 /// we have a chance to check the order here
2550 // Keep giving the same key to the same ip until they use it
2551 if (!mapReuseKey.count(pfrom->addr.ip))
2552 mapReuseKey[pfrom->addr.ip] = CWalletDB().GetKeyFromKeyPool();
2554 // Send back approval of order and pubkey to use
2555 CScript scriptPubKey;
2556 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
2557 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
2561 else if (strCommand == "submitorder")
2565 vRecv >> hashReply >> wtxNew;
2566 wtxNew.fFromMe = false;
2568 if (!mapArgs.count("-allowreceivebyip") || mapArgs["-allowreceivebyip"] == "0")
2570 pfrom->PushMessage("reply", hashReply, (int)2);
2575 if (!wtxNew.AcceptWalletTransaction())
2577 pfrom->PushMessage("reply", hashReply, (int)1);
2578 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
2580 wtxNew.fTimeReceivedIsTxTime = true;
2581 AddToWallet(wtxNew);
2582 wtxNew.RelayWalletTransaction();
2583 mapReuseKey.erase(pfrom->addr.ip);
2585 // Send back confirmation
2586 pfrom->PushMessage("reply", hashReply, (int)0);
2590 else if (strCommand == "reply")
2595 CRequestTracker tracker;
2596 CRITICAL_BLOCK(pfrom->cs_mapRequests)
2598 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
2599 if (mi != pfrom->mapRequests.end())
2601 tracker = (*mi).second;
2602 pfrom->mapRequests.erase(mi);
2605 if (!tracker.IsNull())
2606 tracker.fn(tracker.param1, vRecv);
2610 else if (strCommand == "ping")
2615 else if (strCommand == "alert")
2620 if (alert.ProcessAlert())
2623 pfrom->setKnown.insert(alert.GetHash());
2624 CRITICAL_BLOCK(cs_vNodes)
2625 foreach(CNode* pnode, vNodes)
2626 alert.RelayTo(pnode);
2633 // Ignore unknown commands for extensibility
2637 // Update the last seen time for this node's address
2638 if (pfrom->fNetworkNode)
2639 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
2640 AddressCurrentlyConnected(pfrom->addr);
2654 bool SendMessages(CNode* pto, bool fSendTrickle)
2656 CRITICAL_BLOCK(cs_main)
2658 // Don't send anything until we get their version message
2659 if (pto->nVersion == 0)
2663 if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty())
2664 pto->PushMessage("ping");
2666 // Resend wallet transactions that haven't gotten in a block yet
2667 ResendWalletTransactions();
2669 // Address refresh broadcast
2670 static int64 nLastRebroadcast;
2671 if (GetTime() - nLastRebroadcast > 24 * 60 * 60)
2673 nLastRebroadcast = GetTime();
2674 CRITICAL_BLOCK(cs_vNodes)
2676 foreach(CNode* pnode, vNodes)
2678 // Periodically clear setAddrKnown to allow refresh broadcasts
2679 pnode->setAddrKnown.clear();
2681 // Rebroadcast our address
2682 if (addrLocalHost.IsRoutable() && !fUseProxy)
2684 CAddress addr(addrLocalHost);
2685 addr.nTime = GetAdjustedTime();
2686 pnode->PushAddress(addr);
2692 // Clear out old addresses periodically so it's not too much work at once
2693 static int64 nLastClear;
2694 if (nLastClear == 0)
2695 nLastClear = GetTime();
2696 if (GetTime() - nLastClear > 10 * 60 && vNodes.size() >= 3)
2698 nLastClear = GetTime();
2699 CRITICAL_BLOCK(cs_mapAddresses)
2702 int64 nSince = GetAdjustedTime() - 14 * 24 * 60 * 60;
2703 for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.begin();
2704 mi != mapAddresses.end();)
2706 const CAddress& addr = (*mi).second;
2707 if (addr.nTime < nSince)
2709 if (mapAddresses.size() < 1000 || GetTime() > nLastClear + 20)
2711 addrdb.EraseAddress(addr);
2712 mapAddresses.erase(mi++);
2726 vector<CAddress> vAddr;
2727 vAddr.reserve(pto->vAddrToSend.size());
2728 foreach(const CAddress& addr, pto->vAddrToSend)
2730 // returns true if wasn't already contained in the set
2731 if (pto->setAddrKnown.insert(addr).second)
2733 vAddr.push_back(addr);
2734 // receiver rejects addr messages larger than 1000
2735 if (vAddr.size() >= 1000)
2737 pto->PushMessage("addr", vAddr);
2742 pto->vAddrToSend.clear();
2744 pto->PushMessage("addr", vAddr);
2749 // Message: inventory
2752 vector<CInv> vInvWait;
2753 CRITICAL_BLOCK(pto->cs_inventory)
2755 vInv.reserve(pto->vInventoryToSend.size());
2756 vInvWait.reserve(pto->vInventoryToSend.size());
2757 foreach(const CInv& inv, pto->vInventoryToSend)
2759 if (pto->setInventoryKnown.count(inv))
2762 // trickle out tx inv to protect privacy
2763 if (inv.type == MSG_TX && !fSendTrickle)
2765 // 1/4 of tx invs blast to all immediately
2766 static uint256 hashSalt;
2768 RAND_bytes((unsigned char*)&hashSalt, sizeof(hashSalt));
2769 uint256 hashRand = inv.hash ^ hashSalt;
2770 hashRand = Hash(BEGIN(hashRand), END(hashRand));
2771 bool fTrickleWait = ((hashRand & 3) != 0);
2773 // always trickle our own transactions
2776 TRY_CRITICAL_BLOCK(cs_mapWallet)
2778 map<uint256, CWalletTx>::iterator mi = mapWallet.find(inv.hash);
2779 if (mi != mapWallet.end())
2781 CWalletTx& wtx = (*mi).second;
2783 fTrickleWait = true;
2790 vInvWait.push_back(inv);
2795 // returns true if wasn't already contained in the set
2796 if (pto->setInventoryKnown.insert(inv).second)
2798 vInv.push_back(inv);
2799 if (vInv.size() >= 1000)
2801 pto->PushMessage("inv", vInv);
2806 pto->vInventoryToSend = vInvWait;
2809 pto->PushMessage("inv", vInv);
2815 vector<CInv> vGetData;
2816 int64 nNow = GetTime() * 1000000;
2818 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
2820 const CInv& inv = (*pto->mapAskFor.begin()).second;
2821 if (!AlreadyHave(txdb, inv))
2823 printf("sending getdata: %s\n", inv.ToString().c_str());
2824 vGetData.push_back(inv);
2825 if (vGetData.size() >= 1000)
2827 pto->PushMessage("getdata", vGetData);
2831 pto->mapAskFor.erase(pto->mapAskFor.begin());
2833 if (!vGetData.empty())
2834 pto->PushMessage("getdata", vGetData);
2853 //////////////////////////////////////////////////////////////////////////////
2858 void GenerateBitcoins(bool fGenerate)
2860 if (fGenerateBitcoins != fGenerate)
2862 fGenerateBitcoins = fGenerate;
2863 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
2866 if (fGenerateBitcoins)
2868 int nProcessors = boost::thread::hardware_concurrency();
2869 printf("%d processors\n", nProcessors);
2870 if (nProcessors < 1)
2872 if (fLimitProcessors && nProcessors > nLimitProcessors)
2873 nProcessors = nLimitProcessors;
2874 int nAddThreads = nProcessors - vnThreadsRunning[3];
2875 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
2876 for (int i = 0; i < nAddThreads; i++)
2878 if (!CreateThread(ThreadBitcoinMiner, NULL))
2879 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
2885 void ThreadBitcoinMiner(void* parg)
2889 vnThreadsRunning[3]++;
2891 vnThreadsRunning[3]--;
2893 catch (std::exception& e) {
2894 vnThreadsRunning[3]--;
2895 PrintException(&e, "ThreadBitcoinMiner()");
2897 vnThreadsRunning[3]--;
2898 PrintException(NULL, "ThreadBitcoinMiner()");
2900 UIThreadCall(boost::bind(CalledSetStatusBar, "", 0));
2902 if (vnThreadsRunning[3] == 0)
2904 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
2907 #if defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
2908 void CallCPUID(int in, int& aret, int& cret)
2912 "mov %2, %%eax; " // in into eax
2914 "mov %%eax, %0;" // eax into a
2915 "mov %%ecx, %1;" // ecx into c
2916 :"=r"(a),"=r"(c) /* output */
2917 :"r"(in) /* input */
2918 :"%eax","%ecx" /* clobbered register */
2924 bool Detect128BitSSE2()
2927 CallCPUID(0, a, nBrand);
2928 bool fIntel = (nBrand == 0x6c65746e); // ntel
2929 bool fAMD = (nBrand == 0x444d4163); // cAMD
2933 unsigned int nStepping : 4;
2934 unsigned int nModel : 4;
2935 unsigned int nFamily : 4;
2936 unsigned int nProcessorType : 2;
2937 unsigned int nUnused : 2;
2938 unsigned int nExtendedModel : 4;
2939 unsigned int nExtendedFamily : 8;
2943 memcpy(&cpu, &a, sizeof(cpu));
2944 int nFamily = cpu.nExtendedFamily + cpu.nFamily;
2945 int nModel = cpu.nExtendedModel*16 + cpu.nModel;
2947 // We need Intel Nehalem or AMD K10 or better for 128bit SSE2
2948 // Nehalem = i3/i5/i7 and some Xeon
2949 // K10 = Opterons with 4 or more cores, Phenom, Phenom II, Athlon II
2950 // Intel Core i5 family 6, model 26 or 30
2951 // Intel Core i7 family 6, model 26 or 30
2952 // Intel Core i3 family 6, model 37
2953 // AMD Phenom family 16, model 10
2954 bool fUseSSE2 = ((fIntel && nFamily * 10000 + nModel >= 60026) ||
2955 (fAMD && nFamily * 10000 + nModel >= 160010));
2957 // AMD reports a lower model number in 64-bit mode
2958 if (fAMD && sizeof(void*) > 4 && nFamily * 10000 + nModel >= 160000)
2961 static bool fPrinted;
2965 printf("CPUID %08x family %d, model %d, stepping %d, fUseSSE2=%d\n", nBrand, nFamily, nModel, cpu.nStepping, fUseSSE2);
2970 bool Detect128BitSSE2() { return false; }
2973 int FormatHashBlocks(void* pbuffer, unsigned int len)
2975 unsigned char* pdata = (unsigned char*)pbuffer;
2976 unsigned int blocks = 1 + ((len + 8) / 64);
2977 unsigned char* pend = pdata + 64 * blocks;
2978 memset(pdata + len, 0, 64 * blocks - len);
2980 unsigned int bits = len * 8;
2981 pend[-1] = (bits >> 0) & 0xff;
2982 pend[-2] = (bits >> 8) & 0xff;
2983 pend[-3] = (bits >> 16) & 0xff;
2984 pend[-4] = (bits >> 24) & 0xff;
2988 using CryptoPP::ByteReverse;
2990 static const unsigned int pSHA256InitState[8] =
2991 {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
2993 inline void SHA256Transform(void* pstate, void* pinput, const void* pinit)
2995 memcpy(pstate, pinit, 32);
2996 CryptoPP::SHA256::Transform((CryptoPP::word32*)pstate, (CryptoPP::word32*)pinput);
3000 // ScanHash scans nonces looking for a hash with at least some zero bits.
3001 // It operates on big endian data. Caller does the byte reversing.
3002 // All input buffers are 16-byte aligned. nNonce is usually preserved
3003 // between calls, but periodically or if nNonce is above 0xff000000,
3004 // the block is rebuilt and nNonce starts over at zero.
3006 unsigned int ScanHash_CryptoPP(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone)
3008 unsigned int& nNonce = *(unsigned int*)(pblock + 12);
3012 // Hash pblock using pmidstate as the starting state into
3013 // preformatted buffer phash1, then hash phash1 into phash
3015 SHA256Transform(phash1, pblock, pmidstate);
3016 SHA256Transform(phash, phash1, pSHA256InitState);
3018 // Return the nonce if the hash has at least some zero bits,
3019 // caller will check if it has enough to reach the target
3020 if (((unsigned short*)phash)[14] == 0)
3023 // If nothing found after trying for a while, return -1
3024 if ((nNonce & 0xffff) == 0)
3026 nHashesDone = 0xffff+1;
3032 extern unsigned int ScanHash_4WaySSE2(char* pmidstate, char* pblock, char* phash1, char* phash, unsigned int& nHashesDone);
3040 set<uint256> setDependsOn;
3043 COrphan(CTransaction* ptxIn)
3051 printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
3052 foreach(uint256 hash, setDependsOn)
3053 printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
3061 printf("BitcoinMiner started\n");
3062 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3063 bool f4WaySSE2 = Detect128BitSSE2();
3064 if (mapArgs.count("-4way"))
3065 f4WaySSE2 = (mapArgs["-4way"] != "0");
3067 CReserveKey reservekey;
3068 unsigned int nExtraNonce = 0;
3069 int64 nPrevTime = 0;
3070 while (fGenerateBitcoins)
3072 if (AffinityBugWorkaround(ThreadBitcoinMiner))
3076 while (vNodes.empty() || IsInitialBlockDownload())
3081 if (!fGenerateBitcoins)
3085 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
3086 CBlockIndex* pindexPrev = pindexBest;
3087 unsigned int nBits = GetNextWorkRequired(pindexPrev);
3091 // Create coinbase tx
3094 txNew.vin.resize(1);
3095 txNew.vin[0].prevout.SetNull();
3096 int64 nNow = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3097 if (++nExtraNonce >= 0x7f && nNow > nPrevTime+1)
3102 txNew.vin[0].scriptSig << nBits << CBigNum(nExtraNonce);
3103 txNew.vout.resize(1);
3104 txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
3110 auto_ptr<CBlock> pblock(new CBlock());
3114 // Add our coinbase tx as first transaction
3115 pblock->vtx.push_back(txNew);
3117 // Collect memory pool transactions into the block
3119 CRITICAL_BLOCK(cs_main)
3120 CRITICAL_BLOCK(cs_mapTransactions)
3124 // Priority order to process transactions
3125 list<COrphan> vOrphan; // list memory doesn't move
3126 map<uint256, vector<COrphan*> > mapDependers;
3127 multimap<double, CTransaction*> mapPriority;
3128 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi)
3130 CTransaction& tx = (*mi).second;
3131 if (tx.IsCoinBase() || !tx.IsFinal())
3134 COrphan* porphan = NULL;
3135 double dPriority = 0;
3136 foreach(const CTxIn& txin, tx.vin)
3138 // Read prev transaction
3139 CTransaction txPrev;
3141 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
3143 // Has to wait for dependencies
3146 // Use list for automatic deletion
3147 vOrphan.push_back(COrphan(&tx));
3148 porphan = &vOrphan.back();
3150 mapDependers[txin.prevout.hash].push_back(porphan);
3151 porphan->setDependsOn.insert(txin.prevout.hash);
3154 int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
3156 // Read block header
3159 if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
3161 map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(block.GetHash());
3162 if (it != mapBlockIndex.end())
3164 CBlockIndex* pindex = (*it).second;
3165 if (pindex->IsInMainChain())
3166 nConf = 1 + nBestHeight - pindex->nHeight;
3170 dPriority += (double)nValueIn * nConf;
3172 if (fDebug && mapArgs.count("-printpriority"))
3173 printf("priority nValueIn=%-12I64d nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
3176 // Priority is sum(valuein * age) / txsize
3177 dPriority /= ::GetSerializeSize(tx, SER_NETWORK);
3180 porphan->dPriority = dPriority;
3182 mapPriority.insert(make_pair(-dPriority, &(*mi).second));
3184 if (fDebug && mapArgs.count("-printpriority"))
3186 printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
3193 // Collect transactions into block
3194 map<uint256, CTxIndex> mapTestPool;
3195 uint64 nBlockSize = 1000;
3196 int nBlockSigOps = 100;
3197 while (!mapPriority.empty())
3199 // Take highest priority transaction off priority queue
3200 double dPriority = -(*mapPriority.begin()).first;
3201 CTransaction& tx = *(*mapPriority.begin()).second;
3202 mapPriority.erase(mapPriority.begin());
3205 unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK);
3206 if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
3208 int nTxSigOps = tx.GetSigOpCount();
3209 if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
3212 // Transaction fee required depends on block size
3213 bool fAllowFree = (nBlockSize + nTxSize < 4000 || dPriority > COIN * 144 / 250);
3214 int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree);
3216 // Connecting shouldn't fail due to dependency on other memory pool transactions
3217 // because we're already processing them in order of dependency
3218 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
3219 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, nFees, false, true, nMinFee))
3221 swap(mapTestPool, mapTestPoolTmp);
3224 pblock->vtx.push_back(tx);
3225 nBlockSize += nTxSize;
3226 nBlockSigOps += nTxSigOps;
3228 // Add transactions that depend on this one to the priority queue
3229 uint256 hash = tx.GetHash();
3230 if (mapDependers.count(hash))
3232 foreach(COrphan* porphan, mapDependers[hash])
3234 if (!porphan->setDependsOn.empty())
3236 porphan->setDependsOn.erase(hash);
3237 if (porphan->setDependsOn.empty())
3238 mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
3244 pblock->nBits = nBits;
3245 pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
3246 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
3250 // Prebuild hash buffer
3257 uint256 hashPrevBlock;
3258 uint256 hashMerkleRoot;
3261 unsigned int nNonce;
3264 unsigned char pchPadding0[64];
3266 unsigned char pchPadding1[64];
3268 char tmpbuf[sizeof(tmpworkspace)+16];
3269 tmpworkspace& tmp = *(tmpworkspace*)alignup<16>(tmpbuf);
3271 tmp.block.nVersion = pblock->nVersion;
3272 tmp.block.hashPrevBlock = pblock->hashPrevBlock = pindexPrev->GetBlockHash();
3273 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
3274 tmp.block.nTime = pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3275 tmp.block.nBits = pblock->nBits = nBits;
3276 tmp.block.nNonce = pblock->nNonce = 0;
3278 unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
3279 unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
3281 // Byte swap all the input buffer
3282 for (int i = 0; i < sizeof(tmp)/4; i++)
3283 ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
3285 // Precalc the first half of the first hash, which stays constant
3286 uint256 midstatebuf[2];
3287 uint256& midstate = *alignup<16>(midstatebuf);
3288 SHA256Transform(&midstate, &tmp.block, pSHA256InitState);
3294 int64 nStart = GetTime();
3295 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
3297 uint256& hash = *alignup<16>(hashbuf);
3300 unsigned int nHashesDone = 0;
3301 unsigned int nNonceFound;
3305 // tcatm's 4-way 128-bit SSE2 SHA-256
3306 nNonceFound = ScanHash_4WaySSE2((char*)&midstate, (char*)&tmp.block + 64, (char*)&tmp.hash1, (char*)&hash, nHashesDone);
3310 nNonceFound = ScanHash_CryptoPP((char*)&midstate, (char*)&tmp.block + 64, (char*)&tmp.hash1, (char*)&hash, nHashesDone);
3312 // Check if something found
3313 if (nNonceFound != -1)
3315 for (int i = 0; i < sizeof(hash)/4; i++)
3316 ((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
3318 if (hash <= hashTarget)
3321 pblock->nNonce = ByteReverse(nNonceFound);
3322 assert(hash == pblock->GetHash());
3325 printf("BitcoinMiner:\n");
3326 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
3328 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3329 printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
3331 SetThreadPriority(THREAD_PRIORITY_NORMAL);
3332 CRITICAL_BLOCK(cs_main)
3334 if (pindexPrev == pindexBest)
3336 // Remove key from key pool
3337 reservekey.KeepKey();
3339 // Track how many getdata requests this block gets
3340 CRITICAL_BLOCK(cs_mapRequestCount)
3341 mapRequestCount[pblock->GetHash()] = 0;
3343 // Process this block the same as if we had received it from another node
3344 if (!ProcessBlock(NULL, pblock.release()))
3345 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
3348 SetThreadPriority(THREAD_PRIORITY_LOWEST);
3356 static int64 nHashCounter;
3357 if (nHPSTimerStart == 0)
3359 nHPSTimerStart = GetTimeMillis();
3363 nHashCounter += nHashesDone;
3364 if (GetTimeMillis() - nHPSTimerStart > 4000)
3366 static CCriticalSection cs;
3369 if (GetTimeMillis() - nHPSTimerStart > 4000)
3371 dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
3372 nHPSTimerStart = GetTimeMillis();
3374 string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
3375 UIThreadCall(boost::bind(CalledSetStatusBar, strStatus, 0));
3376 static int64 nLogTime;
3377 if (GetTime() - nLogTime > 30 * 60)
3379 nLogTime = GetTime();
3380 printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
3381 printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[3], dHashesPerSec/1000.0);
3387 // Check for stop or if block needs to be rebuilt
3390 if (!fGenerateBitcoins)
3392 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
3396 if (tmp.block.nNonce >= 0xff000000)
3398 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
3400 if (pindexPrev != pindexBest)
3403 // Update nTime every few seconds
3404 pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
3405 tmp.block.nTime = ByteReverse(pblock->nTime);
3427 //////////////////////////////////////////////////////////////////////////////
3435 int64 nStart = GetTimeMillis();
3438 CRITICAL_BLOCK(cs_mapWallet)
3440 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3442 CWalletTx* pcoin = &(*it).second;
3443 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3445 nTotal += pcoin->GetCredit(true);
3449 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
3454 bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, set<CWalletTx*>& setCoinsRet)
3456 setCoinsRet.clear();
3458 // List of values less than target
3459 int64 nLowestLarger = INT64_MAX;
3460 CWalletTx* pcoinLowestLarger = NULL;
3461 vector<pair<int64, CWalletTx*> > vValue;
3462 int64 nTotalLower = 0;
3464 CRITICAL_BLOCK(cs_mapWallet)
3466 vector<CWalletTx*> vCoins;
3467 vCoins.reserve(mapWallet.size());
3468 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3469 vCoins.push_back(&(*it).second);
3470 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
3472 foreach(CWalletTx* pcoin, vCoins)
3474 if (!pcoin->IsFinal() || pcoin->fSpent || !pcoin->IsConfirmed())
3477 int nDepth = pcoin->GetDepthInMainChain();
3478 if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
3481 int64 n = pcoin->GetCredit();
3484 if (n < nTargetValue)
3486 vValue.push_back(make_pair(n, pcoin));
3489 else if (n == nTargetValue)
3491 setCoinsRet.insert(pcoin);
3494 else if (n < nLowestLarger)
3497 pcoinLowestLarger = pcoin;
3502 if (nTotalLower < nTargetValue)
3504 if (pcoinLowestLarger == NULL)
3506 setCoinsRet.insert(pcoinLowestLarger);
3510 // Solve subset sum by stochastic approximation
3511 sort(vValue.rbegin(), vValue.rend());
3512 vector<char> vfIncluded;
3513 vector<char> vfBest(vValue.size(), true);
3514 int64 nBest = nTotalLower;
3516 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
3518 vfIncluded.assign(vValue.size(), false);
3520 bool fReachedTarget = false;
3521 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
3523 for (int i = 0; i < vValue.size(); i++)
3525 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
3527 nTotal += vValue[i].first;
3528 vfIncluded[i] = true;
3529 if (nTotal >= nTargetValue)
3531 fReachedTarget = true;
3535 vfBest = vfIncluded;
3537 nTotal -= vValue[i].first;
3538 vfIncluded[i] = false;
3545 // If the next larger is still closer, return it
3546 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
3547 setCoinsRet.insert(pcoinLowestLarger);
3550 for (int i = 0; i < vValue.size(); i++)
3552 setCoinsRet.insert(vValue[i].second);
3555 printf("SelectCoins() best subset: ");
3556 for (int i = 0; i < vValue.size(); i++)
3558 printf("%s ", FormatMoney(vValue[i].first).c_str());
3559 printf("total %s\n", FormatMoney(nBest).c_str());
3565 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
3567 return (SelectCoinsMinConf(nTargetValue, 1, 6, setCoinsRet) ||
3568 SelectCoinsMinConf(nTargetValue, 1, 1, setCoinsRet) ||
3569 SelectCoinsMinConf(nTargetValue, 0, 1, setCoinsRet));
3575 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet)
3577 CRITICAL_BLOCK(cs_main)
3579 // txdb must be opened before the mapWallet lock
3581 CRITICAL_BLOCK(cs_mapWallet)
3583 nFeeRet = nTransactionFee;
3587 wtxNew.vout.clear();
3588 wtxNew.fFromMe = true;
3591 int64 nValueOut = nValue;
3592 int64 nTotalValue = nValue + nFeeRet;
3594 // Choose coins to use
3595 set<CWalletTx*> setCoins;
3596 if (!SelectCoins(nTotalValue, setCoins))
3599 foreach(CWalletTx* pcoin, setCoins)
3600 nValueIn += pcoin->GetCredit();
3602 // Fill a vout to the payee
3603 bool fChangeFirst = GetRand(2);
3605 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3607 // Fill a vout back to self with any change
3608 int64 nChange = nValueIn - nTotalValue;
3609 if (nChange >= CENT)
3611 // Note: We use a new key here to keep it from being obvious which side is the change.
3612 // The drawback is that by not reusing a previous key, the change may be lost if a
3613 // backup is restored, if the backup doesn't have the new private key for the change.
3614 // If we reused the old key, it would be possible to add code to look for and
3615 // rediscover unknown transactions that were written with keys of ours to recover
3616 // post-backup change.
3618 // Reserve a new key pair from key pool
3619 vector<unsigned char> vchPubKey = reservekey.GetReservedKey();
3620 assert(mapKeys.count(vchPubKey));
3622 // Fill a vout to ourself, using same address type as the payment
3623 CScript scriptChange;
3624 if (scriptPubKey.GetBitcoinAddressHash160() != 0)
3625 scriptChange.SetBitcoinAddress(vchPubKey);
3627 scriptChange << vchPubKey << OP_CHECKSIG;
3628 wtxNew.vout.push_back(CTxOut(nChange, scriptChange));
3631 reservekey.ReturnKey();
3633 // Fill a vout to the payee
3635 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
3638 foreach(CWalletTx* pcoin, setCoins)
3639 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3640 if (pcoin->vout[nOut].IsMine())
3641 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
3645 foreach(CWalletTx* pcoin, setCoins)
3646 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
3647 if (pcoin->vout[nOut].IsMine())
3648 if (!SignSignature(*pcoin, wtxNew, nIn++))
3652 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK);
3653 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
3656 // Check that enough fee is included
3657 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
3658 int64 nMinFee = wtxNew.GetMinFee();
3659 if (nFeeRet < max(nPayFee, nMinFee))
3661 nFeeRet = max(nPayFee, nMinFee);
3665 // Fill vtxPrev by copying from previous transactions vtxPrev
3666 wtxNew.AddSupportingTransactions(txdb);
3667 wtxNew.fTimeReceivedIsTxTime = true;
3676 // Call after CreateTransaction unless you want to abort
3677 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
3679 CRITICAL_BLOCK(cs_main)
3681 printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
3682 CRITICAL_BLOCK(cs_mapWallet)
3684 // This is only to keep the database open to defeat the auto-flush for the
3685 // duration of this scope. This is the only place where this optimization
3686 // maybe makes sense; please don't do it anywhere else.
3687 CWalletDB walletdb("r");
3689 // Take key pair from key pool so it won't be used again
3690 reservekey.KeepKey();
3692 // Add tx to wallet, because if it has change it's also ours,
3693 // otherwise just for transaction history.
3694 AddToWallet(wtxNew);
3696 // Mark old coins as spent
3697 set<CWalletTx*> setCoins;
3698 foreach(const CTxIn& txin, wtxNew.vin)
3699 setCoins.insert(&mapWallet[txin.prevout.hash]);
3700 foreach(CWalletTx* pcoin, setCoins)
3702 pcoin->fSpent = true;
3703 pcoin->WriteToDisk();
3704 vWalletUpdated.push_back(pcoin->GetHash());
3708 // Track how many getdata requests our transaction gets
3709 CRITICAL_BLOCK(cs_mapRequestCount)
3710 mapRequestCount[wtxNew.GetHash()] = 0;
3713 if (!wtxNew.AcceptToMemoryPool())
3715 // This must not fail. The transaction has already been signed and recorded.
3716 printf("CommitTransaction() : Error: Transaction not valid");
3719 wtxNew.RelayWalletTransaction();
3728 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3730 CRITICAL_BLOCK(cs_main)
3732 CReserveKey reservekey;
3734 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
3737 if (nValue + nFeeRequired > GetBalance())
3738 strError = strprintf(_("Error: This is an oversized transaction that requires a transaction fee of %s "), FormatMoney(nFeeRequired).c_str());
3740 strError = _("Error: Transaction creation failed ");
3741 printf("SendMoney() : %s", strError.c_str());
3745 if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."), NULL))
3748 if (!CommitTransaction(wtxNew, reservekey))
3749 return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
3757 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
3761 return _("Invalid amount");
3762 if (nValue + nTransactionFee > GetBalance())
3763 return _("Insufficient funds");
3765 // Parse bitcoin address
3766 CScript scriptPubKey;
3767 if (!scriptPubKey.SetBitcoinAddress(strAddress))
3768 return _("Invalid bitcoin address");
3770 return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);