1 // Copyright (c) 2009-2010 Satoshi Nakamoto
\r
2 // Distributed under the MIT/X11 software license, see the accompanying
\r
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
\r
16 CCriticalSection cs_main;
\r
18 map<uint256, CTransaction> mapTransactions;
\r
19 CCriticalSection cs_mapTransactions;
\r
20 unsigned int nTransactionsUpdated = 0;
\r
21 map<COutPoint, CInPoint> mapNextTx;
\r
23 map<uint256, CBlockIndex*> mapBlockIndex;
\r
24 const uint256 hashGenesisBlock("0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
\r
25 CBlockIndex* pindexGenesisBlock = NULL;
\r
26 int nBestHeight = -1;
\r
27 uint256 hashBestChain = 0;
\r
28 CBlockIndex* pindexBest = NULL;
\r
30 map<uint256, CBlock*> mapOrphanBlocks;
\r
31 multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
\r
33 map<uint256, CDataStream*> mapOrphanTransactions;
\r
34 multimap<uint256, CDataStream*> mapOrphanTransactionsByPrev;
\r
36 map<uint256, CWalletTx> mapWallet;
\r
37 vector<uint256> vWalletUpdated;
\r
38 CCriticalSection cs_mapWallet;
\r
40 map<vector<unsigned char>, CPrivKey> mapKeys;
\r
41 map<uint160, vector<unsigned char> > mapPubKeys;
\r
42 CCriticalSection cs_mapKeys;
\r
45 map<uint256, int> mapRequestCount;
\r
46 CCriticalSection cs_mapRequestCount;
\r
49 int fGenerateBitcoins = false;
\r
50 int64 nTransactionFee = 0;
\r
51 CAddress addrIncoming;
\r
52 int fLimitProcessors = false;
\r
53 int nLimitProcessors = 1;
\r
60 //////////////////////////////////////////////////////////////////////////////
\r
65 bool AddKey(const CKey& key)
\r
67 CRITICAL_BLOCK(cs_mapKeys)
\r
69 mapKeys[key.GetPubKey()] = key.GetPrivKey();
\r
70 mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
\r
72 return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
\r
75 vector<unsigned char> GenerateNewKey()
\r
80 throw runtime_error("GenerateNewKey() : AddKey failed\n");
\r
81 return key.GetPubKey();
\r
87 //////////////////////////////////////////////////////////////////////////////
\r
92 bool AddToWallet(const CWalletTx& wtxIn)
\r
94 uint256 hash = wtxIn.GetHash();
\r
95 CRITICAL_BLOCK(cs_mapWallet)
\r
97 // Inserts only if not already there, returns tx inserted or tx found
\r
98 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
\r
99 CWalletTx& wtx = (*ret.first).second;
\r
100 bool fInsertedNew = ret.second;
\r
102 wtx.nTimeReceived = GetAdjustedTime();
\r
104 bool fUpdated = false;
\r
108 if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
\r
110 wtx.hashBlock = wtxIn.hashBlock;
\r
113 if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
\r
115 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
\r
116 wtx.nIndex = wtxIn.nIndex;
\r
119 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
\r
121 wtx.fFromMe = wtxIn.fFromMe;
\r
124 if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
\r
126 wtx.fSpent = wtxIn.fSpent;
\r
132 printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,6).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
\r
135 if (fInsertedNew || fUpdated)
\r
136 if (!wtx.WriteToDisk())
\r
140 vWalletUpdated.push_back(hash);
\r
144 MainFrameRepaint();
\r
148 bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
\r
150 if (tx.IsMine() || mapWallet.count(tx.GetHash()))
\r
153 // Get merkle branch if transaction was found in a block
\r
155 wtx.SetMerkleBranch(pblock);
\r
156 return AddToWallet(wtx);
\r
161 bool EraseFromWallet(uint256 hash)
\r
163 CRITICAL_BLOCK(cs_mapWallet)
\r
165 if (mapWallet.erase(hash))
\r
166 CWalletDB().EraseTx(hash);
\r
171 void WalletUpdateSpent(const COutPoint& prevout)
\r
173 // Anytime a signature is successfully verified, it's proof the outpoint is spent.
\r
174 // Update the wallet spent flag if it doesn't know due to wallet.dat being
\r
175 // restored from backup or the user making copies of wallet.dat.
\r
176 CRITICAL_BLOCK(cs_mapWallet)
\r
178 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
\r
179 if (mi != mapWallet.end())
\r
181 CWalletTx& wtx = (*mi).second;
\r
182 if (!wtx.fSpent && wtx.vout[prevout.n].IsMine())
\r
184 printf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
\r
187 vWalletUpdated.push_back(prevout.hash);
\r
200 //////////////////////////////////////////////////////////////////////////////
\r
202 // mapOrphanTransactions
\r
205 void AddOrphanTx(const CDataStream& vMsg)
\r
208 CDataStream(vMsg) >> tx;
\r
209 uint256 hash = tx.GetHash();
\r
210 if (mapOrphanTransactions.count(hash))
\r
212 CDataStream* pvMsg = mapOrphanTransactions[hash] = new CDataStream(vMsg);
\r
213 foreach(const CTxIn& txin, tx.vin)
\r
214 mapOrphanTransactionsByPrev.insert(make_pair(txin.prevout.hash, pvMsg));
\r
217 void EraseOrphanTx(uint256 hash)
\r
219 if (!mapOrphanTransactions.count(hash))
\r
221 const CDataStream* pvMsg = mapOrphanTransactions[hash];
\r
223 CDataStream(*pvMsg) >> tx;
\r
224 foreach(const CTxIn& txin, tx.vin)
\r
226 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(txin.prevout.hash);
\r
227 mi != mapOrphanTransactionsByPrev.upper_bound(txin.prevout.hash);)
\r
229 if ((*mi).second == pvMsg)
\r
230 mapOrphanTransactionsByPrev.erase(mi++);
\r
236 mapOrphanTransactions.erase(hash);
\r
246 //////////////////////////////////////////////////////////////////////////////
\r
251 bool CTxIn::IsMine() const
\r
253 CRITICAL_BLOCK(cs_mapWallet)
\r
255 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
\r
256 if (mi != mapWallet.end())
\r
258 const CWalletTx& prev = (*mi).second;
\r
259 if (prevout.n < prev.vout.size())
\r
260 if (prev.vout[prevout.n].IsMine())
\r
267 int64 CTxIn::GetDebit() const
\r
269 CRITICAL_BLOCK(cs_mapWallet)
\r
271 map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
\r
272 if (mi != mapWallet.end())
\r
274 const CWalletTx& prev = (*mi).second;
\r
275 if (prevout.n < prev.vout.size())
\r
276 if (prev.vout[prevout.n].IsMine())
\r
277 return prev.vout[prevout.n].nValue;
\r
283 int64 CWalletTx::GetTxTime() const
\r
285 if (!fTimeReceivedIsTxTime && hashBlock != 0)
\r
287 // If we did not receive the transaction directly, we rely on the block's
\r
288 // time to figure out when it happened. We use the median over a range
\r
289 // of blocks to try to filter out inaccurate block times.
\r
290 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
291 if (mi != mapBlockIndex.end())
\r
293 CBlockIndex* pindex = (*mi).second;
\r
295 return pindex->GetMedianTime();
\r
298 return nTimeReceived;
\r
301 int CWalletTx::GetRequestCount() const
\r
303 // Returns -1 if it wasn't being tracked
\r
304 int nRequests = -1;
\r
305 CRITICAL_BLOCK(cs_mapRequestCount)
\r
310 if (hashBlock != 0)
\r
312 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
\r
313 if (mi != mapRequestCount.end())
\r
314 nRequests = (*mi).second;
\r
319 // Did anyone request this transaction?
\r
320 map<uint256, int>::iterator mi = mapRequestCount.find(GetHash());
\r
321 if (mi != mapRequestCount.end())
\r
323 nRequests = (*mi).second;
\r
325 // How about the block it's in?
\r
326 if (nRequests == 0 && hashBlock != 0)
\r
328 map<uint256, int>::iterator mi = mapRequestCount.find(hashBlock);
\r
329 if (mi != mapRequestCount.end())
\r
330 nRequests = (*mi).second;
\r
332 nRequests = 1; // If it's in someone else's block it must have got out
\r
343 int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
\r
347 if (hashBlock == 0)
\r
353 if (pblock == NULL)
\r
355 // Load the block this tx is in
\r
357 if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
\r
359 if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
\r
361 pblock = &blockTmp;
\r
364 // Update the tx's hashBlock
\r
365 hashBlock = pblock->GetHash();
\r
367 // Locate the transaction
\r
368 for (nIndex = 0; nIndex < pblock->vtx.size(); nIndex++)
\r
369 if (pblock->vtx[nIndex] == *(CTransaction*)this)
\r
371 if (nIndex == pblock->vtx.size())
\r
373 vMerkleBranch.clear();
\r
375 printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
\r
379 // Fill in merkle branch
\r
380 vMerkleBranch = pblock->GetMerkleBranch(nIndex);
\r
383 // Is the tx in a block that's in the main chain
\r
384 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
385 if (mi == mapBlockIndex.end())
\r
387 CBlockIndex* pindex = (*mi).second;
\r
388 if (!pindex || !pindex->IsInMainChain())
\r
391 return pindexBest->nHeight - pindex->nHeight + 1;
\r
396 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
\r
400 const int COPY_DEPTH = 3;
\r
401 if (SetMerkleBranch() < COPY_DEPTH)
\r
403 vector<uint256> vWorkQueue;
\r
404 foreach(const CTxIn& txin, vin)
\r
405 vWorkQueue.push_back(txin.prevout.hash);
\r
407 // This critsect is OK because txdb is already open
\r
408 CRITICAL_BLOCK(cs_mapWallet)
\r
410 map<uint256, const CMerkleTx*> mapWalletPrev;
\r
411 set<uint256> setAlreadyDone;
\r
412 for (int i = 0; i < vWorkQueue.size(); i++)
\r
414 uint256 hash = vWorkQueue[i];
\r
415 if (setAlreadyDone.count(hash))
\r
417 setAlreadyDone.insert(hash);
\r
420 if (mapWallet.count(hash))
\r
422 tx = mapWallet[hash];
\r
423 foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
\r
424 mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
\r
426 else if (mapWalletPrev.count(hash))
\r
428 tx = *mapWalletPrev[hash];
\r
430 else if (!fClient && txdb.ReadDiskTx(hash, tx))
\r
436 printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
\r
440 int nDepth = tx.SetMerkleBranch();
\r
441 vtxPrev.push_back(tx);
\r
443 if (nDepth < COPY_DEPTH)
\r
444 foreach(const CTxIn& txin, tx.vin)
\r
445 vWorkQueue.push_back(txin.prevout.hash);
\r
450 reverse(vtxPrev.begin(), vtxPrev.end());
\r
463 bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
\r
465 if (pfMissingInputs)
\r
466 *pfMissingInputs = false;
\r
468 // Coinbase is only valid in a block, not as a loose transaction
\r
470 return error("AcceptTransaction() : coinbase as individual tx");
\r
472 if (!CheckTransaction())
\r
473 return error("AcceptTransaction() : CheckTransaction failed");
\r
475 // To help v0.1.5 clients who would see it as negative number. please delete this later.
\r
476 if (nLockTime > INT_MAX)
\r
477 return error("AcceptTransaction() : not accepting nLockTime beyond 2038");
\r
479 // Do we already have it?
\r
480 uint256 hash = GetHash();
\r
481 CRITICAL_BLOCK(cs_mapTransactions)
\r
482 if (mapTransactions.count(hash))
\r
485 if (txdb.ContainsTx(hash))
\r
488 // Check for conflicts with in-memory transactions
\r
489 CTransaction* ptxOld = NULL;
\r
490 for (int i = 0; i < vin.size(); i++)
\r
492 COutPoint outpoint = vin[i].prevout;
\r
493 if (mapNextTx.count(outpoint))
\r
495 // Allow replacing with a newer version of the same transaction
\r
498 ptxOld = mapNextTx[outpoint].ptx;
\r
499 if (!IsNewerThan(*ptxOld))
\r
501 for (int i = 0; i < vin.size(); i++)
\r
503 COutPoint outpoint = vin[i].prevout;
\r
504 if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
\r
511 // Check against previous transactions
\r
512 map<uint256, CTxIndex> mapUnused;
\r
514 if (fCheckInputs && !ConnectInputs(txdb, mapUnused, CDiskTxPos(1,1,1), 0, nFees, false, false))
\r
516 if (pfMissingInputs)
\r
517 *pfMissingInputs = true;
\r
518 return error("AcceptTransaction() : ConnectInputs failed %s", hash.ToString().substr(0,6).c_str());
\r
521 // Store transaction in memory
\r
522 CRITICAL_BLOCK(cs_mapTransactions)
\r
526 printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());
\r
527 mapTransactions.erase(ptxOld->GetHash());
\r
532 ///// are we sure this is ok when loading transactions or restoring block txes
\r
533 // If updated, erase old tx from wallet
\r
535 EraseFromWallet(ptxOld->GetHash());
\r
537 printf("AcceptTransaction(): accepted %s\n", hash.ToString().substr(0,6).c_str());
\r
542 bool CTransaction::AddToMemoryPool()
\r
544 // Add to memory pool without checking anything. Don't call this directly,
\r
545 // call AcceptTransaction to properly check the transaction first.
\r
546 CRITICAL_BLOCK(cs_mapTransactions)
\r
548 uint256 hash = GetHash();
\r
549 mapTransactions[hash] = *this;
\r
550 for (int i = 0; i < vin.size(); i++)
\r
551 mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
\r
552 nTransactionsUpdated++;
\r
558 bool CTransaction::RemoveFromMemoryPool()
\r
560 // Remove transaction from memory pool
\r
561 CRITICAL_BLOCK(cs_mapTransactions)
\r
563 foreach(const CTxIn& txin, vin)
\r
564 mapNextTx.erase(txin.prevout);
\r
565 mapTransactions.erase(GetHash());
\r
566 nTransactionsUpdated++;
\r
576 int CMerkleTx::GetDepthInMainChain() const
\r
578 if (hashBlock == 0 || nIndex == -1)
\r
581 // Find the block it claims to be in
\r
582 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
\r
583 if (mi == mapBlockIndex.end())
\r
585 CBlockIndex* pindex = (*mi).second;
\r
586 if (!pindex || !pindex->IsInMainChain())
\r
589 // Make sure the merkle branch connects to this block
\r
590 if (!fMerkleVerified)
\r
592 if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
\r
594 fMerkleVerified = true;
\r
597 return pindexBest->nHeight - pindex->nHeight + 1;
\r
601 int CMerkleTx::GetBlocksToMaturity() const
\r
605 return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
\r
609 bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)
\r
613 if (!IsInMainChain() && !ClientConnectInputs())
\r
615 return CTransaction::AcceptTransaction(txdb, false);
\r
619 return CTransaction::AcceptTransaction(txdb, fCheckInputs);
\r
625 bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
\r
627 CRITICAL_BLOCK(cs_mapTransactions)
\r
629 foreach(CMerkleTx& tx, vtxPrev)
\r
631 if (!tx.IsCoinBase())
\r
633 uint256 hash = tx.GetHash();
\r
634 if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
\r
635 tx.AcceptTransaction(txdb, fCheckInputs);
\r
639 return AcceptTransaction(txdb, fCheckInputs);
\r
644 void ReacceptWalletTransactions()
\r
647 CRITICAL_BLOCK(cs_mapWallet)
\r
649 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
\r
651 CWalletTx& wtx = item.second;
\r
652 if (wtx.fSpent && wtx.IsCoinBase())
\r
656 if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
\r
658 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
\r
661 if (txindex.vSpent.size() != wtx.vout.size())
\r
663 printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size());
\r
666 for (int i = 0; i < txindex.vSpent.size(); i++)
\r
668 if (!txindex.vSpent[i].IsNull() && wtx.vout[i].IsMine())
\r
670 printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
\r
680 // Reaccept any txes of ours that aren't already in a block
\r
681 if (!wtx.IsCoinBase())
\r
682 wtx.AcceptWalletTransaction(txdb, false);
\r
689 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
\r
691 foreach(const CMerkleTx& tx, vtxPrev)
\r
693 if (!tx.IsCoinBase())
\r
695 uint256 hash = tx.GetHash();
\r
696 if (!txdb.ContainsTx(hash))
\r
697 RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
\r
702 uint256 hash = GetHash();
\r
703 if (!txdb.ContainsTx(hash))
\r
705 printf("Relaying wtx %s\n", hash.ToString().substr(0,6).c_str());
\r
706 RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
\r
711 void RelayWalletTransactions()
\r
713 static int64 nLastTime;
\r
714 if (GetTime() - nLastTime < 10 * 60)
\r
716 nLastTime = GetTime();
\r
718 // Rebroadcast any of our txes that aren't in a block yet
\r
719 printf("RelayWalletTransactions()\n");
\r
721 CRITICAL_BLOCK(cs_mapWallet)
\r
723 // Sort them in chronological order
\r
724 multimap<unsigned int, CWalletTx*> mapSorted;
\r
725 foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
\r
727 CWalletTx& wtx = item.second;
\r
728 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
\r
730 foreach(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
\r
732 CWalletTx& wtx = *item.second;
\r
733 wtx.RelayWalletTransaction(txdb);
\r
747 //////////////////////////////////////////////////////////////////////////////
\r
749 // CBlock and CBlockIndex
\r
752 bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)
\r
754 return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);
\r
757 uint256 GetOrphanRoot(const CBlock* pblock)
\r
759 // Work back to the first block in the orphan chain
\r
760 while (mapOrphanBlocks.count(pblock->hashPrevBlock))
\r
761 pblock = mapOrphanBlocks[pblock->hashPrevBlock];
\r
762 return pblock->GetHash();
\r
765 int64 CBlock::GetBlockValue(int64 nFees) const
\r
767 int64 nSubsidy = 50 * COIN;
\r
769 // Subsidy is cut in half every 4 years
\r
770 nSubsidy >>= (nBestHeight / 210000);
\r
772 return nSubsidy + nFees;
\r
775 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
\r
777 const unsigned int nTargetTimespan = 14 * 24 * 60 * 60; // two weeks
\r
778 const unsigned int nTargetSpacing = 10 * 60;
\r
779 const unsigned int nInterval = nTargetTimespan / nTargetSpacing;
\r
782 if (pindexLast == NULL)
\r
783 return bnProofOfWorkLimit.GetCompact();
\r
785 // Only change once per interval
\r
786 if ((pindexLast->nHeight+1) % nInterval != 0)
\r
787 return pindexLast->nBits;
\r
789 // Go back by what we want to be 14 days worth of blocks
\r
790 const CBlockIndex* pindexFirst = pindexLast;
\r
791 for (int i = 0; pindexFirst && i < nInterval-1; i++)
\r
792 pindexFirst = pindexFirst->pprev;
\r
793 assert(pindexFirst);
\r
795 // Limit adjustment step
\r
796 unsigned int nActualTimespan = pindexLast->nTime - pindexFirst->nTime;
\r
797 printf(" nActualTimespan = %d before bounds\n", nActualTimespan);
\r
798 if (nActualTimespan < nTargetTimespan/4)
\r
799 nActualTimespan = nTargetTimespan/4;
\r
800 if (nActualTimespan > nTargetTimespan*4)
\r
801 nActualTimespan = nTargetTimespan*4;
\r
805 bnNew.SetCompact(pindexLast->nBits);
\r
806 bnNew *= nActualTimespan;
\r
807 bnNew /= nTargetTimespan;
\r
809 if (bnNew > bnProofOfWorkLimit)
\r
810 bnNew = bnProofOfWorkLimit;
\r
813 printf("GetNextWorkRequired RETARGET\n");
\r
814 printf("nTargetTimespan = %d nActualTimespan = %d\n", nTargetTimespan, nActualTimespan);
\r
815 printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
\r
816 printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
\r
818 return bnNew.GetCompact();
\r
829 bool CTransaction::DisconnectInputs(CTxDB& txdb)
\r
831 // Relinquish previous transactions' spent pointers
\r
834 foreach(const CTxIn& txin, vin)
\r
836 COutPoint prevout = txin.prevout;
\r
838 // Get prev txindex from disk
\r
840 if (!txdb.ReadTxIndex(prevout.hash, txindex))
\r
841 return error("DisconnectInputs() : ReadTxIndex failed");
\r
843 if (prevout.n >= txindex.vSpent.size())
\r
844 return error("DisconnectInputs() : prevout.n out of range");
\r
846 // Mark outpoint as not spent
\r
847 txindex.vSpent[prevout.n].SetNull();
\r
850 txdb.UpdateTxIndex(prevout.hash, txindex);
\r
854 // Remove transaction from index
\r
855 if (!txdb.EraseTxIndex(*this))
\r
856 return error("DisconnectInputs() : EraseTxPos failed");
\r
862 bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx, int nHeight, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee)
\r
864 // Take over previous transactions' spent pointers
\r
867 int64 nValueIn = 0;
\r
868 for (int i = 0; i < vin.size(); i++)
\r
870 COutPoint prevout = vin[i].prevout;
\r
874 bool fFound = true;
\r
875 if (fMiner && mapTestPool.count(prevout.hash))
\r
877 // Get txindex from current proposed changes
\r
878 txindex = mapTestPool[prevout.hash];
\r
882 // Read txindex from txdb
\r
883 fFound = txdb.ReadTxIndex(prevout.hash, txindex);
\r
885 if (!fFound && (fBlock || fMiner))
\r
886 return fMiner ? false : error("ConnectInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
\r
889 CTransaction txPrev;
\r
890 if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
\r
892 // Get prev tx from single transactions in memory
\r
893 CRITICAL_BLOCK(cs_mapTransactions)
\r
895 if (!mapTransactions.count(prevout.hash))
\r
896 return error("ConnectInputs() : %s mapTransactions prev not found %s", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
\r
897 txPrev = mapTransactions[prevout.hash];
\r
900 txindex.vSpent.resize(txPrev.vout.size());
\r
904 // Get prev tx from disk
\r
905 if (!txPrev.ReadFromDisk(txindex.pos))
\r
906 return error("ConnectInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,6).c_str(), prevout.hash.ToString().substr(0,6).c_str());
\r
909 if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
\r
910 return error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,6).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,6).c_str(), txPrev.ToString().c_str());
\r
912 // If prev is coinbase, check that it's matured
\r
913 if (txPrev.IsCoinBase())
\r
914 for (CBlockIndex* pindex = pindexBest; pindex && nBestHeight - pindex->nHeight < COINBASE_MATURITY-1; pindex = pindex->pprev)
\r
915 if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
\r
916 return error("ConnectInputs() : tried to spend coinbase at depth %d", nBestHeight - pindex->nHeight);
\r
918 // Verify signature
\r
919 if (!VerifySignature(txPrev, *this, i))
\r
920 return error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,6).c_str());
\r
922 // Check for conflicts
\r
923 if (!txindex.vSpent[prevout.n].IsNull())
\r
924 return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,6).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
\r
926 // Mark outpoints as spent
\r
927 txindex.vSpent[prevout.n] = posThisTx;
\r
931 txdb.UpdateTxIndex(prevout.hash, txindex);
\r
933 mapTestPool[prevout.hash] = txindex;
\r
935 nValueIn += txPrev.vout[prevout.n].nValue;
\r
938 // Tally transaction fees
\r
939 int64 nTxFee = nValueIn - GetValueOut();
\r
941 return error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,6).c_str());
\r
942 if (nTxFee < nMinFee)
\r
949 // Add transaction to disk index
\r
950 if (!txdb.AddTxIndex(*this, posThisTx, nHeight))
\r
951 return error("ConnectInputs() : AddTxPos failed");
\r
955 // Add transaction to test pool
\r
956 mapTestPool[GetHash()] = CTxIndex(CDiskTxPos(1,1,1), vout.size());
\r
963 bool CTransaction::ClientConnectInputs()
\r
968 // Take over previous transactions' spent pointers
\r
969 CRITICAL_BLOCK(cs_mapTransactions)
\r
971 int64 nValueIn = 0;
\r
972 for (int i = 0; i < vin.size(); i++)
\r
974 // Get prev tx from single transactions in memory
\r
975 COutPoint prevout = vin[i].prevout;
\r
976 if (!mapTransactions.count(prevout.hash))
\r
978 CTransaction& txPrev = mapTransactions[prevout.hash];
\r
980 if (prevout.n >= txPrev.vout.size())
\r
983 // Verify signature
\r
984 if (!VerifySignature(txPrev, *this, i))
\r
985 return error("ConnectInputs() : VerifySignature failed");
\r
987 ///// this is redundant with the mapNextTx stuff, not sure which I want to get rid of
\r
988 ///// this has to go away now that posNext is gone
\r
989 // // Check for conflicts
\r
990 // if (!txPrev.vout[prevout.n].posNext.IsNull())
\r
991 // return error("ConnectInputs() : prev tx already used");
\r
993 // // Flag outpoints as used
\r
994 // txPrev.vout[prevout.n].posNext = posThisTx;
\r
996 nValueIn += txPrev.vout[prevout.n].nValue;
\r
998 if (GetValueOut() > nValueIn)
\r
1008 bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
\r
1010 // Disconnect in reverse order
\r
1011 for (int i = vtx.size()-1; i >= 0; i--)
\r
1012 if (!vtx[i].DisconnectInputs(txdb))
\r
1015 // Update block index on disk without changing it in memory.
\r
1016 // The memory index structure will be changed after the db commits.
\r
1017 if (pindex->pprev)
\r
1019 CDiskBlockIndex blockindexPrev(pindex->pprev);
\r
1020 blockindexPrev.hashNext = 0;
\r
1021 txdb.WriteBlockIndex(blockindexPrev);
\r
1027 bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
\r
1029 //// issue here: it doesn't know the version
\r
1030 unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
\r
1032 map<uint256, CTxIndex> mapUnused;
\r
1034 foreach(CTransaction& tx, vtx)
\r
1036 CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
\r
1037 nTxPos += ::GetSerializeSize(tx, SER_DISK);
\r
1039 if (!tx.ConnectInputs(txdb, mapUnused, posThisTx, pindex->nHeight, nFees, true, false))
\r
1043 if (vtx[0].GetValueOut() > GetBlockValue(nFees))
\r
1046 // Update block index on disk without changing it in memory.
\r
1047 // The memory index structure will be changed after the db commits.
\r
1048 if (pindex->pprev)
\r
1050 CDiskBlockIndex blockindexPrev(pindex->pprev);
\r
1051 blockindexPrev.hashNext = pindex->GetBlockHash();
\r
1052 txdb.WriteBlockIndex(blockindexPrev);
\r
1055 // Watch for transactions paying to me
\r
1056 foreach(CTransaction& tx, vtx)
\r
1057 AddToWalletIfMine(tx, this);
\r
1064 bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
\r
1066 printf("REORGANIZE\n");
\r
1069 CBlockIndex* pfork = pindexBest;
\r
1070 CBlockIndex* plonger = pindexNew;
\r
1071 while (pfork != plonger)
\r
1073 if (!(pfork = pfork->pprev))
\r
1074 return error("Reorganize() : pfork->pprev is null");
\r
1075 while (plonger->nHeight > pfork->nHeight)
\r
1076 if (!(plonger = plonger->pprev))
\r
1077 return error("Reorganize() : plonger->pprev is null");
\r
1080 // List of what to disconnect
\r
1081 vector<CBlockIndex*> vDisconnect;
\r
1082 for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
\r
1083 vDisconnect.push_back(pindex);
\r
1085 // List of what to connect
\r
1086 vector<CBlockIndex*> vConnect;
\r
1087 for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
\r
1088 vConnect.push_back(pindex);
\r
1089 reverse(vConnect.begin(), vConnect.end());
\r
1091 // Disconnect shorter branch
\r
1092 vector<CTransaction> vResurrect;
\r
1093 foreach(CBlockIndex* pindex, vDisconnect)
\r
1096 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
\r
1097 return error("Reorganize() : ReadFromDisk for disconnect failed");
\r
1098 if (!block.DisconnectBlock(txdb, pindex))
\r
1099 return error("Reorganize() : DisconnectBlock failed");
\r
1101 // Queue memory transactions to resurrect
\r
1102 foreach(const CTransaction& tx, block.vtx)
\r
1103 if (!tx.IsCoinBase())
\r
1104 vResurrect.push_back(tx);
\r
1107 // Connect longer branch
\r
1108 vector<CTransaction> vDelete;
\r
1109 for (int i = 0; i < vConnect.size(); i++)
\r
1111 CBlockIndex* pindex = vConnect[i];
\r
1113 if (!block.ReadFromDisk(pindex->nFile, pindex->nBlockPos))
\r
1114 return error("Reorganize() : ReadFromDisk for connect failed");
\r
1115 if (!block.ConnectBlock(txdb, pindex))
\r
1117 // Invalid block, delete the rest of this branch
\r
1119 for (int j = i; j < vConnect.size(); j++)
\r
1121 CBlockIndex* pindex = vConnect[j];
\r
1122 pindex->EraseBlockFromDisk();
\r
1123 txdb.EraseBlockIndex(pindex->GetBlockHash());
\r
1124 mapBlockIndex.erase(pindex->GetBlockHash());
\r
1127 return error("Reorganize() : ConnectBlock failed");
\r
1130 // Queue memory transactions to delete
\r
1131 foreach(const CTransaction& tx, block.vtx)
\r
1132 vDelete.push_back(tx);
\r
1134 if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
\r
1135 return error("Reorganize() : WriteHashBestChain failed");
\r
1137 // Commit now because resurrecting could take some time
\r
1140 // Disconnect shorter branch
\r
1141 foreach(CBlockIndex* pindex, vDisconnect)
\r
1142 if (pindex->pprev)
\r
1143 pindex->pprev->pnext = NULL;
\r
1145 // Connect longer branch
\r
1146 foreach(CBlockIndex* pindex, vConnect)
\r
1147 if (pindex->pprev)
\r
1148 pindex->pprev->pnext = pindex;
\r
1150 // Resurrect memory transactions that were in the disconnected branch
\r
1151 foreach(CTransaction& tx, vResurrect)
\r
1152 tx.AcceptTransaction(txdb, false);
\r
1154 // Delete redundant memory transactions that are in the connected branch
\r
1155 foreach(CTransaction& tx, vDelete)
\r
1156 tx.RemoveFromMemoryPool();
\r
1162 bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
\r
1164 // Check for duplicate
\r
1165 uint256 hash = GetHash();
\r
1166 if (mapBlockIndex.count(hash))
\r
1167 return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,16).c_str());
\r
1169 // Construct new block index object
\r
1170 CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
\r
1172 return error("AddToBlockIndex() : new CBlockIndex failed");
\r
1173 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
\r
1174 pindexNew->phashBlock = &((*mi).first);
\r
1175 map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
\r
1176 if (miPrev != mapBlockIndex.end())
\r
1178 pindexNew->pprev = (*miPrev).second;
\r
1179 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
\r
1184 txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
\r
1187 if (pindexNew->nHeight > nBestHeight)
\r
1189 if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
\r
1191 pindexGenesisBlock = pindexNew;
\r
1192 txdb.WriteHashBestChain(hash);
\r
1194 else if (hashPrevBlock == hashBestChain)
\r
1196 // Adding to current best branch
\r
1197 if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
\r
1200 pindexNew->EraseBlockFromDisk();
\r
1201 mapBlockIndex.erase(pindexNew->GetBlockHash());
\r
1203 return error("AddToBlockIndex() : ConnectBlock failed");
\r
1206 pindexNew->pprev->pnext = pindexNew;
\r
1208 // Delete redundant memory transactions
\r
1209 foreach(CTransaction& tx, vtx)
\r
1210 tx.RemoveFromMemoryPool();
\r
1214 // New best branch
\r
1215 if (!Reorganize(txdb, pindexNew))
\r
1218 return error("AddToBlockIndex() : Reorganize failed");
\r
1223 hashBestChain = hash;
\r
1224 pindexBest = pindexNew;
\r
1225 nBestHeight = pindexBest->nHeight;
\r
1226 nTransactionsUpdated++;
\r
1227 printf("AddToBlockIndex: new best=%s height=%d\n", hashBestChain.ToString().substr(0,16).c_str(), nBestHeight);
\r
1233 if (pindexNew == pindexBest)
\r
1235 // Relay wallet transactions that haven't gotten in yet
\r
1236 RelayWalletTransactions();
\r
1238 // Notify UI to display prev block's coinbase if it was ours
\r
1239 static uint256 hashPrevBestCoinBase;
\r
1240 CRITICAL_BLOCK(cs_mapWallet)
\r
1241 vWalletUpdated.push_back(hashPrevBestCoinBase);
\r
1242 hashPrevBestCoinBase = vtx[0].GetHash();
\r
1245 MainFrameRepaint();
\r
1252 bool CBlock::CheckBlock() const
\r
1254 // These are checks that are independent of context
\r
1255 // that can be verified before saving an orphan block.
\r
1258 if (vtx.empty() || vtx.size() > MAX_SIZE || ::GetSerializeSize(*this, SER_DISK) > MAX_SIZE)
\r
1259 return error("CheckBlock() : size limits failed");
\r
1261 // Check timestamp
\r
1262 if (nTime > GetAdjustedTime() + 2 * 60 * 60)
\r
1263 return error("CheckBlock() : block timestamp too far in the future");
\r
1265 // First transaction must be coinbase, the rest must not be
\r
1266 if (vtx.empty() || !vtx[0].IsCoinBase())
\r
1267 return error("CheckBlock() : first tx is not coinbase");
\r
1268 for (int i = 1; i < vtx.size(); i++)
\r
1269 if (vtx[i].IsCoinBase())
\r
1270 return error("CheckBlock() : more than one coinbase");
\r
1272 // Check transactions
\r
1273 foreach(const CTransaction& tx, vtx)
\r
1274 if (!tx.CheckTransaction())
\r
1275 return error("CheckBlock() : CheckTransaction failed");
\r
1277 // Check proof of work matches claimed amount
\r
1278 if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
\r
1279 return error("CheckBlock() : nBits below minimum work");
\r
1280 if (GetHash() > CBigNum().SetCompact(nBits).getuint256())
\r
1281 return error("CheckBlock() : hash doesn't match nBits");
\r
1283 // Check merkleroot
\r
1284 if (hashMerkleRoot != BuildMerkleTree())
\r
1285 return error("CheckBlock() : hashMerkleRoot mismatch");
\r
1290 bool CBlock::AcceptBlock()
\r
1292 // Check for duplicate
\r
1293 uint256 hash = GetHash();
\r
1294 if (mapBlockIndex.count(hash))
\r
1295 return error("AcceptBlock() : block already in mapBlockIndex");
\r
1297 // Get prev block index
\r
1298 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
\r
1299 if (mi == mapBlockIndex.end())
\r
1300 return error("AcceptBlock() : prev block not found");
\r
1301 CBlockIndex* pindexPrev = (*mi).second;
\r
1303 // Check timestamp against prev
\r
1304 if (nTime <= pindexPrev->GetMedianTimePast())
\r
1305 return error("AcceptBlock() : block's timestamp is too early");
\r
1307 // Check that all transactions are finalized (starting around Mar 2010)
\r
1308 if (nBestHeight > 36000)
\r
1309 foreach(const CTransaction& tx, vtx)
\r
1310 if (!tx.IsFinal(nTime))
\r
1311 return error("AcceptBlock() : contains a non-final transaction");
\r
1313 // Check proof of work
\r
1314 if (nBits != GetNextWorkRequired(pindexPrev))
\r
1315 return error("AcceptBlock() : incorrect proof of work");
\r
1317 // Write block to history file
\r
1318 if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK)))
\r
1319 return error("AcceptBlock() : out of disk space");
\r
1320 unsigned int nFile;
\r
1321 unsigned int nBlockPos;
\r
1322 if (!WriteToDisk(!fClient, nFile, nBlockPos))
\r
1323 return error("AcceptBlock() : WriteToDisk failed");
\r
1324 if (!AddToBlockIndex(nFile, nBlockPos))
\r
1325 return error("AcceptBlock() : AddToBlockIndex failed");
\r
1327 if (hashBestChain == hash && nBestHeight > 28000)
\r
1328 RelayInventory(CInv(MSG_BLOCK, hash));
\r
1330 // // Add atoms to user reviews for coins created
\r
1331 // vector<unsigned char> vchPubKey;
\r
1332 // if (ExtractPubKey(vtx[0].vout[0].scriptPubKey, false, vchPubKey))
\r
1334 // unsigned short nAtom = GetRand(USHRT_MAX - 100) + 100;
\r
1335 // vector<unsigned short> vAtoms(1, nAtom);
\r
1336 // AddAtomsAndPropagate(Hash(vchPubKey.begin(), vchPubKey.end()), vAtoms, true);
\r
1342 bool ProcessBlock(CNode* pfrom, CBlock* pblock)
\r
1344 // Check for duplicate
\r
1345 uint256 hash = pblock->GetHash();
\r
1346 if (mapBlockIndex.count(hash))
\r
1347 return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,16).c_str());
\r
1348 if (mapOrphanBlocks.count(hash))
\r
1349 return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,16).c_str());
\r
1351 // Preliminary checks
\r
1352 if (!pblock->CheckBlock())
\r
1355 return error("ProcessBlock() : CheckBlock FAILED");
\r
1358 // If don't already have its previous block, shunt it off to holding area until we get it
\r
1359 if (!mapBlockIndex.count(pblock->hashPrevBlock))
\r
1361 printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,16).c_str());
\r
1362 mapOrphanBlocks.insert(make_pair(hash, pblock));
\r
1363 mapOrphanBlocksByPrev.insert(make_pair(pblock->hashPrevBlock, pblock));
\r
1365 // Ask this guy to fill in what we're missing
\r
1367 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock));
\r
1372 if (!pblock->AcceptBlock())
\r
1375 return error("ProcessBlock() : AcceptBlock FAILED");
\r
1379 // Recursively process any orphan blocks that depended on this one
\r
1380 vector<uint256> vWorkQueue;
\r
1381 vWorkQueue.push_back(hash);
\r
1382 for (int i = 0; i < vWorkQueue.size(); i++)
\r
1384 uint256 hashPrev = vWorkQueue[i];
\r
1385 for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
\r
1386 mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
\r
1389 CBlock* pblockOrphan = (*mi).second;
\r
1390 if (pblockOrphan->AcceptBlock())
\r
1391 vWorkQueue.push_back(pblockOrphan->GetHash());
\r
1392 mapOrphanBlocks.erase(pblockOrphan->GetHash());
\r
1393 delete pblockOrphan;
\r
1395 mapOrphanBlocksByPrev.erase(hashPrev);
\r
1398 printf("ProcessBlock: ACCEPTED\n");
\r
1409 template<typename Stream>
\r
1410 bool ScanMessageStart(Stream& s)
\r
1412 // Scan ahead to the next pchMessageStart, which should normally be immediately
\r
1413 // at the file pointer. Leaves file pointer at end of pchMessageStart.
\r
1415 short prevmask = s.exceptions(0);
\r
1416 const char* p = BEGIN(pchMessageStart);
\r
1426 s.exceptions(prevmask);
\r
1430 p = BEGIN(pchMessageStart);
\r
1433 if (++p == END(pchMessageStart))
\r
1436 s.exceptions(prevmask);
\r
1445 s.exceptions(prevmask);
\r
1450 bool CheckDiskSpace(int64 nAdditionalBytes)
\r
1453 uint64 nFreeBytesAvailable = 0; // bytes available to caller
\r
1454 uint64 nTotalNumberOfBytes = 0; // bytes on disk
\r
1455 uint64 nTotalNumberOfFreeBytes = 0; // free bytes on disk
\r
1456 if (!GetDiskFreeSpaceEx(GetDataDir().c_str(),
\r
1457 (PULARGE_INTEGER)&nFreeBytesAvailable,
\r
1458 (PULARGE_INTEGER)&nTotalNumberOfBytes,
\r
1459 (PULARGE_INTEGER)&nTotalNumberOfFreeBytes))
\r
1461 printf("ERROR: GetDiskFreeSpaceEx() failed\n");
\r
1465 uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
\r
1468 // Check for 15MB because database could create another 10MB log file at any time
\r
1469 if (nFreeBytesAvailable < (int64)15000000 + nAdditionalBytes)
\r
1472 ThreadSafeMessageBox("Warning: Your disk space is low ", "Bitcoin", wxOK | wxICON_EXCLAMATION);
\r
1473 CreateThread(Shutdown, NULL);
\r
1479 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
\r
1483 FILE* file = fopen(strprintf("%s/blk%04d.dat", GetDataDir().c_str(), nFile).c_str(), pszMode);
\r
1486 if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
\r
1488 if (fseek(file, nBlockPos, SEEK_SET) != 0)
\r
1497 static unsigned int nCurrentBlockFile = 1;
\r
1499 FILE* AppendBlockFile(unsigned int& nFileRet)
\r
1504 FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
\r
1507 if (fseek(file, 0, SEEK_END) != 0)
\r
1509 // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
\r
1510 if (ftell(file) < 0x7F000000 - MAX_SIZE)
\r
1512 nFileRet = nCurrentBlockFile;
\r
1516 nCurrentBlockFile++;
\r
1520 bool LoadBlockIndex(bool fAllowNew)
\r
1523 // Load block index
\r
1526 if (!txdb.LoadBlockIndex())
\r
1531 // Init with genesis block
\r
1533 if (mapBlockIndex.empty())
\r
1540 // GetHash() = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
\r
1541 // hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b
\r
1542 // txNew.vin[0].scriptSig = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E697262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D695420656854
\r
1543 // txNew.vout[0].nValue = 5000000000
\r
1544 // txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG
\r
1545 // block.nVersion = 1
\r
1546 // block.nTime = 1231006505
\r
1547 // block.nBits = 0x1d00ffff
\r
1548 // block.nNonce = 2083236893
\r
1549 // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1)
\r
1550 // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
\r
1551 // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73)
\r
1552 // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B)
\r
1553 // vMerkleTree: 4a5e1e
\r
1556 const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks";
\r
1557 CTransaction txNew;
\r
1558 txNew.vin.resize(1);
\r
1559 txNew.vout.resize(1);
\r
1560 txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
\r
1561 txNew.vout[0].nValue = 50 * COIN;
\r
1562 txNew.vout[0].scriptPubKey = CScript() << CBigNum("0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEAE06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704") << OP_CHECKSIG;
\r
1564 block.vtx.push_back(txNew);
\r
1565 block.hashPrevBlock = 0;
\r
1566 block.hashMerkleRoot = block.BuildMerkleTree();
\r
1567 block.nVersion = 1;
\r
1568 block.nTime = 1231006505;
\r
1569 block.nBits = 0x1d00ffff;
\r
1570 block.nNonce = 2083236893;
\r
1573 printf("%s\n", block.GetHash().ToString().c_str());
\r
1574 printf("%s\n", block.hashMerkleRoot.ToString().c_str());
\r
1575 printf("%s\n", hashGenesisBlock.ToString().c_str());
\r
1576 txNew.vout[0].scriptPubKey.print();
\r
1578 assert(block.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"));
\r
1580 assert(block.GetHash() == hashGenesisBlock);
\r
1582 // Start new block file
\r
1583 unsigned int nFile;
\r
1584 unsigned int nBlockPos;
\r
1585 if (!block.WriteToDisk(!fClient, nFile, nBlockPos))
\r
1586 return error("LoadBlockIndex() : writing genesis block to disk failed");
\r
1587 if (!block.AddToBlockIndex(nFile, nBlockPos))
\r
1588 return error("LoadBlockIndex() : genesis block not accepted");
\r
1596 void PrintBlockTree()
\r
1598 // precompute tree structure
\r
1599 map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
\r
1600 for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
\r
1602 CBlockIndex* pindex = (*mi).second;
\r
1603 mapNext[pindex->pprev].push_back(pindex);
\r
1605 //while (rand() % 3 == 0)
\r
1606 // mapNext[pindex->pprev].push_back(pindex);
\r
1609 vector<pair<int, CBlockIndex*> > vStack;
\r
1610 vStack.push_back(make_pair(0, pindexGenesisBlock));
\r
1613 while (!vStack.empty())
\r
1615 int nCol = vStack.back().first;
\r
1616 CBlockIndex* pindex = vStack.back().second;
\r
1617 vStack.pop_back();
\r
1619 // print split or gap
\r
1620 if (nCol > nPrevCol)
\r
1622 for (int i = 0; i < nCol-1; i++)
\r
1626 else if (nCol < nPrevCol)
\r
1628 for (int i = 0; i < nCol; i++)
\r
1635 for (int i = 0; i < nCol; i++)
\r
1640 block.ReadFromDisk(pindex);
\r
1641 printf("%d (%u,%u) %s %s tx %d",
\r
1644 pindex->nBlockPos,
\r
1645 block.GetHash().ToString().substr(0,16).c_str(),
\r
1646 DateTimeStrFormat("%x %H:%M:%S", block.nTime).c_str(),
\r
1647 block.vtx.size());
\r
1649 CRITICAL_BLOCK(cs_mapWallet)
\r
1651 if (mapWallet.count(block.vtx[0].GetHash()))
\r
1653 CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
\r
1654 printf(" mine: %d %d %d", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
\r
1660 // put the main timechain first
\r
1661 vector<CBlockIndex*>& vNext = mapNext[pindex];
\r
1662 for (int i = 0; i < vNext.size(); i++)
\r
1664 if (vNext[i]->pnext)
\r
1666 swap(vNext[0], vNext[i]);
\r
1671 // iterate children
\r
1672 for (int i = 0; i < vNext.size(); i++)
\r
1673 vStack.push_back(make_pair(nCol+i, vNext[i]));
\r
1686 //////////////////////////////////////////////////////////////////////////////
\r
1692 bool AlreadyHave(CTxDB& txdb, const CInv& inv)
\r
1696 case MSG_TX: return mapTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash);
\r
1697 case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash);
\r
1698 case MSG_REVIEW: return true;
\r
1699 case MSG_PRODUCT: return mapProducts.count(inv.hash);
\r
1701 // Don't know what it is, just say we already got one
\r
1711 bool ProcessMessages(CNode* pfrom)
\r
1713 CDataStream& vRecv = pfrom->vRecv;
\r
1714 if (vRecv.empty())
\r
1717 // printf("ProcessMessages(%d bytes)\n", vRecv.size());
\r
1721 // (4) message start
\r
1729 // Scan for message start
\r
1730 CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
\r
1731 if (vRecv.end() - pstart < sizeof(CMessageHeader))
\r
1733 if (vRecv.size() > sizeof(CMessageHeader))
\r
1735 printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
\r
1736 vRecv.erase(vRecv.begin(), vRecv.end() - sizeof(CMessageHeader));
\r
1740 if (pstart - vRecv.begin() > 0)
\r
1741 printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
\r
1742 vRecv.erase(vRecv.begin(), pstart);
\r
1745 CMessageHeader hdr;
\r
1747 if (!hdr.IsValid())
\r
1749 printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
\r
1752 string strCommand = hdr.GetCommand();
\r
1755 unsigned int nMessageSize = hdr.nMessageSize;
\r
1756 if (nMessageSize > vRecv.size())
\r
1758 // Rewind and wait for rest of message
\r
1759 ///// need a mechanism to give up waiting for overlong message size error
\r
1761 // printf("message-break\n");
\r
1762 vRecv.insert(vRecv.begin(), BEGIN(hdr), END(hdr));
\r
1767 // Copy message to its own buffer
\r
1768 CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
\r
1769 vRecv.ignore(nMessageSize);
\r
1771 // Process message
\r
1772 bool fRet = false;
\r
1775 CRITICAL_BLOCK(cs_main)
\r
1776 fRet = ProcessMessage(pfrom, strCommand, vMsg);
\r
1780 catch (std::ios_base::failure& e)
\r
1782 if (strstr(e.what(), "CDataStream::read() : end of data"))
\r
1784 // Allow exceptions from underlength message on vRecv
\r
1785 printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
\r
1787 else if (strstr(e.what(), ": size too large"))
\r
1789 // Allow exceptions from overlong size
\r
1790 printf("ProcessMessage(%s, %d bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
\r
1794 PrintException(&e, "ProcessMessage()");
\r
1797 catch (std::exception& e) {
\r
1798 PrintException(&e, "ProcessMessage()");
\r
1800 PrintException(NULL, "ProcessMessage()");
\r
1804 printf("ProcessMessage(%s, %d bytes) FAILED\n", strCommand.c_str(), nMessageSize);
\r
1814 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
\r
1816 static map<unsigned int, vector<unsigned char> > mapReuseKey;
\r
1817 RandAddSeedPerfmon();
\r
1819 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
\r
1820 printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
\r
1821 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
\r
1823 printf("dropmessagestest DROPPING RECV MESSAGE\n");
\r
1831 if (strCommand == "version")
\r
1833 // Each connection can only send one version message
\r
1834 if (pfrom->nVersion != 0)
\r
1839 CAddress addrFrom;
\r
1840 uint64 nNonce = 1;
\r
1842 vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
\r
1843 if (pfrom->nVersion >= 106 && !vRecv.empty())
\r
1844 vRecv >> addrFrom >> nNonce;
\r
1845 if (pfrom->nVersion >= 106 && !vRecv.empty())
\r
1846 vRecv >> strSubVer;
\r
1847 if (pfrom->nVersion == 0)
\r
1850 // Disconnect if we connected to ourself
\r
1851 if (nNonce == nLocalHostNonce && nNonce > 1)
\r
1853 pfrom->fDisconnect = true;
\r
1857 pfrom->vSend.SetVersion(min(pfrom->nVersion, VERSION));
\r
1858 pfrom->vRecv.SetVersion(min(pfrom->nVersion, VERSION));
\r
1860 pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
\r
1861 if (pfrom->fClient)
\r
1863 pfrom->vSend.nType |= SER_BLOCKHEADERONLY;
\r
1864 pfrom->vRecv.nType |= SER_BLOCKHEADERONLY;
\r
1867 AddTimeData(pfrom->addr.ip, nTime);
\r
1869 // Ask the first connected node for block updates
\r
1870 static bool fAskedForBlocks;
\r
1871 if (!fAskedForBlocks && !pfrom->fClient)
\r
1873 fAskedForBlocks = true;
\r
1874 pfrom->PushGetBlocks(pindexBest, uint256(0));
\r
1877 pfrom->fSuccessfullyConnected = true;
\r
1879 printf("version message: version %d\n", pfrom->nVersion);
\r
1883 else if (pfrom->nVersion == 0)
\r
1885 // Must have a version message before anything else
\r
1890 else if (strCommand == "addr")
\r
1892 vector<CAddress> vAddr;
\r
1894 if (vAddr.size() > 50000) // lower this to 1000 later
\r
1895 return error("message addr size() = %d", vAddr.size());
\r
1897 // Store the new addresses
\r
1898 foreach(CAddress& addr, vAddr)
\r
1902 addr.nTime = GetAdjustedTime() - 2 * 60 * 60;
\r
1903 if (pfrom->fGetAddr)
\r
1904 addr.nTime -= 5 * 24 * 60 * 60;
\r
1905 AddAddress(addr, false);
\r
1906 pfrom->AddAddressKnown(addr);
\r
1907 if (!pfrom->fGetAddr && addr.IsRoutable())
\r
1909 // Put on lists to send to other nodes
\r
1910 CRITICAL_BLOCK(cs_vNodes)
\r
1911 foreach(CNode* pnode, vNodes)
\r
1912 pnode->PushAddress(addr);
\r
1915 pfrom->fGetAddr = false;
\r
1919 else if (strCommand == "inv")
\r
1921 vector<CInv> vInv;
\r
1923 if (vInv.size() > 50000)
\r
1924 return error("message inv size() = %d", vInv.size());
\r
1927 foreach(const CInv& inv, vInv)
\r
1931 pfrom->AddInventoryKnown(inv);
\r
1933 bool fAlreadyHave = AlreadyHave(txdb, inv);
\r
1934 printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
\r
1936 if (!fAlreadyHave)
\r
1937 pfrom->AskFor(inv);
\r
1938 else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash))
\r
1939 pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
\r
1941 // Track requests for our stuff
\r
1942 CRITICAL_BLOCK(cs_mapRequestCount)
\r
1944 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
\r
1945 if (mi != mapRequestCount.end())
\r
1952 else if (strCommand == "getdata")
\r
1954 vector<CInv> vInv;
\r
1956 if (vInv.size() > 50000)
\r
1957 return error("message getdata size() = %d", vInv.size());
\r
1959 foreach(const CInv& inv, vInv)
\r
1963 printf("received getdata for: %s\n", inv.ToString().c_str());
\r
1965 if (inv.type == MSG_BLOCK)
\r
1967 // Send block from disk
\r
1968 map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
\r
1969 if (mi != mapBlockIndex.end())
\r
1971 //// could optimize this to send header straight from blockindex for client
\r
1973 block.ReadFromDisk((*mi).second, !pfrom->fClient);
\r
1974 pfrom->PushMessage("block", block);
\r
1976 // Trigger them to send a getblocks request for the next batch of inventory
\r
1977 if (inv.hash == pfrom->hashContinue)
\r
1979 // Bypass PushInventory, this must send even if redundant,
\r
1980 // and we want it right after the last block so they don't
\r
1981 // wait for other stuff first.
\r
1982 vector<CInv> vInv;
\r
1983 vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
\r
1984 pfrom->PushMessage("inv", vInv);
\r
1985 pfrom->hashContinue = 0;
\r
1989 else if (inv.IsKnownType())
\r
1991 // Send stream from relay memory
\r
1992 CRITICAL_BLOCK(cs_mapRelay)
\r
1994 map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
\r
1995 if (mi != mapRelay.end())
\r
1996 pfrom->PushMessage(inv.GetCommand(), (*mi).second);
\r
2000 // Track requests for our stuff
\r
2001 CRITICAL_BLOCK(cs_mapRequestCount)
\r
2003 map<uint256, int>::iterator mi = mapRequestCount.find(inv.hash);
\r
2004 if (mi != mapRequestCount.end())
\r
2011 else if (strCommand == "getblocks")
\r
2013 CBlockLocator locator;
\r
2015 vRecv >> locator >> hashStop;
\r
2017 // Find the first block the caller has in the main chain
\r
2018 CBlockIndex* pindex = locator.GetBlockIndex();
\r
2020 // Send the rest of the chain
\r
2022 pindex = pindex->pnext;
\r
2023 int nLimit = 500 + locator.GetDistanceBack();
\r
2024 printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,16).c_str(), nLimit);
\r
2025 for (; pindex; pindex = pindex->pnext)
\r
2027 if (pindex->GetBlockHash() == hashStop)
\r
2029 printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
\r
2032 pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
\r
2033 if (--nLimit <= 0)
\r
2035 // When this block is requested, we'll send an inv that'll make them
\r
2036 // getblocks the next batch of inventory.
\r
2037 printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,16).c_str());
\r
2038 pfrom->hashContinue = pindex->GetBlockHash();
\r
2045 else if (strCommand == "tx")
\r
2047 vector<uint256> vWorkQueue;
\r
2048 CDataStream vMsg(vRecv);
\r
2052 CInv inv(MSG_TX, tx.GetHash());
\r
2053 pfrom->AddInventoryKnown(inv);
\r
2055 bool fMissingInputs = false;
\r
2056 if (tx.AcceptTransaction(true, &fMissingInputs))
\r
2058 AddToWalletIfMine(tx, NULL);
\r
2059 RelayMessage(inv, vMsg);
\r
2060 mapAlreadyAskedFor.erase(inv);
\r
2061 vWorkQueue.push_back(inv.hash);
\r
2063 // Recursively process any orphan transactions that depended on this one
\r
2064 for (int i = 0; i < vWorkQueue.size(); i++)
\r
2066 uint256 hashPrev = vWorkQueue[i];
\r
2067 for (multimap<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev.lower_bound(hashPrev);
\r
2068 mi != mapOrphanTransactionsByPrev.upper_bound(hashPrev);
\r
2071 const CDataStream& vMsg = *((*mi).second);
\r
2073 CDataStream(vMsg) >> tx;
\r
2074 CInv inv(MSG_TX, tx.GetHash());
\r
2076 if (tx.AcceptTransaction(true))
\r
2078 printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
\r
2079 AddToWalletIfMine(tx, NULL);
\r
2080 RelayMessage(inv, vMsg);
\r
2081 mapAlreadyAskedFor.erase(inv);
\r
2082 vWorkQueue.push_back(inv.hash);
\r
2087 foreach(uint256 hash, vWorkQueue)
\r
2088 EraseOrphanTx(hash);
\r
2090 else if (fMissingInputs)
\r
2092 printf("storing orphan tx %s\n", inv.hash.ToString().substr(0,6).c_str());
\r
2093 AddOrphanTx(vMsg);
\r
2098 else if (strCommand == "review")
\r
2100 CDataStream vMsg(vRecv);
\r
2104 CInv inv(MSG_REVIEW, review.GetHash());
\r
2105 pfrom->AddInventoryKnown(inv);
\r
2107 if (review.AcceptReview())
\r
2109 // Relay the original message as-is in case it's a higher version than we know how to parse
\r
2110 RelayMessage(inv, vMsg);
\r
2111 mapAlreadyAskedFor.erase(inv);
\r
2116 else if (strCommand == "block")
\r
2118 auto_ptr<CBlock> pblock(new CBlock);
\r
2122 // printf("received block:\n");
\r
2123 // pblock->print();
\r
2124 printf("received block %s\n", pblock->GetHash().ToString().substr(0,16).c_str());
\r
2126 CInv inv(MSG_BLOCK, pblock->GetHash());
\r
2127 pfrom->AddInventoryKnown(inv);
\r
2129 if (ProcessBlock(pfrom, pblock.release()))
\r
2130 mapAlreadyAskedFor.erase(inv);
\r
2134 else if (strCommand == "getaddr")
\r
2136 pfrom->vAddrToSend.clear();
\r
2137 int64 nSince = GetAdjustedTime() - 5 * 24 * 60 * 60; // in the last 5 days
\r
2138 CRITICAL_BLOCK(cs_mapAddresses)
\r
2140 unsigned int nSize = mapAddresses.size();
\r
2141 foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)
\r
2145 const CAddress& addr = item.second;
\r
2146 if (addr.nTime > nSince)
\r
2147 pfrom->PushAddress(addr);
\r
2153 else if (strCommand == "checkorder")
\r
2155 uint256 hashReply;
\r
2157 vRecv >> hashReply >> order;
\r
2159 /// we have a chance to check the order here
\r
2161 // Keep giving the same key to the same ip until they use it
\r
2162 if (!mapReuseKey.count(pfrom->addr.ip))
\r
2163 mapReuseKey[pfrom->addr.ip] = GenerateNewKey();
\r
2165 // Send back approval of order and pubkey to use
\r
2166 CScript scriptPubKey;
\r
2167 scriptPubKey << mapReuseKey[pfrom->addr.ip] << OP_CHECKSIG;
\r
2168 pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
\r
2172 else if (strCommand == "submitorder")
\r
2174 uint256 hashReply;
\r
2176 vRecv >> hashReply >> wtxNew;
\r
2179 if (!wtxNew.AcceptWalletTransaction())
\r
2181 pfrom->PushMessage("reply", hashReply, (int)1);
\r
2182 return error("submitorder AcceptWalletTransaction() failed, returning error 1");
\r
2184 wtxNew.fTimeReceivedIsTxTime = true;
\r
2185 AddToWallet(wtxNew);
\r
2186 wtxNew.RelayWalletTransaction();
\r
2187 mapReuseKey.erase(pfrom->addr.ip);
\r
2189 // Send back confirmation
\r
2190 pfrom->PushMessage("reply", hashReply, (int)0);
\r
2194 else if (strCommand == "reply")
\r
2196 uint256 hashReply;
\r
2197 vRecv >> hashReply;
\r
2199 CRequestTracker tracker;
\r
2200 CRITICAL_BLOCK(pfrom->cs_mapRequests)
\r
2202 map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
\r
2203 if (mi != pfrom->mapRequests.end())
\r
2205 tracker = (*mi).second;
\r
2206 pfrom->mapRequests.erase(mi);
\r
2209 if (!tracker.IsNull())
\r
2210 tracker.fn(tracker.param1, vRecv);
\r
2214 else if (strCommand == "ping")
\r
2221 // Ignore unknown commands for extensibility
\r
2225 // Update the last seen time for this node's address
\r
2226 if (pfrom->fNetworkNode)
\r
2227 if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
\r
2228 AddressCurrentlyConnected(pfrom->addr);
\r
2242 bool SendMessages(CNode* pto)
\r
2244 CRITICAL_BLOCK(cs_main)
\r
2246 // Don't send anything until we get their version message
\r
2247 if (pto->nVersion == 0)
\r
2250 // Keep-alive ping
\r
2251 if (pto->nLastSend && GetTime() - pto->nLastSend > 12 * 60 && pto->vSend.empty())
\r
2252 pto->PushMessage("ping");
\r
2254 // Address refresh broadcast
\r
2255 static int64 nLastRebroadcast;
\r
2256 if (GetTime() - nLastRebroadcast > 24 * 60 * 60) // every 24 hours
\r
2258 nLastRebroadcast = GetTime();
\r
2259 CRITICAL_BLOCK(cs_vNodes)
\r
2261 foreach(CNode* pnode, vNodes)
\r
2263 // Periodically clear setAddrKnown to allow refresh broadcasts
\r
2264 pnode->setAddrKnown.clear();
\r
2266 // Rebroadcast our address
\r
2267 if (addrLocalHost.IsRoutable() && !fUseProxy)
\r
2268 pnode->PushAddress(addrLocalHost);
\r
2277 vector<CAddress> vAddrToSend;
\r
2278 vAddrToSend.reserve(pto->vAddrToSend.size());
\r
2279 foreach(const CAddress& addr, pto->vAddrToSend)
\r
2281 // returns true if wasn't already contained in the set
\r
2282 if (pto->setAddrKnown.insert(addr).second)
\r
2284 vAddrToSend.push_back(addr);
\r
2285 if (vAddrToSend.size() >= 1000)
\r
2287 pto->PushMessage("addr", vAddrToSend);
\r
2288 vAddrToSend.clear();
\r
2292 pto->vAddrToSend.clear();
\r
2293 if (!vAddrToSend.empty())
\r
2294 pto->PushMessage("addr", vAddrToSend);
\r
2298 // Message: inventory
\r
2300 vector<CInv> vInventoryToSend;
\r
2301 CRITICAL_BLOCK(pto->cs_inventory)
\r
2303 vInventoryToSend.reserve(pto->vInventoryToSend.size());
\r
2304 foreach(const CInv& inv, pto->vInventoryToSend)
\r
2306 // returns true if wasn't already contained in the set
\r
2307 if (pto->setInventoryKnown.insert(inv).second)
\r
2309 vInventoryToSend.push_back(inv);
\r
2310 if (vInventoryToSend.size() >= 1000)
\r
2312 pto->PushMessage("inv", vInventoryToSend);
\r
2313 vInventoryToSend.clear();
\r
2317 pto->vInventoryToSend.clear();
\r
2319 if (!vInventoryToSend.empty())
\r
2320 pto->PushMessage("inv", vInventoryToSend);
\r
2324 // Message: getdata
\r
2326 vector<CInv> vAskFor;
\r
2327 int64 nNow = GetTime() * 1000000;
\r
2329 while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
\r
2331 const CInv& inv = (*pto->mapAskFor.begin()).second;
\r
2332 if (!AlreadyHave(txdb, inv))
\r
2334 printf("sending getdata: %s\n", inv.ToString().c_str());
\r
2335 vAskFor.push_back(inv);
\r
2336 if (vAskFor.size() >= 1000)
\r
2338 pto->PushMessage("getdata", vAskFor);
\r
2342 pto->mapAskFor.erase(pto->mapAskFor.begin());
\r
2344 if (!vAskFor.empty())
\r
2345 pto->PushMessage("getdata", vAskFor);
\r
2364 //////////////////////////////////////////////////////////////////////////////
\r
2369 void GenerateBitcoins(bool fGenerate)
\r
2371 if (fGenerateBitcoins != fGenerate)
\r
2373 fGenerateBitcoins = fGenerate;
\r
2374 CWalletDB().WriteSetting("fGenerateBitcoins", fGenerateBitcoins);
\r
2375 MainFrameRepaint();
\r
2377 if (fGenerateBitcoins)
\r
2379 int nProcessors = wxThread::GetCPUCount();
\r
2380 printf("%d processors\n", nProcessors);
\r
2381 if (nProcessors < 1)
\r
2383 if (fLimitProcessors && nProcessors > nLimitProcessors)
\r
2384 nProcessors = nLimitProcessors;
\r
2385 int nAddThreads = nProcessors - vnThreadsRunning[3];
\r
2386 printf("Starting %d BitcoinMiner threads\n", nAddThreads);
\r
2387 for (int i = 0; i < nAddThreads; i++)
\r
2388 if (!CreateThread(ThreadBitcoinMiner, NULL))
\r
2389 printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
\r
2393 void ThreadBitcoinMiner(void* parg)
\r
2397 vnThreadsRunning[3]++;
\r
2399 vnThreadsRunning[3]--;
\r
2401 catch (std::exception& e) {
\r
2402 vnThreadsRunning[3]--;
\r
2403 PrintException(&e, "ThreadBitcoinMiner()");
\r
2405 vnThreadsRunning[3]--;
\r
2406 PrintException(NULL, "ThreadBitcoinMiner()");
\r
2409 printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[3]);
\r
2412 int FormatHashBlocks(void* pbuffer, unsigned int len)
\r
2414 unsigned char* pdata = (unsigned char*)pbuffer;
\r
2415 unsigned int blocks = 1 + ((len + 8) / 64);
\r
2416 unsigned char* pend = pdata + 64 * blocks;
\r
2417 memset(pdata + len, 0, 64 * blocks - len);
\r
2418 pdata[len] = 0x80;
\r
2419 unsigned int bits = len * 8;
\r
2420 pend[-1] = (bits >> 0) & 0xff;
\r
2421 pend[-2] = (bits >> 8) & 0xff;
\r
2422 pend[-3] = (bits >> 16) & 0xff;
\r
2423 pend[-4] = (bits >> 24) & 0xff;
\r
2427 using CryptoPP::ByteReverse;
\r
2428 static int detectlittleendian = 1;
\r
2430 void BlockSHA256(const void* pin, unsigned int nBlocks, void* pout)
\r
2432 unsigned int* pinput = (unsigned int*)pin;
\r
2433 unsigned int* pstate = (unsigned int*)pout;
\r
2435 CryptoPP::SHA256::InitState(pstate);
\r
2437 if (*(char*)&detectlittleendian != 0)
\r
2439 for (int n = 0; n < nBlocks; n++)
\r
2441 unsigned int pbuf[16];
\r
2442 for (int i = 0; i < 16; i++)
\r
2443 pbuf[i] = ByteReverse(pinput[n * 16 + i]);
\r
2444 CryptoPP::SHA256::Transform(pstate, pbuf);
\r
2446 for (int i = 0; i < 8; i++)
\r
2447 pstate[i] = ByteReverse(pstate[i]);
\r
2451 for (int n = 0; n < nBlocks; n++)
\r
2452 CryptoPP::SHA256::Transform(pstate, pinput + n * 16);
\r
2457 void BitcoinMiner()
\r
2459 printf("BitcoinMiner started\n");
\r
2463 CBigNum bnExtraNonce = 0;
\r
2464 while (fGenerateBitcoins)
\r
2466 SetThreadPriority(THREAD_PRIORITY_LOWEST);
\r
2470 while (vNodes.empty())
\r
2475 if (!fGenerateBitcoins)
\r
2479 unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
\r
2480 CBlockIndex* pindexPrev = pindexBest;
\r
2481 unsigned int nBits = GetNextWorkRequired(pindexPrev);
\r
2485 // Create coinbase tx
\r
2487 CTransaction txNew;
\r
2488 txNew.vin.resize(1);
\r
2489 txNew.vin[0].prevout.SetNull();
\r
2490 txNew.vin[0].scriptSig << nBits << ++bnExtraNonce;
\r
2491 txNew.vout.resize(1);
\r
2492 txNew.vout[0].scriptPubKey << key.GetPubKey() << OP_CHECKSIG;
\r
2496 // Create new block
\r
2498 auto_ptr<CBlock> pblock(new CBlock());
\r
2499 if (!pblock.get())
\r
2502 // Add our coinbase tx as first transaction
\r
2503 pblock->vtx.push_back(txNew);
\r
2505 // Collect the latest transactions into the block
\r
2507 CRITICAL_BLOCK(cs_main)
\r
2508 CRITICAL_BLOCK(cs_mapTransactions)
\r
2511 map<uint256, CTxIndex> mapTestPool;
\r
2512 vector<char> vfAlreadyAdded(mapTransactions.size());
\r
2513 bool fFoundSomething = true;
\r
2514 unsigned int nBlockSize = 0;
\r
2515 while (fFoundSomething && nBlockSize < MAX_SIZE/2)
\r
2517 fFoundSomething = false;
\r
2518 unsigned int n = 0;
\r
2519 for (map<uint256, CTransaction>::iterator mi = mapTransactions.begin(); mi != mapTransactions.end(); ++mi, ++n)
\r
2521 if (vfAlreadyAdded[n])
\r
2523 CTransaction& tx = (*mi).second;
\r
2524 if (tx.IsCoinBase() || !tx.IsFinal())
\r
2527 // Transaction fee based on block size
\r
2528 int64 nMinFee = tx.GetMinFee(nBlockSize);
\r
2530 map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
\r
2531 if (!tx.ConnectInputs(txdb, mapTestPoolTmp, CDiskTxPos(1,1,1), 0, nFees, false, true, nMinFee))
\r
2533 swap(mapTestPool, mapTestPoolTmp);
\r
2535 pblock->vtx.push_back(tx);
\r
2536 nBlockSize += ::GetSerializeSize(tx, SER_NETWORK);
\r
2537 vfAlreadyAdded[n] = true;
\r
2538 fFoundSomething = true;
\r
2542 pblock->nBits = nBits;
\r
2543 pblock->vtx[0].vout[0].nValue = pblock->GetBlockValue(nFees);
\r
2544 printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
\r
2548 // Prebuild hash buffer
\r
2555 uint256 hashPrevBlock;
\r
2556 uint256 hashMerkleRoot;
\r
2557 unsigned int nTime;
\r
2558 unsigned int nBits;
\r
2559 unsigned int nNonce;
\r
2562 unsigned char pchPadding0[64];
\r
2564 unsigned char pchPadding1[64];
\r
2568 tmp.block.nVersion = pblock->nVersion;
\r
2569 tmp.block.hashPrevBlock = pblock->hashPrevBlock = (pindexPrev ? pindexPrev->GetBlockHash() : 0);
\r
2570 tmp.block.hashMerkleRoot = pblock->hashMerkleRoot = pblock->BuildMerkleTree();
\r
2571 tmp.block.nTime = pblock->nTime = max((pindexPrev ? pindexPrev->GetMedianTimePast()+1 : 0), GetAdjustedTime());
\r
2572 tmp.block.nBits = pblock->nBits = nBits;
\r
2573 tmp.block.nNonce = pblock->nNonce = 1;
\r
2575 unsigned int nBlocks0 = FormatHashBlocks(&tmp.block, sizeof(tmp.block));
\r
2576 unsigned int nBlocks1 = FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
\r
2582 int64 nStart = GetTime();
\r
2583 uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
\r
2587 BlockSHA256(&tmp.block, nBlocks0, &tmp.hash1);
\r
2588 BlockSHA256(&tmp.hash1, nBlocks1, &hash);
\r
2590 if (hash <= hashTarget)
\r
2592 pblock->nNonce = tmp.block.nNonce;
\r
2593 assert(hash == pblock->GetHash());
\r
2596 printf("BitcoinMiner:\n");
\r
2597 printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
\r
2600 SetThreadPriority(THREAD_PRIORITY_NORMAL);
\r
2601 CRITICAL_BLOCK(cs_main)
\r
2603 if (pindexPrev == pindexBest)
\r
2610 // Track how many getdata requests this block gets
\r
2611 CRITICAL_BLOCK(cs_mapRequestCount)
\r
2612 mapRequestCount[pblock->GetHash()] = 0;
\r
2614 // Process this block the same as if we had received it from another node
\r
2615 if (!ProcessBlock(NULL, pblock.release()))
\r
2616 printf("ERROR in BitcoinMiner, ProcessBlock, block not accepted\n");
\r
2619 SetThreadPriority(THREAD_PRIORITY_LOWEST);
\r
2625 // Update nTime every few seconds
\r
2626 if ((++tmp.block.nNonce & 0xffff) == 0)
\r
2630 if (!fGenerateBitcoins)
\r
2632 if (fLimitProcessors && vnThreadsRunning[3] > nLimitProcessors)
\r
2634 if (vNodes.empty())
\r
2636 if (tmp.block.nNonce == 0)
\r
2638 if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
\r
2640 if (pindexPrev != pindexBest)
\r
2642 // Pause generating during initial download
\r
2643 if (GetTime() - nStart < 20)
\r
2645 CBlockIndex* pindexTmp;
\r
2648 pindexTmp = pindexBest;
\r
2651 while (pindexTmp != pindexBest);
\r
2655 tmp.block.nTime = pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
\r
2678 //////////////////////////////////////////////////////////////////////////////
\r
2684 int64 GetBalance()
\r
2686 int64 nStart = GetTimeMillis();
\r
2689 CRITICAL_BLOCK(cs_mapWallet)
\r
2691 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
\r
2693 CWalletTx* pcoin = &(*it).second;
\r
2694 if (!pcoin->IsFinal() || pcoin->fSpent)
\r
2696 nTotal += pcoin->GetCredit(true);
\r
2700 //printf("GetBalance() %"PRI64d"ms\n", GetTimeMillis() - nStart);
\r
2706 bool SelectCoins(int64 nTargetValue, set<CWalletTx*>& setCoinsRet)
\r
2708 setCoinsRet.clear();
\r
2710 // List of values less than target
\r
2711 int64 nLowestLarger = INT64_MAX;
\r
2712 CWalletTx* pcoinLowestLarger = NULL;
\r
2713 vector<pair<int64, CWalletTx*> > vValue;
\r
2714 int64 nTotalLower = 0;
\r
2716 CRITICAL_BLOCK(cs_mapWallet)
\r
2718 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
\r
2720 CWalletTx* pcoin = &(*it).second;
\r
2721 if (!pcoin->IsFinal() || pcoin->fSpent)
\r
2723 int64 n = pcoin->GetCredit();
\r
2726 if (n < nTargetValue)
\r
2728 vValue.push_back(make_pair(n, pcoin));
\r
2731 else if (n == nTargetValue)
\r
2733 setCoinsRet.insert(pcoin);
\r
2736 else if (n < nLowestLarger)
\r
2738 nLowestLarger = n;
\r
2739 pcoinLowestLarger = pcoin;
\r
2744 if (nTotalLower < nTargetValue)
\r
2746 if (pcoinLowestLarger == NULL)
\r
2748 setCoinsRet.insert(pcoinLowestLarger);
\r
2752 // Solve subset sum by stochastic approximation
\r
2753 sort(vValue.rbegin(), vValue.rend());
\r
2754 vector<char> vfIncluded;
\r
2755 vector<char> vfBest(vValue.size(), true);
\r
2756 int64 nBest = nTotalLower;
\r
2758 for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++)
\r
2760 vfIncluded.assign(vValue.size(), false);
\r
2762 bool fReachedTarget = false;
\r
2763 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
\r
2765 for (int i = 0; i < vValue.size(); i++)
\r
2767 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
\r
2769 nTotal += vValue[i].first;
\r
2770 vfIncluded[i] = true;
\r
2771 if (nTotal >= nTargetValue)
\r
2773 fReachedTarget = true;
\r
2774 if (nTotal < nBest)
\r
2777 vfBest = vfIncluded;
\r
2779 nTotal -= vValue[i].first;
\r
2780 vfIncluded[i] = false;
\r
2787 // If the next larger is still closer, return it
\r
2788 if (pcoinLowestLarger && nLowestLarger - nTargetValue <= nBest - nTargetValue)
\r
2789 setCoinsRet.insert(pcoinLowestLarger);
\r
2792 for (int i = 0; i < vValue.size(); i++)
\r
2794 setCoinsRet.insert(vValue[i].second);
\r
2797 printf("SelectCoins() best subset: ");
\r
2798 for (int i = 0; i < vValue.size(); i++)
\r
2800 printf("%s ", FormatMoney(vValue[i].first).c_str());
\r
2801 printf("total %s\n", FormatMoney(nBest).c_str());
\r
2810 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CKey& keyRet, int64& nFeeRequiredRet)
\r
2812 nFeeRequiredRet = 0;
\r
2813 CRITICAL_BLOCK(cs_main)
\r
2815 // txdb must be opened before the mapWallet lock
\r
2817 CRITICAL_BLOCK(cs_mapWallet)
\r
2819 int64 nFee = nTransactionFee;
\r
2822 wtxNew.vin.clear();
\r
2823 wtxNew.vout.clear();
\r
2826 int64 nValueOut = nValue;
\r
2827 int64 nTotalValue = nValue + nFee;
\r
2829 // Choose coins to use
\r
2830 set<CWalletTx*> setCoins;
\r
2831 if (!SelectCoins(nTotalValue, setCoins))
\r
2833 int64 nValueIn = 0;
\r
2834 foreach(CWalletTx* pcoin, setCoins)
\r
2835 nValueIn += pcoin->GetCredit();
\r
2837 // Fill a vout to the payee
\r
2838 bool fChangeFirst = GetRand(2);
\r
2839 if (!fChangeFirst)
\r
2840 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
\r
2842 // Fill a vout back to self with any change
\r
2843 if (nValueIn > nTotalValue)
\r
2845 // New private key
\r
2846 if (keyRet.IsNull())
\r
2847 keyRet.MakeNewKey();
\r
2849 // Fill a vout to ourself
\r
2850 CScript scriptPubKey;
\r
2851 scriptPubKey << keyRet.GetPubKey() << OP_CHECKSIG;
\r
2852 wtxNew.vout.push_back(CTxOut(nValueIn - nTotalValue, scriptPubKey));
\r
2855 // Fill a vout to the payee
\r
2857 wtxNew.vout.push_back(CTxOut(nValueOut, scriptPubKey));
\r
2860 foreach(CWalletTx* pcoin, setCoins)
\r
2861 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
\r
2862 if (pcoin->vout[nOut].IsMine())
\r
2863 wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));
\r
2867 foreach(CWalletTx* pcoin, setCoins)
\r
2868 for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
\r
2869 if (pcoin->vout[nOut].IsMine())
\r
2870 SignSignature(*pcoin, wtxNew, nIn++);
\r
2872 // Check that enough fee is included
\r
2873 if (nFee < wtxNew.GetMinFee())
\r
2875 nFee = nFeeRequiredRet = wtxNew.GetMinFee();
\r
2879 // Fill vtxPrev by copying from previous transactions vtxPrev
\r
2880 wtxNew.AddSupportingTransactions(txdb);
\r
2881 wtxNew.fTimeReceivedIsTxTime = true;
\r
2890 // Call after CreateTransaction unless you want to abort
\r
2891 bool CommitTransactionSpent(const CWalletTx& wtxNew, const CKey& key)
\r
2893 CRITICAL_BLOCK(cs_main)
\r
2894 CRITICAL_BLOCK(cs_mapWallet)
\r
2896 //// old: eventually should make this transactional, never want to add a
\r
2897 //// transaction without marking spent transactions, although the risk of
\r
2898 //// interruption during this step is remote.
\r
2899 //// update: This matters even less now that fSpent can get corrected
\r
2900 //// when transactions are seen in VerifySignature. The remote chance of
\r
2901 //// unmarked fSpent will be handled by that. Don't need to make this
\r
2902 //// transactional.
\r
2904 // This is only to keep the database open to defeat the auto-flush for the
\r
2905 // duration of this scope. This is the only place where this optimization
\r
2906 // maybe makes sense; please don't do it anywhere else.
\r
2907 CWalletDB walletdb("r");
\r
2909 // Add the change's private key to wallet
\r
2910 if (!key.IsNull() && !AddKey(key))
\r
2911 throw runtime_error("CommitTransactionSpent() : AddKey failed\n");
\r
2913 // Add tx to wallet, because if it has change it's also ours,
\r
2914 // otherwise just for transaction history.
\r
2915 AddToWallet(wtxNew);
\r
2917 // Mark old coins as spent
\r
2918 set<CWalletTx*> setCoins;
\r
2919 foreach(const CTxIn& txin, wtxNew.vin)
\r
2920 setCoins.insert(&mapWallet[txin.prevout.hash]);
\r
2921 foreach(CWalletTx* pcoin, setCoins)
\r
2923 pcoin->fSpent = true;
\r
2924 pcoin->WriteToDisk();
\r
2925 vWalletUpdated.push_back(pcoin->GetHash());
\r
2928 MainFrameRepaint();
\r
2935 bool SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew)
\r
2937 CRITICAL_BLOCK(cs_main)
\r
2940 int64 nFeeRequired;
\r
2941 if (!CreateTransaction(scriptPubKey, nValue, wtxNew, key, nFeeRequired))
\r
2944 if (nValue + nFeeRequired > GetBalance())
\r
2945 strError = strprintf("Error: This is an oversized transaction that requires a transaction fee of %s ", FormatMoney(nFeeRequired).c_str());
\r
2947 strError = "Error: Transaction creation failed ";
\r
2948 wxMessageBox(strError, "Sending...");
\r
2949 return error("SendMoney() : %s", strError.c_str());
\r
2951 if (!CommitTransactionSpent(wtxNew, key))
\r
2953 wxMessageBox("Error finalizing transaction ", "Sending...");
\r
2954 return error("SendMoney() : Error finalizing transaction");
\r
2957 // Track how many getdata requests our transaction gets
\r
2958 CRITICAL_BLOCK(cs_mapRequestCount)
\r
2959 mapRequestCount[wtxNew.GetHash()] = 0;
\r
2961 printf("SendMoney: %s\n", wtxNew.GetHash().ToString().substr(0,6).c_str());
\r
2964 if (!wtxNew.AcceptTransaction())
\r
2966 // This must not fail. The transaction has already been signed and recorded.
\r
2967 wxMessageBox("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.", "Sending...");
\r
2968 return error("SendMoney() : Error: Transaction not valid");
\r
2970 wtxNew.RelayWalletTransaction();
\r
2972 MainFrameRepaint();
\r